code
stringlengths
1
18.2k
def once(self): """ Inspected function should be called one time Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledOnce self.valid_list.append(check) return self
def twice(self): """ Inspected function should be called two times Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledTwice self.valid_list.append(check) return self
def thrice(self): """ Inspected function should be called three times Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledThrice self.valid_list.append(check) return self
def exactly(self, number): """ Inspected function should be called exactly number times Return: self """ def check(): #pylint: disable=missing-docstring return True if number == super(SinonExpectation, self).callCount else False self.valid_list.append(check) return self
def withArgs(self, *args, **kwargs): #pylint: disable=invalid-name """ Inspected function should be called with some of specified arguments Args: any Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledWith(*args, **kwargs) self.valid_list.append(check) return sel...
def withExactArgs(self, *args, **kwargs): #pylint: disable=invalid-name """ Inspected function should be called with full of specified arguments Args: any Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledWithExactly(*args, **kwargs) self.valid_list.append(check...
def verify(self): """ Running all conditions in the instance variable valid_list Return: True: pass all conditions False: fail at more than one condition """ if self not in self._queue: return False valid = True for check in self.valid_list: valid = valid & check() return valid
def expects(self, prop): """ Adding new property of object as inspector into exp_list Args: string (property of object) Return: SinonExpectation """ expectation = SinonExpectation(self.obj, prop) self.exp_list.append(expectation) return expectation
def verify(self): """ Verifying all inspectors in exp_list Return: True: pass all inspectors False: fail at more than one inspector """ for expectation in self.exp_list: if hasattr(expectation, "verify") and not expectation.verify(): return False return True
def restore(self): """ Destroy all inspectors in exp_list and SinonMock itself """ for expectation in self.exp_list: try: expectation.restore() except ReferenceError: pass #ignore removed expectation self._queue.remove(self)
def google_app_engine_ndb_delete_expired_sessions(dormant_for=86400, limit=500): """ Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, defaults to 24 hours. :...
def google_cloud_datastore_delete_expired_sessions(dormant_for=86400, limit=500): """ Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, defaults to 24 hours. ...
accessed_results: keys.append(result.key) for result in expires_results: if result.key not in keys: keys.append(result.key) client.delete_multi(keys) return len(keys) < limit
def values(self, name): """ RETURN VALUES FOR THE GIVEN PATH NAME :param name: :return: """ return list(self.lookup_variables.get(unnest_path(name), Null))
def leaves(self, name): """ RETURN LEAVES OF GIVEN PATH NAME pull leaves, considering query_path and namespace pull all first-level properties pull leaves, including parent leaves pull the head of any tree by name :param name: :return: """ return list(self.lookup_leaves.get(unnest_path(name), Null))
def map_to_es(self): """ RETURN A MAP FROM THE NAMESPACE TO THE es_column NAME """ full_name = self.query_path return set_default( { relative_field(c.name, full_name): c.es_column for k, cs in self.lookup.items() # if startswith_field(k, full_name) for c in cs if c.jx_type not in STRUCT }, { c.name: c.es_column for k, ...
def get_version_from_dirname(name, parent): """Extracted sdist""" parent = parent.resolve() logger.info(f"dirname: Trying to get version of {name} from dirname {parent}") name_re = name.replace("_", "[_-]") re_dirname = re.compile(f"{name_re}-{RE_VERSION}$") if not re_dirname.match(parent.name): logger.info(f"dirname: ...
def execute_by_options(args): """execute by argument dictionary Args: args (dict): command line argument dictionary """ if args['subcommand'] == 'sphinx': s = Sphinx(proj_info) if args['quickstart']: s.quickstart() elif args['gen_code_api']: s.gen_code_api() elif args['rst2html']: s.rst2html() pass elif args['subcomman...
def editline_with_regex(self, regex_tgtline, to_replace): """find the first matched line, then replace Args: regex_tgtline (str): regular expression used to match the target line to_replace (str): line you wanna use to replace """ for idx, line in enumerate(self._swp_lines): mobj = re.match(regex_tgtline, line) if mobj...
def gen_code_api(self): """TODO: Docstring for gen_code_api.""" # edit config file conf_editor = Editor(self.conf_fpath) # insert code path for searching conf_editor.editline_with_regex(r'^# import os', 'import os') conf_editor.editline_with_regex(r'^# import sys', 'import sys') conf_editor.editline_with_regex( r'^# sy...
def wrap_spy(function, owner=None): """ Surrounds the given 'function' with a spy wrapper that tracks usage data, such as: * call count * arguments it was called with * keyword argument it was called with * return values * etc. Parameters: function: function, could be one of 3 things: 1. the original function the user ...
""" def __set__(value, new_list): """ For python 2.x compatibility """ setattr(wrapped, value, new_list) def wrapped(*args, **kwargs): """ Fully manipulatable inspector function """ if owner: if len(args) > 0: if owner == args[0].__class__: args = args[1:] wrapped.callCount += 1 wrapped.args_list.append(args) wrapped.k...
def save(self, sync_only=False): """ :param sync_only: :type: bool """ entity = datastore.Entity(key=self._key) entity["last_accessed"] = self.last_accessed # todo: restore sync only entity["data"] = self._data if self.expires: entity["expires"] = self.expires self._client.put(entity)
def __default_custom_function(self, *args, **kwargs): """ If the user does not specify a custom function with which to replace the original, then this is the function that we shall use. This function allows the user to call returns/throws to customize the return value. Args: args: tuple, the arguments inputed by the us...
def __get_matching_indices(self, args, kwargs, args_list, kwargs_list): """ Args: args: tuple, the arguments inputed by the user kwargs: dictionary, the keyword arguments inputed by the user args_list: list, a list of argument tuples kwargs_list: list, a list of keyword argument dictionaries Returns: list, the list of ...
x in enumerate(kwargs_list) if x == kwargs and not args_list[i]] else: return []
def __get_matching_withargs_indices(self, *args, **kwargs): """ Args: args: tuple, the arguments inputed by the user kwargs: dictionary, the keyword arguments inputed by the user Returns: list, the list of indices in conditions for which the user args/kwargs match """ return self.__get_matching_indices(args, kwargs, se...
def __get_call_count(self, args, kwargs, args_list, kwargs_list): """ Args: args: tuple, the arguments inputed by the user kwargs: dictionary, the keyword arguments inputed by the user args_list: list, the tuples of args from all the times this stub was called kwargs_list: list, the dictionaries of kwargs from all the ...
def __get_return_value_withargs(self, index_list, *args, **kwargs): """ Pre-conditions: (1) The user has created a stub and specified the stub behaviour (2) The user has called the stub function with the specified "args" and "kwargs" (3) One or more 'withArgs' conditions were applicable in this case Args: index_list: l...
if there are any combined withArgs+onCall conditions if indices_with_oncall: call_count = self.__get_call_count(args, kwargs, args_list, kwargs_list) for i in indices_with_oncall: if c["oncall"][i] == call_count: return c["action"][i](*args, **kwargs) # else if there are simple withArgs conditions indices_without_oncal...
def __get_return_value_no_withargs(self, *args, **kwargs): """ Pre-conditions: (1) The user has created a stub and specified the stub behaviour (2) The user has called the stub function with the specified "args" and "kwargs" (3) No 'withArgs' conditions were applicable in this case Args: args: tuple, the arguments inpu...
# else all conditions did not match return c["default"](*args, **kwargs)
def _append_condition(self, sinon_stub_condition, func): ''' Permanently saves the current (volatile) conditions, which would be otherwise lost In the _conditions dictionary, the keys "args", "kwargs", "oncall" and "action" each refer to a list. All 4 lists have a value appended each time the user calls returns or thro...
self._conditions["oncall"].append(sinon_stub_condition._oncall) self._conditions["action"].append(func)
def withArgs(self, *args, **kwargs): #pylint: disable=invalid-name """ Adds a condition for when the stub is called. When the condition is met, a special return value can be returned. Adds the specified argument(s) into the condition list. For example, when the stub function is called with argument 1, it will return "#...
def onCall(self, n): #pylint: disable=invalid-name """ Adds a condition for when the stub is called. When the condition is met, a special return value can be returned. Adds the specified call number into the condition list. For example, when the stub function is called the second time, it will return "#": stub.onCall(1...
def throws(self, exception=Exception): """ Customizes the stub function to raise an exception. If conditions like withArgs or onCall were specified, then the return value will only be returned when the conditions are met. Args: exception (by default=Exception, it could be any customized exception) Return: a SinonStub o...
def returns(self, obj): """ Customizes the return values of the stub function. If conditions like withArgs or onCall were specified, then the return value will only be returned when the conditions are met. Args: obj (anything) Return: a SinonStub object (able to be chained) """ self._copy._append_condition(self, lambda...
def throws(self, exception=Exception): """ Customizes the stub function to raise an exception. If conditions like withArgs or onCall were specified, then the return value will only be returned when the conditions are met. Args: exception (by default=Exception, it could be any customized exception) Return: a SinonStub o...
def humanize_api_path(api_path): """ Converts an API path to a humaized string, for example: # >>> In [2]: humanize_api_path('/api/vlan/{id}') # >>> Out[2]: u'ApiVlanId' Parameters ---------- api_path : str An API path string. Returns ------- str - humazined form. """ return reduce(lambda val, func: func(val), [paramet...
def modeltag_nonref_schemas(spec): """ This function will go through the OpenAPI 'paths' and look for any command parameters that have non "$ref" schemas defined. If the parameter does have a $ref schema, then the bravado library will do this x-model tagging. But it does not do it for schemas that are defined inside th...
model_name = (camelize(cmd_data.get('operationId')) or "%s%s" % (path_cmd.upper(), humanize_api_path(path_name))) schema[MODEL_MARKER] = "%s%s" % (model_name, MODEL_NAME_SUFFIX)
def assign_operation_ids(spec, operids): """ used to assign caller provided operationId values into a spec """ empty_dict = {} for path_name, path_data in six.iteritems(spec['paths']): for method, method_data in six.iteritems(path_data): oper_id = operids.get(path_name, empty_dict).get(method) if oper_id: method_data['...
def pretty_print(self, printer: Optional[Printer] = None, align: int = ALIGN_CENTER, border: bool = False): """ Pretty prints the table. :param printer: The printer to print with. :param align: The alignment of the cells(Table.ALIGN_CENTER/ALIGN_LEFT/ALIGN_RIGHT) :param border: Whether to add a border around the table ...
def rows(self) -> List[List[str]]: """ Returns the table rows. """ return [list(d.values()) for d in self.data]
def set_column_size_limit(self, column_name: str, size_limit: int): """ Sets the size limit of a specific column. :param column_name: The name of the column to change. :param size_limit: The max size of the column width. """ if self._column_size_map.get(column_name): self._column_size_map[column_name] = size_limit else...
def _get_pretty_table(self, indent: int = 0, align: int = ALIGN_CENTER, border: bool = False) -> PrettyTable: """ Returns the table format of the scheme, i.e.: <table name> +----------------+---------------- | <field1> | <field2>... +----------------+---------------- | value1(field1) | value1(field2) | value2(field1) |...
the max width according to the columns size dict, or by default size limit when columns were not provided. for column, max_width in self._column_size_map.items(): table.max_width[column] = max_width return table
def get_as_html(self) -> str: """ Returns the table object as an HTML string. :return: HTML representation of the table. """ table_string = self._get_pretty_table().get_html_string() title = ('{:^' + str(len(table_string.splitlines()[0])) + '}').format(self.title) return f'<center><h1>{title}</h1></center>{table_string...
def get_as_csv(self, output_file_path: Optional[str] = None) -> str: """ Returns the table object as a CSV string. :param output_file_path: The output file to save the CSV to, or None. :return: CSV representation of the table. """ output = StringIO() if not output_file_path else open(output_file_path, 'w') try: csv_wri...
def schedule(self, when=None, action=None, **kwargs): """ Schedule an update of this object. when: The date for the update. action: if provided it will be looked up on the implementing class and called with **kwargs. If action is not provided each k/v pair in kwargs will be set on self and then self is saved. kwargs: a...
def do_scheduled_update(self, action, **kwargs): """ Do the actual update. action: if provided it will be looked up on the implementing class and called with **kwargs. If action is not provided each k/v pair in kwargs will be set on self and then self is saved. kwargs: any other you passed for this update passed along ...
def get_md5_hash(file_path): """ Calculate the MD5 checksum for a file. :param string file_path: Path to the file :return: MD5 checksum """ checksum = hashlib.md5() with open(file_path, 'rb') as f: for chunk in iter(lambda: f.read(128 * checksum.block_size), b''): checksum.update(chunk) return checksum.hexdigest()
def as_dict(self): """ Convert this FileRecordSearch to a dict, ready for serialization to JSON for use in the API. :return: Dict representation of this FileRecordSearch instance """ d = {} _add_value(d, 'obstory_ids', self.obstory_ids) _add_value(d, 'lat_min', self.lat_min) _add_value(d, 'lat_max', self.lat_max) _add_...
def from_dict(d): """ Builds a new instance of FileRecordSearch from a dict :param Object d: the dict to parse :return: a new FileRecordSearch based on the supplied dict """ obstory_ids = _value_from_dict(d, 'obstory_ids') lat_min = _value_from_dict(d, 'lat_min') lat_max = _value_from_dict(d, 'lat_max') long_min = _val...
def as_dict(self): """ Convert this ObservationGroupSearch to a dict, ready for serialization to JSON for use in the API. :return: Dict representation of this ObservationGroupSearch instance """ d = {} _add_string(d, 'obstory_name', self.obstory_name) _add_string(d, 'semantic_type', self.semantic_type) _add_value(d, 't...
def as_dict(self): """ Convert this ObservatoryMetadataSearch to a dict, ready for serialization to JSON for use in the API. :return: Dict representation of this ObservatoryMetadataSearch instance """ d = {} _add_value(d, 'obstory_ids', self.obstory_ids) _add_string(d, 'field_name', self.field_name) _add_value(d, 'lat_...
def type(self): """Returns 'number', 'string', 'date' or 'unknown' based on the type of the value""" if isinstance(self.value, numbers.Number): return "number" if isinstance(self.value, basestring): return "string" return "unknown"
def _data(self): """Read data from the file.""" current_position = self.file.tell() self.file.seek(self.position) data = self.file.read(self.length) self.file.seek(current_position) if self.length % 2: data += '\x00' # Padding byte return data
def find(self, header, list_type=None): """Find the first chunk with specified header and optional list type.""" for chunk in self: if chunk.header == header and (list_type is None or (header in list_headers and chunk.type == list_type)): return chunk elif chunk.header in list_headers: try: result = chunk.find(header, ...
def find_all(self, header, list_type=None): """Find all direct children with header and optional list type.""" found = [] for chunk in self: if chunk.header == header and (not list_type or (header in list_headers and chunk.type == list_type)): found.append(chunk) return found
def replace(self, child, replacement): """Replace a child chunk with something else.""" for i in range(len(self.chunks)): if self.chunks[i] == child: self.chunks[i] = replacement
def remove(self, child): """Remove a child element.""" for i in range(len(self)): if self[i] == child: del self[i]
def from_data(data): """Create a chunk from data including header and length bytes.""" header, length = struct.unpack('4s<I', data[:8]) data = data[8:] return RiffDataChunk(header, data)
def get_urls(self): """Add our dashboard view to the admin urlconf. Deleted the default index.""" from django.conf.urls import patterns, url from views import DashboardWelcomeView urls = super(AdminMixin, self).get_urls() del urls[0] custom_url = patterns( '', url(r'^$', self.admin_view(DashboardWelcomeView.as_view()),...
def index_to_coordinate(dims): """ RETURN A FUNCTION THAT WILL TAKE AN INDEX, AND MAP IT TO A coordinate IN dims :param dims: TUPLE WITH NUMBER OF POINTS IN EACH DIMENSION :return: FUNCTION """ _ = divmod # SO WE KEEP THE IMPORT num_dims = len(dims) if num_dims == 0: return _zero_dim prod = [1] * num_dims acc = 1 domai...
+ "\treturn " + coords[0] + "," ) else: code = ( "def output(index):\n" + "\n".join(commands) + "\n" + "\treturn " + ", ".join(coords) ) exec(code) return output
def groupby(self, io_select): """ SLICE THIS MATRIX INTO ONES WITH LESS DIMENSIONALITY io_select - 1 IF GROUPING BY THIS DIMENSION, 0 IF FLATTENING return - """ # offsets WILL SERVE TO MASK DIMS WE ARE NOT GROUPING BY, AND SERVE AS RELATIVE INDEX FOR EACH COORDINATE offsets = [] new_dim = [] acc = 1 for i, d in reverse...
tuple(), []) return output
def forall(self, method): """ IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE value - VALUE FOUND AT ELEMENT coord - THE COORDINATES OF THE ELEMENT (PLEASE, READ ONLY) cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS """ for c in self._all_combos(): method(self[c], c, self.cube)
def items(self): """ ITERATE THROUGH ALL coord, value PAIRS """ for c in self._all_combos(): _, value = _getitem(self.cube, c) yield c, value
def _all_combos(self): """ RETURN AN ITERATOR OF ALL COORDINATES """ combos = _product(self.dims) if not combos: return calc = [(coalesce(_product(self.dims[i+1:]), 1), mm) for i, mm in enumerate(self.dims)] for c in xrange(combos): yield tuple(int(c / dd) % mm for dd, mm in calc)
def send(self, topic, message): """Publishes a pulse message to the proper exchange.""" if not message: Log.error("Expecting a message") message._prepare() if not self.connection: self.connect() producer = Producer( channel=self.connection, exchange=Exchange(self.settings.exchange, type='topic'), routing_key=topic ) # ...
def add_child(self, child): """ Add a child to the tree. Extends discards all comments and whitespace Text. On non-whitespace Text, and any other nodes, raise a syntax error. """ if isinstance(child, Comment): return # ignore Text nodes with whitespace-only content if isinstance(child, Text) and not child.text.strip():...
def query(self, command): """ WILL BLOCK CALLING THREAD UNTIL THE command IS COMPLETED :param command: COMMAND FOR SQLITE :return: list OF RESULTS """ if self.closed: Log.error("database is closed") signal = _allocate_lock() signal.acquire() result = Data() trace = extract_stack(1) if self.get_trace else None if self.g...
def close(self): """ OPTIONAL COMMIT-AND-CLOSE IF THIS IS NOT DONE, THEN THE THREAD THAT SPAWNED THIS INSTANCE :return: """ self.closed = True signal = _allocate_lock() signal.acquire() self.queue.add(CommandItem(COMMIT, None, signal, None, None)) signal.acquire() self.worker.please_stop.go() return
def handle_next_export(self): """ Retrieve and fully evaluate the next export task, including resolution of any sub-tasks requested by the import client such as requests for binary data, observation, etc. :return: An instance of ExportStateCache, the 'state' field contains the state of the export after running as many ...
while True: state = self._handle_next_export_subtask(export_state=state) if state is None: return None elif state.export_task is None: return state
def _handle_next_export_subtask(self, export_state=None): """ Process the next export sub-task, if there is one. :param ExportState export_state: If provided, this is used instead of the database queue, in effect directing the exporter to process the previous export again. This is used to avoid having to query the data...
= (export_state.export_task.target_user, export_state.export_task.target_password) target_url = export_state.export_task.target_url response = post(url=target_url, verify=False, json=export_state.entity_dict, auth=auth) response.raise_for_status() json = response.json() state = json['state'] if state == 'complete': ret...
def extract_options_dict(template, options): """Extract options from a dictionary against the template""" for option, val in template.items(): if options and option in options: yield option, options[option] else: yield option, Default(template[option]['default'](os.environ))
def modify_macho_file_headers(macho_file_path, modificator_func): """ Modifies headers of a Mach-O file at the given path by calling the modificator function on each header. Returns True on success, otherwise rises an exeption (e.g. from macholib) """ if not os.path.isfile(macho_file_path): raise Exception("You must sp...
def ia_credentials_helper(client_id, client_secret, credentials_cache_file="credentials.json", cache_key="default"): """Helper function to manage a credentials cache during testing. This function attempts to load and refresh a credentials object from a json cache file, using the cache_key and client_id as a lookup. If ...
cache = json.load(inf) cred_json = cache[key] return OAuth2Credentials.from_json(cred_json) def _save_credentials(key, credentials): cache = {} try: with open(credentials_cache_file, 'rb') as inf: cache = json.load(inf) except (IOError, ValueError), e: pass cache[key] = credentials.to_json() with open(credentials_cache...
def backup(self, backup_name, folder_key=None, folder_name=None): """Copies the google spreadsheet to the backup_name and folder specified. Args: backup_name (str): The name of the backup document to create. folder_key (Optional) (str): The key of a folder that the new copy will be moved to. folder_name (Optional) (str...
def data(self, as_cells=False): """ Reads the worksheet and returns an indexed dictionary of the row objects. For example: >>>print sheet.data() {'Miss Piggy': {'Color': 'Pink', 'Performer': 'Frank Oz'}, 'Kermit': {'Color': 'Green', 'Performer': 'Jim Henson'}} """ sheet_data = {} self.max_row = max(self.header_row_ix, ...
h.split("-")[1].isdigit()] logger.info("Assumed key column headers were: %s", self.key_column_headers) else: raise Exception("Unable to read spreadsheet. Specify" "key_column_headers when initializing Sheet object.") key_list = [] for key_hdr in self.key_column_headers: key_val = wks_row.db.get(key_hdr,"") if key_val.s...
def sync(self, raw_data, row_change_callback=None): """ Equivalent to the inject method but will delete rows from the google spreadsheet if their key is not found in the input (raw_data) dictionary. Args: raw_data (dict): See inject method row_change_callback (Optional) (func): See inject method Returns: UpdateResults ...
def inject(self, raw_data, row_change_callback=None): """ Use this function to add rows or update existing rows in the spreadsheet. Args: raw_data (dict): A dictionary of dictionaries. Where the keys of the outer dictionary uniquely identify each row of data, and the inner dictionaries represent the field,value pairs f...
def is_module_function(obj, prop): """ Checking and setting type to MODULE_FUNCTION Args: obj: ModuleType prop: FunctionType Return: Boolean Raise: prop_type_error: When the type of prop is not valid prop_in_obj_error: When prop is not in the obj(module/class) prop_is_func_error: When prop is not a callable stuff """ p...
def is_module(obj): """ Checking and setting type to MODULE Args: obj: ModuleType / class Note: An instance will be treated as a Class Return: Boolean """ return True if obj and isinstance(obj, ModuleType) or inspect.isclass(obj) else False
def from_apps(cls, apps): "Takes in an Apps and returns a VersionedProjectState matching it" app_models = {} for model in apps.get_models(include_swapped=True): model_state = VersionedModelState.from_model(model) app_models[(model_state.app_label, model_state.name.lower())] = model_state return cls(app_models)
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders data to HTML, using Django's standard template rendering. The template name is determined by (in order of preference): 1. An explicit .template_name set on the response. 2. An explicit .template_name set on this class. 3. The return re...
try: marker_template = Template(getattr(obj, 'marker_template', None)) except TemplateSyntaxError as exception: marker_template = Template(exception) if isinstance(data, dict): features.append(self.process_feature(data, popup_template, marker_template)) else: for feature in data: features.append(self.process_feature(fe...
def search_tags(self, tags): """ Search assets by passing a list of one or more tags. """ qs = self.filter(tags__name__in=tags).order_by('file').distinct() return qs
def _gather_reverses(self): """ Get all the related objects that point to this object that we need to clone. Uses self.clone_related to find those objects. """ old_reverses = {'m2m': {}, 'reverse': {}} for reverse in self.clone_related: ctype, name, l = self._gather_reverse(reverse) old_reverses[ctype][reverse] = (name...
def _set_m2ms(self, old_m2ms): """ Creates the same m2m relationships that the old object had. """ for k, v in old_m2ms.items(): if v: setattr(self, k, v)
def _clone_reverses(self, old_reverses): """ Clones all the objects that were previously gathered. """ for ctype, reverses in old_reverses.items(): for parts in reverses.values(): sub_objs = parts[1] field_name = parts[0] attrs = {} for sub_obj in sub_objs: if ctype != 'm2m' and not attrs: field = sub_obj._meta.get_fie...
def _clone(self, **attrs): """ Makes a copy of an model instance. for every key in **attrs value will be set on the new instance. """ with xact(): # Gather objs we'll need save after old_m2ms = self._gather_m2ms() old_reverses = self._gather_reverses() for k, v in attrs.items(): setattr(self, k, v) # Do the clone self....
def _delete_reverses(self): """ Delete all objects that would have been cloned on a clone command. This is done separately because there may be m2m and other relationships that would have not been deleted otherwise. """ for reverse in self.clone_related: self._delete_reverse(reverse) for field in self._meta.local_many_...