Here are the examples of the python api django.utils.encoding.smart_str taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
172 Examples
3
Example 1
def resolve(self, value):
bits = self.path.split(".")
for bit in bits:
if is_iterable(value):
value = ', '.join(
map(lambda v: smart_str(self.resolve_one(v, bit)), value)
)
else:
value = self.resolve_one(value, bit)
if isinstance(value, self.raw_types):
return value
if is_iterable(value):
return ', '.join(map(smart_str, value))
return value and smart_str(value) or None
3
Example 2
Project: ANALYSE Source File: memcache.py
def cleaned_string(val):
"""
Converts `val` to unicode and URL-encodes special characters
(including quotes and spaces)
"""
return urllib.quote_plus(smart_str(val))
3
Example 3
Project: django-phased Source File: utils.py
def backup_csrf_token(context, storage=None):
"""
Get the CSRF token and convert it to a string (since it's lazy)
"""
if storage is None:
storage = Context()
storage['csrf_token'] = smart_str(context.get('csrf_token', 'NOTPROVIDED'))
return storage
3
Example 4
Project: django-test-extensions Source File: django_common.py
def assertNotContains(self, response, text, status_code=200): # overrides Django's assertion, because all diagnostics should be stated positively!!!
"""
Asserts that a response indicates that a page was retrieved
successfully, (i.e., the HTTP status code was as expected), and that
``text`` doesn't occurs in the content of the response.
"""
self.assertEqual(response.status_code, status_code,
"Retrieving page: Response code was %d (expected %d)'" %
(response.status_code, status_code))
text = smart_str(text, response._charset)
self.assertEqual(response.content.count(text),
0, "Response should not contain '%s'" % text)
3
Example 5
Project: django-cms Source File: admin.py
def jsonify_request(response):
""" Turn any response in a 200 response to let jQuery code handle it nicely.
Response contains a json object with the following attributes:
* status: original response status code
* content: original response content
"""
content = {'status': response.status_code, 'content': smart_str(response.content, response.charset)}
return HttpResponse(json.dumps(content), content_type="application/json")
3
Example 6
Project: django-cookie-consent Source File: middleware.py
def process_response(self, request, response):
if not is_cookie_consent_enabled(request):
return response
cookie_dic = get_cookie_dict_from_request(request)
for cookie_group in all_cookie_groups().values():
if not cookie_group.is_deletable:
continue
group_version = cookie_dic.get(cookie_group.varname, None)
for cookie in cookie_group.cookie_set.all():
if cookie.name not in request.COOKIES:
continue
if group_version == settings.COOKIE_CONSENT_DECLINE:
response.delete_cookie(smart_str(cookie.name),
cookie.path, cookie.domain)
if group_version < cookie.get_version():
if not settings.COOKIE_CONSENT_OPT_OUT:
response.delete_cookie(smart_str(cookie.name),
cookie.path, cookie.domain)
return response
3
Example 7
def handle_argument(self, argument, value):
argument = smart_str(argument, 'ascii')
handler_name = 'handle_%s' % argument
handler = getattr(self, handler_name, None)
if handler is not None:
value = value.resolve(self.context)
handler(value)
3
Example 8
def get(self, key, default=None):
val = CacheRow.get_row(smart_str(key))
if not val:
return default
if val.expires > datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'):
if isinstance(val, basestring):
return smart_unicode(val)
else:
return val
3
Example 9
def clean_cache_key(key):
""" Replace spaces with '-' and hash if length is greater than 250.
"""
cache_key = re.sub(r'\s+', '-', key)
cache_key = smart_str(cache_key)
if len(cache_key) > 200:
cache_key = cache_key[:150] + '-' + hashlib.md5(cache_key).hexdigest()
return cache_key
3
Example 10
def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0,
word_boundary=False, separator='-', save_order=False, stopwords=()):
"""
Make a slug from a given text.
"""
return smart_str(pyslugify(text, entities, decimal, hexadecimal, max_length,
word_boundary, separator, save_order, stopwords))
3
Example 11
Project: aemanager Source File: views.py
@login_required
@commit_on_success
def logo_overview(request):
file = request.user.get_profile().logo_file
if not file:
return HttpResponseNotFound()
response = HttpResponse(mimetype='application/force-download')
response['Content-Disposition'] = 'attachment;filename="%s"'\
% smart_str(file.name)
response["X-Sendfile"] = settings.FILE_UPLOAD_DIR + file.name
response['Content-length'] = file.size
return response
3
Example 12
Project: django-cache-machine Source File: ext.py
def _cache_support(self, name, obj, timeout, extra, caller):
"""Cache helper callback."""
if settings.TEMPLATE_DEBUG:
return caller()
extra = ':'.join(map(encoding.smart_str, extra))
key = 'fragment:%s:%s' % (name, extra)
return caching.base.cached_with(obj, caller, key, timeout)
3
Example 13
Project: django-castor Source File: storage.py
def path(self, hexdigest):
shards = self.shard(hexdigest)
try:
path = safe_join(self.location, *shards)
except ValueError:
raise SuspiciousOperation("Attempted access to '%s' denied." %
('/'.join(shards),))
return smart_str(os.path.normpath(path))
3
Example 14
@register.filter(is_safe=True)
def textile(value):
"""
:type value: str
:rtype: str
"""
import textile
return mark_safe(force_text(
textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))
)
3
Example 15
def set_password(self, raw_password):
import bcrypt
if raw_password is None:
self.set_unusable_password()
else:
raw_password = smart_str(raw_password)
salt = bcrypt.gensalt(self.rounds)
self.password = 'bcrypt%s' % bcrypt.hashpw(raw_password, salt)
3
Example 16
Project: django-js-reverse Source File: unit_tests.py
def test_tpl_tag_with_request_in_context(self):
context_instance = RequestContext(self.client.request)
tpl = Template('{% load js_reverse %}{% js_reverse_inline %}')
js_from_tag = tpl.render(context_instance)
js_from_view = smart_str(self.client.post('/jsreverse/').content)
self.assertEqual(js_from_tag, js_from_view)
3
Example 17
def __repr__(self):
params = []
for key, values in self:
for value in values:
value = smart_str(value)
params.append((key, value))
return urlencode(params)
3
Example 18
Project: jeeves Source File: logging_middleware.py
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
3
Example 19
def get_value(self, item, source_name):
"""
This method receives an item from the source and a source name,
and returns the text content for the `source_name` node.
"""
return force_text(smart_str(item.findtext(source_name))).strip()
3
Example 20
def post(self, request, *args, **kwargs):
body = smart_str(request.body)
data = json.loads(body)
if Event.stripe_objects.exists_by_json(data):
EventProcessingException.objects.create(
data=data,
message="Duplicate event record",
traceback=""
)
else:
event = Event.create_from_stripe_object(data)
event.validate()
event.process()
return HttpResponse()
3
Example 21
def serialize_reverse_fields(self, obj):
super(Serializer, self).serialize_reverse_fields(obj)
for fieldname in self.reverse_fields:
related = getattr(obj, fieldname)
if isinstance(self._current[fieldname], list):
self._current[fieldname].insert(0, smart_str(related.model._meta.verbose_name))
3
Example 22
def get_all_versions(fail_silently=bool(not settings.DEBUG)):
# this cannot be done on load as there would be circular and parital imports
try:
allnames = ['', 'django'] + settings.INSTALLED_APPS
res = [ (app, smart_str(svn_app_version(app, fail_silently)))
for app in allnames ]
except:
if fail_silently: return []
raise
return res
3
Example 23
Project: django-easy-maps Source File: geocode.py
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
results = g.geocode(smart_str(address), exactly_one=False)
if results is not None:
return results[0]
raise Error("No results found for '%s'" % address)
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
3
Example 24
def process_response(self, request, response):
if (not response.status_code == 200 or
not '<html' in response.content):
return response
self.update_content = False
soup = BeautifulSoup(smart_str(response.content), "html5lib")
self.remove_pubdate(soup)
self.remove_a_rel(soup)
self.change_link_archives(soup)
self.change_a_rel_tag_category(soup)
if self.update_content:
response.content = str(soup)
return response
3
Example 25
Project: Roll-Your-Own Source File: formatting.py
def get_format(format_type, locale=None):
"""
For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'
"""
format_type = smart_str(format_type)
if settings.USE_L10N:
for module in get_format_modules(locale=locale):
try:
return getattr(module, format_type)
except AttributeError:
pass
return getattr(settings, format_type)
3
Example 26
Project: peer Source File: utils.py
def generate_validation_key(domain_name, domain_owner=None):
""" Generates a unique validation key """
m = hashlib.sha256()
m.update(smart_str(domain_name))
# add also current datetime and owner for more security
m.update(datetime.datetime.now().isoformat())
if domain_owner:
m.update(domain_owner)
return m.hexdigest()
3
Example 27
def __repr__(self):
try:
u = unicode(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return smart_str('<%s: %s>' % (self.__class__.__name__, u))
3
Example 28
Project: django-autoreports Source File: adminfilters_utils.py
def get_lookup_params(request, remove=[]):
""" get lookup params from a http request query param1=value1¶m2__lt=value2&... """
lookup_params = dict(request.REQUEST.items()).copy() # a dictionary of the query string
excluded_params = [ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR]
excluded_params.extend(remove)
for i in excluded_params:
if i in lookup_params:
del lookup_params[i]
for key, value in lookup_params.items():
if not isinstance(key, str):
del lookup_params[key]
lookup_params[smart_str(key)] = value
return lookup_params
3
Example 29
Project: muspy Source File: tools.py
def check_password(user, password):
# Legacy users have their passwords hashed with SHA512.
# TODO: Remove when Django supports SHA512 (1.4?)
if user.password.startswith('sha512$'):
import hashlib
from django.utils.crypto import constant_time_compare
from django.utils.encoding import smart_str
algo, salt, hsh = user.password.split('$')
password, salt = smart_str(password), smart_str(salt)
hash = hashlib.new('sha512')
hash.update(password)
hash.update(salt)
hexdigest = hash.hexdigest()
return constant_time_compare(hsh, hexdigest)
return user.check_password(password)
3
Example 30
def execute(cmd, args):
"""
Just a simple wrapper for executing commands. args is expected to be a
sequence or a basestring, a basestring will be executed with shell=True.
"""
if isinstance(args, basestring):
args = smart_str(args)
args = shlex.split(args)
else:
args = map(smart_str, args)
cmd = smart_str(cmd)
args.insert(0, cmd)
p = Popen(args, stderr=PIPE, stdout=PIPE)
retcode = p.wait()
if retcode != 0:
raise ExecuteException(p.stderr.read().decode(DEFAULT_LOCALE_ENCODING))
return p.stdout.read().decode(DEFAULT_LOCALE_ENCODING)
3
Example 31
Project: django-lingua Source File: collectmessages.py
def handle(self, *args, **options):
db_values = []
""" Taken from django.core.management.commands.syncdb"""
for app in models.get_apps():
model_list = models.get_models(app, include_auto_created=True)
"""Performance is not so important, we do it once... """
for m in model_list:
if hasattr(m, '_translation_fields'):
for x in m._translation_fields:
for y in m.objects.all():
db_values.append( getattr(y, x) )
#print db_values
f = file('db_translation.html', "w")
""" blocktrans and we dont have to worry about to escape the string etc."""
for v in db_values:
f.write('{%% blocktrans %%}%s{%% endblocktrans %%}\n' % smart_str(v))
f.close()
3
Example 32
def to_representation(self, value):
"""
Transform POINT object to json.
"""
if value is None:
return value
if isinstance(value, GEOSGeometry):
value = {
"latitude": smart_str(value.y),
"longitude": smart_str(value.x)
}
return value
3
Example 33
Project: django-mobile Source File: __init__.py
def save(self, request, response):
if hasattr(request, '_flavour_cookie'):
response.set_cookie(
smart_str(settings.FLAVOURS_COOKIE_KEY),
smart_str(request._flavour_cookie),
httponly=settings.FLAVOURS_COOKIE_HTTPONLY)
3
Example 34
def _generate_preview_html(self, data_string):
"""Return html of the ReST file as produced by docutils."""
# Use safe filtering against injection attacks
docutils_settings = {
'file_insertion_enabled': False,
'raw_enabled': False,
'_disable_config': True
}
parts = docutils.core.publish_parts(
source=smart_str(data_string),
writer_name='html4css1',
settings_overrides=docutils_settings)
return parts['html_body']
3
Example 35
@register.filter
def removetext(text):
text=smart_str(text,"utf8")
text=text.replace("-育儿早教-中国早教网","")
text=text.replace("-怀孕胎教-中国早教网","")
text=text.replace("-新闻资讯-中国早教网","")
text=text.replace("-专家指导-中国早教网","")
text=text.replace("中国早教网","")
return text
3
Example 36
def __init__(self, verbose_name=None, name=None, timezone=None, **kwargs):
if isinstance(timezone, basestring):
timezone = smart_str(timezone)
if timezone in pytz.all_timezones_set:
self.timezone = pytz.timezone(timezone)
else:
self.timezone = timezone
super(LocalizedDateTimeField, self).__init__(verbose_name, name, **kwargs)
3
Example 37
Project: django-better-cache Source File: utils.py
def set_header_dict(response, header, header_dict):
"""Formats and sets a header dict in a response, inververs of get_header_dict."""
def dictvalue(t):
if t[1] is True:
return t[0]
return t[0] + '=' + smart_str(t[1])
response[header] = ', '.join([dictvalue(el) for el in header_dict.items()])
3
Example 38
Project: django-formwizard Source File: base.py
def get_step_files(self, step):
wizard_files = self.data[self.step_files_key].get(step, {})
if wizard_files and not self.file_storage:
raise NoFileStorageConfigured
files = {}
for field, field_dict in wizard_files.iteritems():
field_dict = dict((smart_str(k), v)
for k, v in field_dict.iteritems())
tmp_name = field_dict.pop('tmp_name')
files[field] = UploadedFile(
file=self.file_storage.open(tmp_name), **field_dict)
return files or None
3
Example 39
def parse_options(self, bits):
options = {}
for bit in bits:
parsed_bit = self.re_option.match(bit)
key = smart_str(parsed_bit.group('key'))
value = self.parser.compile_filter(parsed_bit.group('value'))
options[key] = value
return options
3
Example 40
def get_context_object_name(self, object_list):
"""
Get the name of the item to be used in the context.
"""
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
return smart_str(object_list.model._meta.verbose_name_plural)
else:
return None
3
Example 41
def delete(self, name, message=None):
"""
Deletes the specified file from the storage system.
"""
self.populate()
if message is None:
message = "Automated commit: removing %s" % name
full_paths = [smart_str(self.path(name))]
try:
self.wd.remove(paths=full_paths)
self.wd.commit(message=message, paths=full_paths)
except OSError:
pass
3
Example 42
def check_password(raw_password, enc_password):
if enc_password[0] == '$':
algo = enc_password[1:].split('$', 1)[0]
assert algo in ('2a', '2', 'bcrypt')
return constant_time_compare(
enc_password,
bcrypt.hashpw(smart_str(raw_password), enc_password),
)
return django_check_password(raw_password, enc_password)
3
Example 43
def process_request(self, request):
_local.remote_addr = request.META.get('REMOTE_ADDR', '')
name = '<anon>'
if hasattr(request, 'user') and request.user.is_authenticated():
field = getattr(request.user, 'USERNAME_FIELD', 'username')
name = encoding.smart_str(getattr(request.user, field, ''))
_local.username = name
3
Example 44
def add_header(content):
"""
We need to add a unique header to each message, as duplicate items
will otherwise be overwritten
"""
return uuid4().hex + smart_str(content)
3
Example 45
def resolve(self, context):
self.resolved_view = self.view.resolve(context)
self.resolved_args = [arg.resolve(context)
for arg in self.args]
self.resolved_kwargs = dict(
[(smart_str(k,'ascii'), v.resolve(context))
for k, v in self.kwargs.items()])
3
Example 46
def form_valid(self, form):
try:
self.update_subscription(form.cleaned_data["plan"])
return redirect("pinax_stripe_subscription_list")
except stripe.StripeError as e:
return self.render_to_response(self.get_context_data(form=form, errors=smart_str(e)))
3
Example 47
Project: tddspry Source File: test_cases.py
def test_datadiff_assert_equal(self):
if not datadiff:
self.assert_false(hasattr(self, 'datadiff_assert_equal'))
else:
self.datadiff_assert_equal(TEST_BAR, TEST_BAR)
try:
self.datadiff_assert_equal(TEST_BAR, TEST_FOO)
except AssertionError, e:
diff = datadiff.diff(TEST_BAR, TEST_FOO)
self.assert_unicode(e, '\n' + smart_str(diff))
3
Example 48
def get_context_object_name(self, object_list):
"""Get the name of the item to be used in the context.
See original in ``django.views.generic.list.MultipleObjectMixin``.
"""
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
object_name = object_list.model._meta.object_name.lower()
return smart_str('{0}_list'.format(object_name))
else:
return None
3
Example 49
Project: django-rocket-engine Source File: views.py
def file_serve(request, filename):
blobinfo = blobstore.BlobInfo.all().filter('filename =', filename)
blobstore_key = blobinfo[0].key()._BlobKey__blob_key
blob_info = blobstore.BlobInfo.get(blobstore_key)
filename = getattr(blob_info, 'filename', blobstore_key)
content_type = getattr(blob_info, 'content_type', 'application/octet-stream')
response = HttpResponse(content_type=content_type)
response[BLOB_KEY_HEADER] = blobstore_key
response['Content-Disposition'] = smart_str(
u'attachment; filename=%s' % filename.split('/')[-1]
)
return response
3
Example 50
Project: ella Source File: managers.py
def get_listings_key(self, category=None, children=ListingHandler.NONE, count=10, offset=0, content_types=[], date_range=(), exclude=None, **kwargs):
c = category and category.id or ''
return 'core.get_listing:%s:%d:%d:%d:%d:%s:%s:%s' % (
c, count, offset, children, exclude.id if exclude else 0,
','.join(map(lambda ct: str(ct.pk), content_types)),
','.join(map(lambda d: d.strftime('%Y%m%d'), date_range)),
','.join(':'.join((k, smart_str(v))) for k, v in kwargs.items()),
)