我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.encoding.smart_unicode()。
def posix_shell(chan,channel,log_name=None,width=90,height=40): from OpsManage.asgi import channel_layer stdout = list() begin_time = time.time() last_write_time = {'last_activity_time':begin_time} try: chan.settimeout(0.0) while True: try: x = u(chan.recv(1024)) if len(x) == 0: channel_layer.send(channel, {'text': json.dumps(['disconnect',smart_unicode('\r\n*** EOF\r\n')]) }) break now = time.time() delay = now - last_write_time['last_activity_time'] last_write_time['last_activity_time'] = now if x == "exit\r\n" or x == "logout\r\n" or x == 'logout': chan.close() else: stdout.append([delay,codecs.getincrementaldecoder('UTF-8')('replace').decode(x)]) channel_layer.send(channel, {'text': json.dumps(['stdout',smart_unicode(x)]) }) except socket.timeout: pass except Exception,e: channel_layer.send(channel, {'text': json.dumps(['stdout','A bug find,You can report it to me' + smart_unicode(e)]) }) finally: pass
def choices(self): yield { 'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val, 'query_string': self.query_string({}, [self.lookup_exact_name, self.lookup_isnull_name]), 'display': _('All'), } for pk_val, val in self.lookup_choices: yield { 'selected': self.lookup_exact_val == smart_unicode(pk_val), 'query_string': self.query_string({ self.lookup_exact_name: pk_val, }, [self.lookup_isnull_name]), 'display': val, } if (is_related_field(self.field) and self.field.field.null or hasattr(self.field, 'rel') and self.field.null): yield { 'selected': bool(self.lookup_isnull_val), 'query_string': self.query_string({ self.lookup_isnull_name: 'True', }, [self.lookup_exact_name]), 'display': EMPTY_CHANGELIST_VALUE, }
def choices(self): yield { 'selected': (self.lookup_exact_val is '' and self.lookup_isnull_val is ''), 'query_string': self.query_string({}, [self.lookup_exact_name, self.lookup_isnull_name]), 'display': _('All'), } include_none = False for val in self.lookup_choices: if val is None: include_none = True continue val = smart_unicode(val) yield { 'selected': self.lookup_exact_val == val, 'query_string': self.query_string({self.lookup_exact_name: val}, [self.lookup_isnull_name]), 'display': val, } if include_none: yield { 'selected': bool(self.lookup_isnull_val), 'query_string': self.query_string({self.lookup_isnull_name: 'True'}, [self.lookup_exact_name]), 'display': EMPTY_CHANGELIST_VALUE, }
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return smart_unicode(value)
def text_diff(old_as_text, new_as_text): # {{{1 """ returns a unicode string containing a diff text showing differences of the utf8 parameters """ old_as_text = smart_unicode( old_as_text ).splitlines() new_as_text = smart_unicode( new_as_text ).splitlines() text_diff = unified_diff( old_as_text, new_as_text, n = 0, lineterm = "" ) # we now delete from the text diff all control lines # TODO: when the description field of an event contains such lines, # they will be deleted: avoid it. text_diff = [line for line in text_diff if not re.match(r"^---\s*$", line) and not re.match(r"^\+\+\+\s*$", line) and not re.match(r"^@@.*@@$", line)] text_diff = u'\n'.join( text_diff ) return text_diff
def choices(self): self.lookup_in_val = (type(self.lookup_in_val) in (tuple,list)) and self.lookup_in_val or list(self.lookup_in_val) yield { 'selected': len(self.lookup_in_val) == 0, 'query_string': self.query_string({},[self.lookup_in_name]), 'display': _('All'), } for val in self.lookup_choices: yield { 'selected': smart_unicode(val) in self.lookup_in_val, 'query_string': self.query_string({self.lookup_in_name: ",".join([val]+self.lookup_in_val),}), 'remove_query_string': self.query_string({self.lookup_in_name: ",".join([v for v in self.lookup_in_val if v != val]),}), 'display': val, } # @manager.register
def _get_new_field_html(self, field_name): try: f, attr, value = lookup_field(field_name, self.org_obj, self) except (AttributeError, ObjectDoesNotExist): return EMPTY_CHANGELIST_VALUE else: allow_tags = False if f is None: allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True text = boolean_icon(value) else: text = smart_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): field_val = getattr(self.org_obj, f.name) if field_val is None: text = EMPTY_CHANGELIST_VALUE else: text = field_val else: text = display_for_field(value, f) return mark_safe(text) if allow_tags else conditional_escape(text)
def choices(self): yield { 'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val, 'query_string': self.query_string({}, [self.lookup_exact_name, self.lookup_isnull_name]), 'display': _('All'), } for pk_val, val in self.lookup_choices: yield { 'selected': self.lookup_exact_val == smart_unicode(pk_val), 'query_string': self.query_string({ self.lookup_exact_name: pk_val, }, [self.lookup_isnull_name]), 'display': val, } if (isinstance(self.field, models.related.RelatedObject) and self.field.field.null or hasattr(self.field, 'rel') and self.field.null): yield { 'selected': bool(self.lookup_isnull_val), 'query_string': self.query_string({ self.lookup_isnull_name: 'True', }, [self.lookup_exact_name]), 'display': EMPTY_CHANGELIST_VALUE, }
def __init__(self, title, url, acl_groups=None, acl_perms=None, absolute_url=False, menu=None): self.title = smart_unicode(title) self._url = url self._url_is_resolved = absolute_url self.absolute_url = absolute_url self.acl_groups = acl_groups and set(acl_groups) or set() self.acl_perms = acl_perms and set(acl_perms) or set() self.main_menu = None self.parent_menu = None self.alters_data = False self.submenu_list = [] for i in menu or []: if type(i) in (tuple, list): self.submenu_list.extend(i) else: self.submenu_list.append(i) self.active = False self.depth = 0
def label_for_value(self, value): values = value.split(',') str_values = [] key = self.rel.get_related_field().name app_label = self.rel.to._meta.app_label class_name = self.rel.to._meta.object_name.lower() for v in values: try: obj = self.rel.to._default_manager.using(self.db).get(**{key: v}) url = reverse('admin:{0}_{1}_change'.format(app_label, class_name), args=[obj.id]) label = escape(smart_unicode(obj)) x = u'<a href="{0}" {1}>{2}</a>'.format(url, 'onclick="return showAddAnotherPopup(this);" target="_blank"', label ) str_values += [x] except self.rel.to.DoesNotExist: str_values += [u'???'] return u' <strong>{0}</strong>'.format(u', '.join(str_values))
def render(self, name, value, attrs=None, choices=(), *args, **kwargs): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) output = [u'<select {0}>'.format(flatatt(final_attrs))] str_value = smart_unicode(value) for group_label, group in self.choices: if group_label: # should belong to an optgroup group_label = smart_unicode(group_label) output.append(u'<optgroup label="%s">' % escape(group_label)) for key, value in group: #build option html option_value = smart_unicode(key) output.append( u'<option value="{0}"{1}>{2}</option>'.format( escape(option_value), (option_value == str_value) and u' selected="selected"' or '', escape(smart_unicode(value)) ) ) if group_label: output.append(u'</optgroup>') output.append(u'</select>') return u'\n'.join(output)
def clean(self, value): """ Validates that the input is in self.choices. """ value = super(GroupedChoiceField, self).clean(value) if value in (None, ''): value = u'' value = forms.util.smart_unicode(value) if value == u'': return value valid_values = [] for choice in self.choices: group = choice[1] valid_values += [str(key) for key, value in group] if value not in valid_values: raise ValidationError(_(u'Select a valid choice. That choice is not one of the available choices.')) return value
def __init__(self, template_string, name='<Unknown Template>', libraries=[]): try: template_string = encoding.smart_unicode(template_string) except UnicodeDecodeError: raise template.TemplateEncodingError( "template content must be unicode or UTF-8 string") origin = template.StringOrigin(template_string) self.nodelist = self.my_compile_string(template_string, origin, libraries) self.name = name
def __unicode__(self): return smart_unicode(self.name)
def choices(self): yield { 'selected': self.lookup_exact_val is '', 'query_string': self.query_string({}, [self.lookup_exact_name]), 'display': _('All') } for lookup, title in self.field.flatchoices: yield { 'selected': smart_unicode(lookup) == self.lookup_exact_val, 'query_string': self.query_string({self.lookup_exact_name: lookup}), 'display': title, }
def choices(self): self.lookup_in_val = (type(self.lookup_in_val) in (tuple,list)) and self.lookup_in_val or list(self.lookup_in_val) yield { 'selected': len(self.lookup_in_val) == 0, 'query_string': self.query_string({},[self.lookup_in_name]), 'display': _('All'), } for val in self.lookup_choices: yield { 'selected': smart_unicode(val) in self.lookup_in_val, 'query_string': self.query_string({self.lookup_in_name: ",".join([val]+self.lookup_in_val),}), 'remove_query_string': self.query_string({self.lookup_in_name: ",".join([v for v in self.lookup_in_val if v != val]),}), 'display': val, }
def init(self): self.label = label_for_field(self.field_name, self.obj.__class__, model_admin=self.admin_view, return_attr=False ) try: f, attr, value = lookup_field( self.field_name, self.obj, self.admin_view) except (AttributeError, ObjectDoesNotExist): self.text else: if f is None: self.allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: self.allow_tags = True self.text = boolean_icon(value) else: self.text = smart_unicode(value) else: if isinstance(f.rel, models.ManyToOneRel): self.text = getattr(self.obj, f.name) else: self.text = display_for_field(value, f) self.field = f self.attr = attr self.value = value
def default(self, o): if isinstance(o, datetime.date): return o.strftime('%Y-%m-%d') elif isinstance(o, datetime.datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(o, decimal.Decimal): return str(o) else: try: return super(JSONEncoder, self).default(o) except Exception: return smart_unicode(o)
def default(self, o): if isinstance(o, datetime.date): return o.strftime('%Y-%m-%d') elif isinstance(o, datetime.datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(o, decimal.Decimal): return str(o) elif isinstance(o, ModelBase): return '%s.%s' % (o._meta.app_label, o._meta.model_name) else: try: return super(JSONEncoder, self).default(o) except Exception: return smart_unicode(o)
def display_for_value(value, boolean=False): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if boolean: return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(value, datetime.datetime): return formats.localize(tz_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (decimal.Decimal, float)): return formats.number_format(value) else: return smart_unicode(value)
def default(self, o): if isinstance(o, (datetime.date, datetime.datetime)): return calendar.timegm(o.timetuple()) * 1000 elif isinstance(o, decimal.Decimal): return str(o) else: try: return super(JSONEncoder, self).default(o) except Exception: return smart_unicode(o)
def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement("row", {}) self._to_xml(xml, item) xml.endElement("row") elif isinstance(data, dict): for key, value in data.iteritems(): key = key.replace(' ', '_') xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) else: xml.characters(smart_unicode(data))