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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: fields.py From coursys with GNU General Public License v3.0 | 5 votes |
def to_python(self, value): """ Validates that the input is a fraction number. Returns a Fraction instance. Returns None for empty values. """ if value in forms.fields.validators.EMPTY_VALUES: return None value = smart_str(value).strip() try: value = Fraction(value).limit_denominator(50) except ValueError: raise forms.fields.ValidationError(self.error_messages['invalid']) return value
Example #12
Source File: betterJSONSerializer.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def deserialize(self, stream_or_string, **options): self.options = options.copy() self.stream = options.pop("stream", StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) if isinstance(stream_or_string, str): stream = StringIO(smart_str(stream_or_string)) elif isinstance(stream_or_string, bytes): try: stream = stream_or_string.decode("utf-8") stream = StringIO(smart_str(stream)) except Exception as e: print(e) stream = stream_or_string else: stream = stream_or_string try: ret = self.handle_object(json.load(stream)) except TypeError as e: print("=== +++ Error in JSONSerializer +++ ===") print(e) ret = None return ret
Example #13
Source File: relate.py From StormOnline 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 #14
Source File: fields.py From drf-mongo-filters with GNU General Public License v2.0 | 5 votes |
def to_representation(self, value): return smart_str(value)
Example #15
Source File: xform_instance_parser.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def clean_and_parse_xml(xml_string): clean_xml_str = xml_string.strip() clean_xml_str = re.sub(ur">\s+<", u"><", smart_unicode(clean_xml_str)) xml_obj = minidom.parseString(smart_str(clean_xml_str)) return xml_obj
Example #16
Source File: moderation.py From DCRM with GNU Affero General Public License v3.0 | 5 votes |
def _get_akismet_data(self, blog_url, comment, content_object, request): # Field documentation: # http://akismet.com/development/api/#comment-check data = { # Comment info 'permalink': urljoin(blog_url, content_object.get_absolute_url()), 'comment_type': 'comment', # comment, trackback, pingback, see http://blog.akismet.com/2012/06/19/pro-tip-tell-us-your-comment_type/ 'comment_author': getattr(comment, 'name', ''), 'comment_author_email': getattr(comment, 'email', ''), 'comment_author_url': getattr(comment, 'url', ''), 'comment_content': smart_str(comment.comment), 'comment_date': comment.submit_date, # Request info 'referrer': request.META.get('HTTP_REFERER', ''), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'user_ip': comment.ip_address, } if comment.user_id and comment.user.is_superuser: data['user_role'] = 'administrator' # always passes test # If the language is known, provide it. language = _get_article_language(content_object) if language: data['blog_lang'] = language return data
Example #17
Source File: admin.py From django-seo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_model_form(metadata_class): model_class = metadata_class._meta.get_model('model') # Restrict content type choices to the models set in seo_models content_types = get_seo_content_types(metadata_class._meta.seo_models) content_type_choices = [(x._get_pk_val(), smart_str(x)) for x in ContentType.objects.filter(id__in=content_types)] # Get a list of fields, with _content_type at the start important_fields = ['_content_type'] + core_choice_fields(metadata_class) _fields = important_fields + list(fields_for_model(model_class, exclude=important_fields).keys()) class ModelMetadataForm(forms.ModelForm): _content_type = forms.ChoiceField(label=capfirst(_("model")), choices=content_type_choices) class Meta: model = model_class fields = _fields def clean__content_type(self): value = self.cleaned_data['_content_type'] try: return ContentType.objects.get(pk=int(value)) except (ContentType.DoesNotExist, ValueError): raise forms.ValidationError("Invalid ContentType") return ModelMetadataForm
Example #18
Source File: middleware.py From Politikon with GNU General Public License v2.0 | 5 votes |
def process_response(self, request, response): if hasattr(request, 'profiler'): import sys request.profiler.disable() stamp = (request.META['REMOTE_ADDR'], datetime.now()) request.profiler.dump_stats('/tmp/%s-%s.pro' % stamp) import pstats stream = StringIO.StringIO() stats = pstats.Stats('/tmp/%s-%s.pro' % stamp, stream=stream) # stats.strip_dirs() stats.sort_stats('time') stats.print_stats(12) stats.print_callers(12) stats.print_callees(12) os.remove('/tmp/%s-%s.pro' % stamp) #response._container[0] += "<pre>"+stream.getvalue()+"</pre>" print >> sys.stderr, stream.getvalue() stream.close() from django.db import connection from django.utils.encoding import smart_str for query in connection.queries: print >> sys.stderr, smart_str(query['time']), smart_str(query['sql']) print >> sys.stderr, len(connection.queries), 'queries, overall time', "%.3f" % sum([float(query['time']) for query in connection.queries]) return response
Example #19
Source File: views.py From fomalhaut-panel with MIT License | 5 votes |
def export_config(request): """ 导出配置 :param request: :return: """ try: file_name = 'export_config_%s.json' % datetime.today().strftime('%Y%m%d') json_data = get_export_config_json() config_data = json_dumps(json_data, indent=4, sort_keys=True) agent = request.META.get('HTTP_USER_AGENT') if agent and re.search('MSIE', agent): # 解决ie不能下载的问题 response = HttpResponse(content=config_data, content_type="text/plain; charset=utf-8") # 解决文件名乱码/不显示的问题 response['Content-Disposition'] = 'attachment; filename=%s' % urlquote(file_name) else: response = HttpResponse(content=config_data, content_type="text/plain; charset=utf-8") response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) return response except Exception as e: logger.error(e.message) logger.error(traceback.format_exc()) return HttpResponse('导出配置失败 %s' % e.message)
Example #20
Source File: relate.py From weibo-analysis-system with MIT License | 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 #21
Source File: utils.py From opensurfaces with MIT License | 5 votes |
def get_upload_dir(obj, attr, time=None): """ Returns the directory used to save obj.attr files """ if not time: time = datetime.datetime.now() upload_to = obj._meta.get_field(attr).upload_to return os.path.normpath(force_unicode( datetime.datetime.now().strftime(smart_str(upload_to))))
Example #22
Source File: relate.py From myblog 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 #23
Source File: relate.py From CTF_AWD_Platform with MIT License | 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: __init__.py From django-gcloud-storage with BSD 3-Clause "New" or "Revised" License | 5 votes |
def prepare_name(name): return smart_str(name, encoding='utf-8')
Example #25
Source File: relate.py From django_OA 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 #26
Source File: models.py From django_OA with GNU General Public License v3.0 | 5 votes |
def __str__(self): return smart_str(self.department.name + "的" + self.type + "的问卷")
Example #27
Source File: models.py From django_OA with GNU General Public License v3.0 | 5 votes |
def __str__(self): return smart_str(self.question_type + " " + self.question_content)
Example #28
Source File: models.py From django_OA with GNU General Public License v3.0 | 5 votes |
def __str__(self): return smart_str(self.judge.first_name + "对" + self.player.first_name + "的评价")
Example #29
Source File: models.py From django_OA with GNU General Public License v3.0 | 5 votes |
def __str__(self): return smart_str(str(self.created_at.month) + "月" + str(self.answer_sheet_base) + "的评价")
Example #30
Source File: relate.py From Mxonline3 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)