Python django.utils.encoding.smart_str() Examples
The following are 30
code examples of django.utils.encoding.smart_str().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.encoding
, or try the search function
.
Example #1
Source File: filter.py From iguana with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def render(self, context): mods = [(smart_str(k, 'ascii'), op, v.resolve(context)) for k, op, v in self.mods] if self.qdict: qdict = self.qdict.resolve(context) else: qdict = None # Internally work only with QueryDict qdict = self._get_initial_query_dict(qdict) # assert isinstance(qdict, QueryDict) for k, op, v in mods: qdict.setlist(k, self._process_list(qdict.getlist(k), op, v)) qstring = qdict.urlencode() if qstring: qstring = '?' + qstring if self.asvar: context[self.asvar] = qstring return '' else: return qstring
Example #2
Source File: check_permissions.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 6 votes |
def handle(self, **options): permissions, users, warnings = UserenaSignup.objects.check_permissions() output = options.pop("output") test = options.pop("test") if test: self.stdout.write(40 * ".") self.stdout.write( "\nChecking permission management command. Ignore output..\n\n" ) if output: for p in permissions: self.stdout.write("Added permission: %s\n" % p) for u in users: self.stdout.write( "Changed permissions for user: %s\n" % smart_str(u, encoding="utf-8", strings_only=False) ) for w in warnings: self.stdout.write("WARNING: %s\n" % w) if test: self.stdout.write("\nFinished testing permissions command.. continuing..\n")
Example #3
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 6 votes |
def create_userena_profile(self, user): """ Creates an :class:`UserenaSignup` instance for this user. :param user: Django :class:`User` instance. :return: The newly created :class:`UserenaSignup` instance. """ if isinstance(user.username, str): user.username = smart_str(user.username) try: profile = self.get(user=user) except self.model.DoesNotExist: profile = self.create(user=user, activation_key=generate_nonce()) return profile
Example #4
Source File: geo_fields.py From drf-extra-fields with Apache License 2.0 | 6 votes |
def to_representation(self, value): """ Transform POINT object to json. """ if value is None: return value if isinstance(value, GEOSGeometry): value = { "latitude": value.y, "longitude": value.x } if self.str_points: value['longitude'] = smart_str(value.pop('longitude')) value['latitude'] = smart_str(value.pop('latitude')) return value
Example #5
Source File: submission_list.py From wagtailstreamforms with MIT License | 6 votes |
def csv(self): queryset = self.get_queryset() data_fields = self.object.get_data_fields() data_headings = [smart_str(label) for name, label in data_fields] response = HttpResponse(content_type="text/csv; charset=utf-8") response["Content-Disposition"] = "attachment;filename=export.csv" writer = csv.writer(response) writer.writerow(data_headings) for s in queryset: data_row = [] form_data = s.get_data() for name, label in data_fields: data_row.append(smart_str(form_data.get(name))) writer.writerow(data_row) return response
Example #6
Source File: leonardo_tags.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render(self, context): args = [arg.resolve(context) for arg in self.args] kwargs = dict([ (smart_str(k, 'ascii'), v.resolve(context)) for k, v in self.kwargs.items()]) view_name = self.view_name.resolve(context) urlconf = self.urlconf.resolve(context) try: url = do_app_reverse( view_name, urlconf, args=args, kwargs=kwargs, current_app=context.current_app) except NoReverseMatch: if self.asvar is None: raise url = '' if self.asvar: context[self.asvar] = url return '' else: return url
Example #7
Source File: views.py From django-searchable-select with GNU General Public License v2.0 | 6 votes |
def filter_models(request): model_name = request.GET.get('model') search_field = request.GET.get('search_field') value = request.GET.get('q') limit = int(request.GET.get('limit', 10)) try: model = get_model(model_name) except LookupError as e: # pragma: no cover return JsonResponse(dict(status=400, error=e.message)) except (ValueError, AttributeError) as e: # pragma: no cover return JsonResponse(dict(status=400, error='Malformed model parameter.')) values = model.objects.filter(**{'{}__icontains'.format(search_field): value})[:limit] values = [ dict(pk=v.pk, name=smart_str(v)) for v in values ] return JsonResponse(dict(result=values))
Example #8
Source File: models.py From fomalhaut-panel with MIT License | 6 votes |
def get_hexdigest(algorithm, salt, raw_password): """ Returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ('md5', 'sha1' or 'crypt'). """ raw_password, salt = smart_str(raw_password), smart_str(salt) if algorithm == 'crypt': try: import crypt except ImportError: raise ValueError('"crypt" password algorithm not supported in this environment') return crypt.crypt(raw_password, salt) if algorithm == 'md5': return hashlib.md5(salt + raw_password).hexdigest() elif algorithm == 'sha1': return hashlib.sha1(salt + raw_password).hexdigest() elif algorithm == 'sha256': return hashlib.sha256(salt + raw_password).hexdigest() raise ValueError("Got unknown password algorithm type in password.")
Example #9
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
def _get_jwt_value(self, request): auth = get_authorization_header(request).split() auth_header_prefix = getattr(settings, 'JWT_AUTH_HEADER_PREFIX', 'JWT') if not auth: if getattr(settings, 'JWT_AUTH_COOKIE', None): return request.COOKIES.get(settings.JWT_AUTH_COOKIE) return None if smart_str(auth[0]) != auth_header_prefix: return None if len(auth) == 1: msg = 'Invalid Authorization header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = ('Invalid Authorization header. Credentials string ' 'should not contain spaces.') raise exceptions.AuthenticationFailed(msg) jwt_value = auth[1] if type(jwt_value) is bytes: jwt_value = jwt_value.decode('utf-8') return jwt_value
Example #10
Source File: frontend.py From naarad-source with GNU Affero General Public License v3.0 | 6 votes |
def get_html(data): template_raw = open('feed.tmpl', 'r').read() for post in data: if 'message' in post: if (type(post['message']) is str): post['message'] = fixnewlines(post['message']) if 'flag' not in post : post['message'] = enable_links(post['message']) post['flag'] = 1 post['message'] = post['message'].replace("\"","'") post['short_message'] = truncate(post['message'],150) post['read_more'] = truncate_length(post['message'],150) json.dump(data, open('docs/feed.json', 'w')) template = Template(template_raw) html = template.render(data=data) # smart_str helps in unicode rendering return smart_str(html)
Example #11
Source File: cache.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def simple_cachekey(key): return 'django_compressor.%s' % smart_str(key)
Example #12
Source File: logging_middleware.py From jeeves with MIT License | 5 votes |
def process_response(self, request, response): logger.info("%s \"%s\" (%s)" % (request.method, smart_str(request.path_info), response.status_code)) indentation = 2 if len(connection.queries) > 0: total_time = 0.0 for query in connection.queries: nice_sql = query['sql'].replace('"', '').replace(',',', ') sql = "[%s] %s" % (query['time'], nice_sql) total_time = total_time + float(query['time']) logger.info("%s%s\n" % (" "*indentation, sql)) replace_tuple = (" "*indentation, str(total_time)) logger.info("%s[TOTAL QUERIES: %d]" % (" "*indentation, len(connection.queries))) logger.info("%s[TOTAL TIME: %s seconds]" % replace_tuple) return response
Example #13
Source File: cache.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_hexdigest(plaintext, length=None): digest = md5_constructor(smart_str(plaintext)).hexdigest() if length: return digest[:length] return digest
Example #14
Source File: tests.py From django-sendfile2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_xsendfile_header_containing_unicode(self): filepath = self.ensure_file(u'péter_là_gueule.txt') response = real_sendfile(HttpRequest(), filepath) self.assertTrue(response is not None) self.assertEqual(smart_str(filepath), response['X-Sendfile'])
Example #15
Source File: relate.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def init_request(self, *args, **kwargs): self.relate_obj = None for k, v in self.request.GET.items(): if smart_str(k).startswith(RELATE_PREFIX): self.relate_obj = RelateObject( self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v) break return bool(self.relate_obj)
Example #16
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 5 votes |
def represent_data(self, data): if isinstance(data, EmbeddedDocument): field = GenericEmbeddedField() return field.to_representation(data) elif isinstance(data, dict): return dict([(key, self.represent_data(val)) for key, val in data.items()]) elif isinstance(data, list): return [self.represent_data(value) for value in data] elif data is None: return None else: return smart_str(data, strings_only=True)
Example #17
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 5 votes |
def to_representation(self, obj): """ convert value to representation. DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method. This implementation uses ``django.utils.encoding.smart_str`` to convert everything to text, while keeping json-safe types intact. NB: The argument is whole object, instead of attribute value. This is upstream feature. Probably because the field can be represented by a complicated method with nontrivial way to extract data. """ value = self.model_field.__get__(obj, None) return smart_str(value, strings_only=True)
Example #18
Source File: lookups.py From astrobin with GNU Affero General Public License v3.0 | 5 votes |
def autocomplete(request, what): values = [] if 'q' not in request.GET: return HttpResponse(simplejson.dumps([{}])) q = smart_str(request.GET['q']) limit = 10 regex = ".*%s.*" % re.escape(q) for k, v in {'locations': Location, 'telescopes':Telescope, 'imaging_telescopes':Telescope, 'guiding_telescopes':Telescope, 'mounts':Mount, 'cameras':Camera, 'imaging_cameras':Camera, 'guiding_cameras':Camera, 'focal_reducers':FocalReducer, 'software':Software, 'filters':Filter, 'accessories':Accessory}.iteritems(): if what == k: values = v.objects.filter(Q(make__iregex=r'%s'%regex) | Q(name__iregex=r'%s'%regex))[:limit] if k == 'locations': return HttpResponse(simplejson.dumps([{'id': str(v.id), 'name': v.name} for v in values])) else: return HttpResponse(simplejson.dumps([{'id': str(v.id), 'name': unicode(v)} for v in values])) return HttpResponse(simplejson.dumps([{}]))
Example #19
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 5 votes |
def to_representation(self, value): return smart_str(value)
Example #20
Source File: fields.py From django-rest-framework-mongoengine with MIT License | 5 votes |
def to_internal_value(self, value): try: return ObjectId(smart_str(value)) except InvalidId: raise serializers.ValidationError("'%s' is not a valid ObjectId" % value)
Example #21
Source File: cache.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def socket_cachekey(key): return "django_compressor.%s.%s" % (socket.gethostname(), smart_str(key))
Example #22
Source File: tests.py From django-sendfile2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_sendfile(self): response = real_sendfile(HttpRequest(), self._get_readme()) self.assertTrue(response is not None) self.assertEqual('text/plain', response['Content-Type']) self.assertEqual('inline; filename="testfile.txt"', response['Content-Disposition']) self.assertEqual(self._get_readme(), smart_str(response.content))
Example #23
Source File: relate.py From Dailyfresh-B2C with Apache License 2.0 | 5 votes |
def init_request(self, *args, **kwargs): self.relate_obj = None for k, v in self.request.GET.items(): if smart_str(k).startswith(RELATE_PREFIX): self.relate_obj = RelateObject( self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v) break return bool(self.relate_obj)
Example #24
Source File: relate.py From online with GNU Affero General Public License v3.0 | 5 votes |
def init_request(self, *args, **kwargs): self.relate_obj = None for k, v in self.request.GET.items(): if smart_str(k).startswith(RELATE_PREFIX): self.relate_obj = RelateObject( self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v) break return bool(self.relate_obj)
Example #25
Source File: forms.py From django-clever-selects with MIT License | 5 votes |
def find_instance_attr(self, instance, attr_name): field = self.fields[attr_name] if hasattr(instance, attr_name): attribute = getattr(instance, attr_name) attr_value = getattr(attribute, 'pk', smart_str(attribute)) if attribute else None setattr(self, '%s' % attr_name, attr_value) if hasattr(field, 'parent_field'): parent_instance = attribute if isinstance(attribute, models.Model) else instance self.find_instance_attr(parent_instance, field.parent_field)
Example #26
Source File: forms.py From django-clever-selects with MIT License | 5 votes |
def find_instance_attr(self, instance, attr_name): field = self.fields[attr_name] if hasattr(instance, attr_name): attribute = getattr(instance, attr_name) attr_value = getattr(attribute, 'pk', smart_str(attribute)) if attribute else None setattr(self, '%s' % attr_name, attr_value) if hasattr(field, 'parent_field'): parent_instance = attribute if isinstance(attribute, models.Model) else instance self.find_instance_attr(parent_instance, field.parent_field)
Example #27
Source File: cache.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_offline_hexdigest(source): return get_hexdigest([smart_str(getattr(s, 's', s)) for s in source])
Example #28
Source File: cache.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _prepare_key(self, raw_key): "``smart_str``-encode the key." return smart_str(raw_key)
Example #29
Source File: webmail_tags.py From modoboa-webmail with MIT License | 5 votes |
def attachment_url(mbox, mail_id, fname, key): """Return full download url of an attachment.""" url = reverse("modoboa_webmail:attachment_get") params = { "mbox": mbox, "mailid": mail_id, "fname": smart_str(fname), "partnumber": key } url = "{}?{}".format(url, urlencode(params)) return url
Example #30
Source File: logging_middleware.py From jeeves with MIT License | 5 votes |
def process_response(self, request, response): logger.info("%s \"%s\" (%s)" % (request.method, smart_str(request.path_info), response.status_code)) indentation = 2 if len(connection.queries) > 0: total_time = 0.0 for query in connection.queries: nice_sql = query['sql'].replace('"', '').replace(',',', ') sql = "[%s] %s" % (query['time'], nice_sql) total_time = total_time + float(query['time']) logger.info("%s%s\n" % (" "*indentation, sql)) replace_tuple = (" "*indentation, str(total_time)) logger.info("%s[TOTAL QUERIES: %d]" % (" "*indentation, len(connection.queries))) logger.info("%s[TOTAL TIME: %s seconds]" % replace_tuple) return response