我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用django.utils.datastructures.SortedDict()。
def assemble_schedule(start, end, context_agent=None): processes = Process.objects.unfinished() #import pdb; pdb.set_trace() if start: processes = processes.filter( Q(start_date__range=(start, end)) | Q(end_date__range=(start, end)) | Q(start_date__lt=start, end_date__gt=end)) processes = processes.order_by("context_agent__name", "end_date", "start_date") context_agents = SortedDict() for proc in processes: if context_agent == None: if proc.context_agent not in context_agents: context_agents[proc.context_agent] = [] context_agents[proc.context_agent].append(proc) else: if proc.context_agent == context_agent: if proc.context_agent not in context_agents: context_agents[proc.context_agent] = [] context_agents[proc.context_agent].append(proc) return processes, context_agents
def include_form_fields(form=None, fields=None, as_choice='as_table', global_errors=True): fields=fields.replace(' ', '').split(',') if not global_errors: form.errors[NON_FIELD_ERRORS] = form.error_class() fields_backup = deepcopy(form.fields) form.fields = SortedDict() for field in fields: if field in fields_backup: form.fields[field] = fields_backup[field] resulting_text = getattr(form, as_choice)() form.fields = fields_backup return resulting_text
def safe_summary(self, encoded): from django.contrib.auth.hashers import mask_hash from django.utils.translation import ugettext_noop as _ from django.utils.datastructures import SortedDict handler = self.passlib_handler items = [ # since this is user-facing, we're reporting passlib's name, # without the distracting PASSLIB_HASHER_PREFIX prepended. (_('algorithm'), handler.name), ] if hasattr(handler, "parsehash"): kwds = handler.parsehash(encoded, sanitize=mask_hash) for key, value in iteritems(kwds): key = self._translate_kwds.get(key, key) items.append((_(key), value)) return SortedDict(items) # added in django 1.6
def get_quotas_list(self, date=None): quotas = SortedDict({ "name": self.name, "uuid": self.openstack_tenant, "customer_name": self.customer_name, "customer_id": self.customer_id, "cpu": self.extra.get("cpu"), "cpu_price": self.get_allocation_price("nova.cpu"), "memory": self.extra.get("memory"), "memory_price": self.get_allocation_price("nova.memory"), }) for r_name, resource in six.iteritems(EXTRA_RESOURCES): extra = self.extra.get(r_name) if extra: quotas[r_name] = extra quotas[ r_name + "_price"] = self.get_allocation_price(resource["resource"], resource.get("name", r_name)) return quotas
def group_history_and_messages(history, messages, group_by=None): grouped_history = SortedDict() for a in history: a.extra_messages = {} for m in messages: if a.id == m['alert_history']: if m['state'] not in a.extra_messages: a.extra_messages[m['state']] = { 'sms': None, 'email': None, 'jabber': None, } a.extra_messages[m['state']][m['type']] = m['message'] try: key = GROUPINGS[group_by]['group_by'](a) except AttributeError: key = None if key not in grouped_history: grouped_history[key] = [] grouped_history[key].append(a) return grouped_history
def get_form_list(self): """ This method returns a form_list based on the initial form list but checks if there is a condition method/value in the condition_list. If an entry exists in the condition list, it will call/read the value and respect the result. (True means add the form, False means ignore the form) The form_list is always generated on the fly because condition methods could use data from other (maybe previous forms). """ form_list = SortedDict() for form_key, form_class in six.iteritems(self.form_list): # try to fetch the value from condition list, by default, the form # gets passed to the new list. condition = self.condition_dict.get(form_key, True) if callable(condition): # call the value if needed, passes the current instance. condition = condition(self) if condition: form_list[form_key] = form_class return form_list
def __init__(self, apps=None, *args, **kwargs): # List of locations with static files self.locations = [] # Maps dir paths to an appropriate storage instance self.storages = SortedDict() if not isinstance(settings.STATICFILES_DIRS, (list, tuple)): raise ImproperlyConfigured( "Your STATICFILES_DIRS setting is not a tuple or list; " "perhaps you forgot a trailing comma?") for root in settings.STATICFILES_DIRS: if isinstance(root, (list, tuple)): prefix, root = root else: prefix = '' if os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root): raise ImproperlyConfigured( "The STATICFILES_DIRS setting should " "not contain the STATIC_ROOT setting") if (prefix, root) not in self.locations: self.locations.append((prefix, root)) for prefix, root in self.locations: filesystem_storage = FileSystemStorage(location=root) filesystem_storage.prefix = prefix self.storages[root] = filesystem_storage super(FileSystemFinder, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): super(CachedFilesMixin, self).__init__(*args, **kwargs) try: self.cache = get_cache('staticfiles') except InvalidCacheBackendError: # Use the default backend self.cache = default_cache self._patterns = SortedDict() for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template))
def get_actions(self): if self.actions is None: return SortedDict() actions = [self.get_action(action) for action in self.global_actions] for klass in self.admin_view.__class__.mro()[::-1]: class_actions = getattr(klass, 'actions', []) if not class_actions: continue actions.extend( [self.get_action(action) for action in class_actions]) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into a SortedDict keyed by name. actions = SortedDict([ (name, (ac, name, desc, icon)) for ac, name, desc, icon in actions ]) return actions
def get_queries_by_score(query_string, search_fields, min_len=1): """ Returns a list of queries, with each element being a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields. """ kwargs = {"findterms": re.compile( r'"([^"]+)"|(\S{%d,})' % min_len).findall} if min_len > 1 else {} terms = normalize_query(query_string, **kwargs) query_dict = SortedDict() for score in range(len(terms), 0, -1): queries = None term_combinations = itertools.combinations(terms, score) for term_combination in term_combinations: query = get_query("", search_fields, term_combination) queries = queries | (query) if queries is not None else (query) query_dict.update({score: queries}) return query_dict
def from_response(self, response, allow_text=False): # XXX(dcramer): this doesnt handle leading spaces, but they're not common # paths so its ok if response.text.startswith(u'<?xml'): return XmlApiResponse(response.text, response.headers, response.status_code) elif response.text.startswith('<'): if not allow_text: raise ValueError('Not a valid response type: {}'.format(response.text[:128])) elif response.status_code < 200 or response.status_code >= 300: raise ValueError('Received unexpected plaintext response for code {}'.format( response.status_code, )) return TextApiResponse(response.text, response.headers, response.status_code) # Some APIs will return JSON with an invalid content-type, so we try # to decode it anyways if 'application/json' not in response.headers['Content-Type']: try: data = json.loads(response.text, object_pairs_hook=SortedDict) except (TypeError, ValueError): if allow_text: return TextApiResponse(response.text, response.headers, response.status_code) raise UnsupportedResponseType( response.headers['Content-Type'], response.status_code) else: data = json.loads(response.text, object_pairs_hook=SortedDict) if isinstance(data, dict): return MappingApiResponse(data, response.headers, response.status_code) elif isinstance(data, (list, tuple)): return SequenceApiResponse(data, response.headers, response.status_code) else: raise NotImplementedError
def __init__(self, *args, **kwargs): super(SortedDotDict, self).__init__(*args, **kwargs) self._dict = SortedDict()
def home(request): layout = None try: layout = HomePageLayout.objects.get(id=1) except HomePageLayout.DoesNotExist: pass template_params = { "layout": layout, "photo_size": (128, 128), "help": get_help("home"), } if layout: if layout.use_work_panel: template_params = work_to_do(template_params) if layout.use_needs_panel: #todo: reqs needs a lot of work reqs = Commitment.objects.to_buy() stuff = SortedDict() for req in reqs: if req.resource_type not in stuff: stuff[req.resource_type] = Decimal("0") stuff[req.resource_type] += req.purchase_quantity template_params["stuff_to_buy"] = stuff if layout.use_creations_panel: vcs = Commitment.objects.filter(event_type__relationship="out") value_creations = [] rts = [] for vc in vcs: if vc.fulfilling_events(): if vc.resource_type not in rts: rts.append(vc.resource_type) value_creations.append(vc) template_params["value_creations"] = value_creations return render_to_response("homepage.html", template_params, context_instance=RequestContext(request))
def supply_older(request): mreqs = [] #todo: needs a lot of work mrqs = Commitment.objects.unfinished().filter( event_type__resource_effect="-", event_type__relationship="in").order_by("resource_type__name") suppliers = SortedDict() for commitment in mrqs: if not commitment.resource_type.producing_commitments(): if not commitment.fulfilling_events(): mreqs.append(commitment) sources = commitment.resource_type.producing_agent_relationships().order_by("resource_type__name") for source in sources: agent = source.agent if agent not in suppliers: suppliers[agent] = SortedDict() if source not in suppliers[agent]: suppliers[agent][source] = [] suppliers[agent][source].append(commitment) treqs = [] trqs = Commitment.objects.unfinished().filter( event_type__resource_effect="=", event_type__relationship="in").order_by("resource_type__name") for commitment in trqs: if not commitment.resource_type.producing_commitments(): if not commitment.fulfilling_events(): treqs.append(commitment) sources = commitment.resource_type.producing_agent_relationships().order_by("resource_type__name") for source in sources: agent = source.agent if agent not in suppliers: suppliers[agent] = SortedDict() if source not in suppliers[agent]: suppliers[agent][source] = [] suppliers[agent][source].append(commitment) return render_to_response("valueaccounting/supply.html", { "mreqs": mreqs, "treqs": treqs, "suppliers": suppliers, "help": get_help("supply"), }, context_instance=RequestContext(request))
def supply_old(request): agent = get_agent(request) mreqs = [] mrqs = Commitment.objects.to_buy() suppliers = SortedDict() #supplier_form = AgentSupplierForm(prefix="supplier") for commitment in mrqs: if not commitment.fulfilling_events(): mreqs.append(commitment) sources = commitment.resource_type.producing_agent_relationships().order_by("resource_type__name") for source in sources: agent = source.agent if agent not in suppliers: suppliers[agent] = SortedDict() if source not in suppliers[agent]: suppliers[agent][source] = [] suppliers[agent][source].append(commitment) treqs = [] return render_to_response("valueaccounting/supply.html", { "mreqs": mreqs, "treqs": treqs, "suppliers": suppliers, "agent": agent, #"supplier_form": supplier_form, "help": get_help("supply"), }, context_instance=RequestContext(request))
def supply(request): agent = get_agent(request) mrqs = Commitment.objects.filter( Q(event_type__relationship='consume')|Q(event_type__relationship='use')).order_by("resource_type__name") suppliers = SortedDict() supply = EventType.objects.get(name="Supply") mreqs = [ct for ct in mrqs if ct.quantity_to_buy()] for commitment in mreqs: sources = AgentResourceType.objects.filter( event_type=supply, resource_type=commitment.resource_type) for source in sources: agent = source.agent if agent not in suppliers: suppliers[agent] = SortedDict() if source not in suppliers[agent]: suppliers[agent][source] = [] suppliers[agent][source].append(commitment) #todo: separate tool reqs from material reqs treqs = [] nav_form = SupplyExchangeNavForm(data=request.POST or None) ext = None if request.method == "POST": #import pdb; pdb.set_trace() if nav_form.is_valid(): data = nav_form.cleaned_data ext = data["exchange_type"] if ext: return HttpResponseRedirect('/%s/%s/%s/' % ('accounting/exchange', ext.id, 0)) return render_to_response("valueaccounting/supply.html", { "mreqs": mreqs, "treqs": treqs, "suppliers": suppliers, "agent": agent, "nav_form": nav_form, "help": get_help("supply"), }, context_instance=RequestContext(request))
def tree(self, path=''): qs = self.filter(path__istartswith=path + '/') if path else self.all() out = SortedDict() for i in qs: ref = out col = [] paths = i.path.split('/') for p in paths: if not ref.has_key(p): ref[p] = [None, SortedDict()] col = ref[p] ref = ref[p][1] col[0] = i return out
def create_tracker(active, dns, inactive, ip_range, ip_result): """Creates a result tracker based on form data""" dns_lookups = None if dns: ips_to_lookup = [str(ip) for ip in ip_range] dns_lookups = asyncdns.reverse_lookup(ips_to_lookup) tracker = SortedDict() for ip_key in ip_range: if active and ip_key in ip_result: create_active_row(tracker, dns, dns_lookups, ip_key, ip_result) elif inactive and ip_key not in ip_result: create_inactive_row(tracker, dns, dns_lookups, ip_key) return tracker
def ip_dict(rows): """Converts IP search result rows to a dict keyed by IP addresses. :param rows: IP search result rows. :return: A dict mapping IP addresses to matching result rows. """ result = SortedDict() for row in rows: ip = IP(row.ip) if ip not in result: result[ip] = [] result[ip].append(row) return result
def track_mac(keys, resultset, dns): """Groups results from Query for the mac_search page. keys - a tuple/list with strings that identifies the fields the result should be grouped by resultset - a QuerySet dns - should we lookup the hostname? """ if dns: ips_to_lookup = [row.ip for row in resultset] dns_lookups = asyncdns.reverse_lookup(ips_to_lookup) tracker = SortedDict() for row in resultset: if row.end_time > datetime.now(): row.still_active = "Still active" if dns: ip = row.ip if dns_lookups[ip] and not isinstance(dns_lookups[ip], Exception): row.dns_lookup = dns_lookups[ip].pop() else: row.dns_lookup = "" if not hasattr(row, 'module'): row.module = '' if not hasattr(row, 'port'): row.port = '' key = [] for k in keys: key.append(getattr(row, k)) key = tuple(key) if key not in tracker: tracker[key] = [] tracker[key].append(row) return tracker
def get_declared_fields(bases, attrs, with_base_fields=True): """ Create a list of form field instances from the passed in 'attrs', plus any similar fields on the base classes (in 'bases'). This is used by both the Form and ModelForm metaclasses. If 'with_base_fields' is True, all fields from the bases are used. Otherwise, only fields in the 'declared_fields' attribute on the bases are used. The distinction is useful in ModelForm subclassing. Also integrates any additional media definitions. """ fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)] fields.sort(key=lambda x: x[1].creation_counter) # If this class is subclassing another Form, add that Form's fields. # Note that we loop over the bases in *reverse*. This is necessary in # order to preserve the correct order of fields. if with_base_fields: for base in bases[::-1]: if hasattr(base, 'base_fields'): fields = list(six.iteritems(base.base_fields)) + fields else: for base in bases[::-1]: if hasattr(base, 'declared_fields'): fields = list(six.iteritems(base.declared_fields)) + fields return SortedDict(fields)
def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = SortedDict() field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for DATA_TYPES_REVERSE to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = int(row[3]) if field_type == 'DecimalField': if row[4] is None or row[5] is None: field_notes.append( 'max_digits and decimal_places have been guessed, as this ' 'database handles decimal fields as float') field_params['max_digits'] = row[4] if row[4] is not None else 10 field_params['decimal_places'] = row[5] if row[5] is not None else 5 else: field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes
def safe_summary(self, encoded): algorithm, iterations, salt, hash = encoded.split('$', 3) assert algorithm == self.algorithm return SortedDict([ (_('algorithm'), algorithm), (_('iterations'), iterations), (_('salt'), mask_hash(salt)), (_('hash'), mask_hash(hash)), ])
def safe_summary(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split('$', 4) assert algorithm == self.algorithm salt, checksum = data[:22], data[22:] return SortedDict([ (_('algorithm'), algorithm), (_('work factor'), work_factor), (_('salt'), mask_hash(salt)), (_('checksum'), mask_hash(checksum)), ])
def safe_summary(self, encoded): algorithm, salt, hash = encoded.split('$', 2) assert algorithm == self.algorithm return SortedDict([ (_('algorithm'), algorithm), (_('salt'), mask_hash(salt, show=2)), (_('hash'), mask_hash(hash)), ])
def safe_summary(self, encoded): assert encoded.startswith('sha1$$') hash = encoded[6:] return SortedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(hash)), ])
def safe_summary(self, encoded): return SortedDict([ (_('algorithm'), self.algorithm), (_('hash'), mask_hash(encoded, show=3)), ])
def safe_summary(self, encoded): algorithm, salt, data = encoded.split('$', 2) assert algorithm == self.algorithm return SortedDict([ (_('algorithm'), algorithm), (_('salt'), salt), (_('hash'), mask_hash(data, show=3)), ])
def get_ordering_field_columns(self): """ Returns a SortedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = SortedDict() if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, idx = p.rpartition('-') try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = 'desc' if pfx == '-' else 'asc' return ordering_fields
def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is explicitly set to None that means that we don't # want *any* actions enabled on this page. from django.contrib.admin.views.main import _is_changelist_popup if self.actions is None or _is_changelist_popup(request): return SortedDict() actions = [] # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr(func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) # Then gather them from the model admin and all parent classes, # starting with self and working back up. for klass in self.__class__.mro()[::-1]: class_actions = getattr(klass, 'actions', []) # Avoid trying to iterate over None if not class_actions: continue actions.extend([self.get_action(action) for action in class_actions]) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into a SortedDict keyed by name. actions = SortedDict([ (name, (func, name, desc)) for func, name, desc in actions ]) return actions
def get_ordering_field_columns(self): """ Returns a SortedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = SortedDict() if ORDER_VAR not in self.params or not self.params[ORDER_VAR]: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for attr in self.list_display: if self.get_ordering_field(attr) == field: ordering_fields[field] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, field_name = p.rpartition('-') ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc' return ordering_fields
def get_form_list(self): if not hasattr(self, '_form_list'): init_form_list = SortedDict() assert len( self.wizard_form_list) > 0, 'at least one form is needed' for i, form in enumerate(self.wizard_form_list): init_form_list[unicode(form[0])] = form[1] self._form_list = init_form_list return self._form_list # Plugin replace methods
def get_response(self, __): if self.request.GET.get('_format') == 'html': self.admin_view.detail_template = 'xadmin/views/quick_detail.html' return __() form = self.admin_view.form_obj layout = form.helper.layout results = [] for p, f in layout.get_field_names(): result = self.admin_view.get_field_result(f) results.append((result.label, result.val)) return self.render_response(SortedDict(results))
def get_args_display(self): """Deserialize args dictionary to human readable form""" from django.utils.datastructures import SortedDict result = SortedDict() for key, value in sorted(self.args.items()): result[key] = json.dumps(value) return result
def top_products_by_categories(self, categories=["all"], n=6): products = SortedDict() for cat in categories: products.update({cat: self.top_products_for_category(cat, n)}) return products
def get_template_titles(template_names): """ Looks for title pattern in each template. Returns a dictionary """ templates = SortedDict() for name in template_names: template, source = get_template(name) m = re.search(TITLE_PATTERN, template) title = m.group("title") if m else name templates.update({name: title}) return templates
def _html_output(self, form_as, normal_row, help_text_html, sections_re, row_re): formsets = SortedDict() for bf in self.formsets: if bf.label: label = conditional_escape(force_unicode(bf.label)) # Only add the suffix if the label does not end in # punctuation. if self.form.label_suffix: if label[-1] not in ':?.!': label += self.form.label_suffix label = label or '' else: label = '' if bf.field.help_text: help_text = help_text_html % force_unicode(bf.field.help_text) else: help_text = u'' formsets[bf.name] = {'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text} try: output = [] data = form_as() section_search = sections_re.search(data) if formsets: hidden = u''.join(hidden_re.findall(data)) last_formset_name, last_formset = formsets.items()[-1] last_formset['field'] = last_formset['field'] + hidden formsets[last_formset_name] = normal_row % last_formset for name, formset in formsets.items()[:-1]: formsets[name] = normal_row % formset if not section_search: output.append(data) else: section_groups = section_search.groups() for row, head, item in row_re.findall(section_groups[1]): head_search = label_re.search(head) if head_search: id = head_search.groups()[1] if formsets.has_key(id): row = formsets[id] del formsets[id] output.append(row) for name, row in formsets.items(): if name in self.form.fields.keyOrder: output.append(row) return mark_safe(u'\n'.join(output)) except Exception,e: import traceback return traceback.format_exc()
def handle(self, *args, **options): # ?? admin.loader from django.conf import settings import_module(settings.ROOT_URLCONF) from jiango.admin.loader import loaded_modules perms = SortedDict([('admin.' + codename, u'????|' + name) for codename, name in ADMIN_PERMISSIONS.items()]) for module, app_label in loaded_modules.items(): app_perms = getattr(module, 'PERMISSIONS', {}) verbose_name = getattr(module, 'verbose_name', capfirst(app_label)) if isfunction(verbose_name): verbose_name = verbose_name(None) for codename, name in app_perms.items(): perms['.'.join((app_label, codename))] = '|'.join((verbose_name, name)) # ?????? for i in Permission.objects.all(): # ???? if i.codename in perms: # ???? if perms[i.codename] != i.name: print >>self.stdout, 'rename', i.codename + ':', i.name, '>', perms[i.codename] i.name = perms[i.codename] i.save() del perms[i.codename] # ???? else: # ???? while 1: raw_value = raw_input(i.codename + ': Has not been used to delete? (y/n)') if raw_value.lower() == 'y': i.delete() break if raw_value.lower() == 'n': break # ?????? for codename, name in perms.items(): print >>self.stdout, 'install', codename + ':', name Permission.objects.create(codename=codename, name=name) self.stdout.write("Sync permissions successfully.\n")
def collect(self): """ Perform the bulk of the work of collectstatic. Split off from handle_noargs() to facilitate testing. """ if self.symlink: if sys.platform == 'win32': raise CommandError("Symlinking is not supported by this " "platform (%s)." % sys.platform) if not self.local: raise CommandError("Can't symlink to a remote destination.") if self.clear: self.clear_dir('') if self.symlink: handler = self.link_file else: handler = self.copy_file found_files = SortedDict() for finder in finders.get_finders(): for path, storage in finder.list(self.ignore_patterns): # Prefix the relative path if the source storage contains it if getattr(storage, 'prefix', None): prefixed_path = os.path.join(storage.prefix, path) else: prefixed_path = path if prefixed_path not in found_files: found_files[prefixed_path] = (storage, path) handler(path, prefixed_path, storage) # Here we check if the storage backend has a post_process # method and pass it the list of modified files. if self.post_process and hasattr(self.storage, 'post_process'): processor = self.storage.post_process(found_files, dry_run=self.dry_run) for original_path, processed_path, processed in processor: if isinstance(processed, Exception): self.stderr.write("Post-processing '%s' failed!" % original_path) # Add a blank line before the traceback, otherwise it's # too easy to miss the relevant part of the error message. self.stderr.write("") raise processed if processed: self.log("Post-processed '%s' as '%s'" % (original_path, processed_path), level=1) self.post_processed_files.append(original_path) else: self.log("Skipped post-processing '%s'" % original_path) return { 'modified': self.copied_files + self.symlinked_files, 'unmodified': self.unmodified_files, 'post_processed': self.post_processed_files, }
def handle(self, *app_labels, **options): # Activate project's default language translation.activate(settings.LANGUAGE_CODE) comment = options["comment"] batch_size = options["batch_size"] verbosity = int(options.get("verbosity", 1)) app_list = SortedDict() # if no apps given, use all installed. if len(app_labels) == 0: for app in models.get_apps (): if not app in app_list: app_list[app] = [] for model_class in models.get_models(app): if not model_class in app_list[app]: app_list[app].append(model_class) else: for label in app_labels: try: app_label, model_label = label.split(".") try: app = models.get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) model_class = models.get_model(app_label, model_label) if model_class is None: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) if app in app_list: if app_list[app] and model_class not in app_list[app]: app_list[app].append(model_class) else: app_list[app] = [model_class] except ValueError: # This is just an app - no model qualifier. app_label = label try: app = models.get_app(app_label) if not app in app_list: app_list[app] = [] for model_class in models.get_models(app): if not model_class in app_list[app]: app_list[app].append(model_class) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) # Create revisions. for app, model_classes in app_list.items(): for model_class in model_classes: self.create_initial_revisions(app, model_class, comment, batch_size, verbosity) # Go back to default language translation.deactivate()