Here are the examples of the python api django.utils.encoding.force_str taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
137 Examples
3
Example 1
Project: HealthStarter Source File: http.py
def urlquote(url, safe='/'):
"""
A version of Python's urllib.quote() function that can operate on unicode
strings. The url is first UTF-8 encoded before quoting. The returned string
can safely be used as part of an argument to a subsequent iri_to_uri() call
without double-quoting occurring.
"""
return force_text(quote(force_str(url), force_str(safe)))
3
Example 2
Project: golismero Source File: client.py
def get(self, path, data={}, **extra):
"Construct a GET request."
parsed = urlparse(path)
r = {
'CONTENT_TYPE': str('text/html; charset=utf-8'),
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': urlencode(data, doseq=True) or force_str(parsed[4]),
'REQUEST_METHOD': str('GET'),
}
r.update(extra)
return self.request(**r)
3
Example 3
Project: cgstudiomap Source File: formats.py
def localize_input(value, default=None):
"""
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, (decimal.Decimal, float) + six.integer_types):
return number_format(value)
elif isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)
format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.date):
value = datetime_safe.new_date(value)
format = force_str(default or get_format('DATE_INPUT_FORMATS')[0])
return value.strftime(format)
elif isinstance(value, datetime.time):
format = force_str(default or get_format('TIME_INPUT_FORMATS')[0])
return value.strftime(format)
return value
3
Example 4
Project: django-precise-bbcode Source File: models.py
def get_parser_tag_klass(self, tag_name=None):
# Construct the inner Options class
opts = self._meta
tag_option_attrs = vars(BBCodeTagOptions)
options_klass_attrs = {
f.name: f.value_from_object(self) for f in opts.fields if f.name in tag_option_attrs}
options_klass = type(force_str('Options'), (), options_klass_attrs)
# Construct the outer BBCodeTag class
tag_klass_attrs = {
'name': self.tag_name if not tag_name else tag_name,
'definition_string': self.tag_definition,
'format_string': self.html_replacement,
'Options': options_klass,
}
tag_klass = type(
force_str('{}Tag'.format(self.tag_name)), (ParserBBCodeTag, ), tag_klass_attrs)
return tag_klass
3
Example 5
Project: hue Source File: client.py
def _get_path(self, parsed):
path = force_str(parsed[2])
# If there are parameters, add them
if parsed[3]:
path += str(";") + force_str(parsed[3])
path = unquote(path)
# WSGI requires latin-1 encoded strings. See get_path_info().
if six.PY3:
path = path.encode('utf-8').decode('iso-8859-1')
return path
3
Example 6
Project: django-downloadview Source File: response.py
def encode_basename_utf8(value):
u"""Return UTF-8 encoded ``value`` for use in Content-Disposition header.
>>> print(encode_basename_utf8(u' .txt'))
%20.txt
>>> print(encode_basename_utf8(u'éà'))
%C3%A9%C3%A0
"""
return urllib.parse.quote(force_str(value))
3
Example 7
Project: django-cryptography Source File: tests.py
def test_sign_unsign(self):
"""sign/unsign should be reversible"""
signer = signing.Signer('predictable-secret')
examples = [
'q;wjmbk;wkmb',
'3098247529087',
'3098247:529:087:',
'jkw osanteuh ,rcuh nthu aou oauh ,ud du',
'\u2019',
]
if six.PY2:
examples.append(b'a byte string')
for example in examples:
signed = signer.sign(example)
self.assertIsInstance(signed, str)
self.assertNotEqual(force_str(example), signed)
self.assertEqual(example, signer.unsign(signed))
3
Example 8
Project: Misago Source File: validators.py
def _real_validate_with_sfs(ip, email):
try:
r = requests.get(SFS_API_URL % {'email': email, 'ip': ip},
timeout=3)
api_response = json.loads(force_str(r.content))
ip_score = api_response.get('ip', {}).get('confidence', 0)
email_score = api_response.get('email', {}).get('confidence', 0)
api_score = max((ip_score, email_score))
if api_score > settings.MISAGO_STOP_FORUM_SPAM_MIN_CONFIDENCE:
raise PermissionDenied()
except requests.exceptions.RequestException:
pass # todo: log those somewhere
3
Example 9
Project: django-static-precompiler Source File: libsass.py
def compile_source(self, source):
try:
compiled = sass.compile(string=source, indented=self.indented)
except sass.CompileError as e:
raise exceptions.StaticCompilationError(encoding.force_str(e))
compiled = encoding.force_str(compiled)
return compiled
3
Example 10
Project: Django--an-app-at-a-time Source File: messages.py
def __str__(self):
from django.db import models
if self.obj is None:
obj = "?"
elif isinstance(self.obj, models.base.ModelBase):
# We need to hardcode ModelBase and Field cases because its __str__
# method doesn't return "applabel.modellabel" and cannot be changed.
model = self.obj
app = model._meta.app_label
obj = '%s.%s' % (app, model._meta.object_name)
else:
obj = force_str(self.obj)
id = "(%s) " % self.id if self.id else ""
hint = "\n\tHINT: %s" % self.hint if self.hint else ''
return "%s: %s%s%s" % (obj, id, self.msg, hint)
3
Example 11
Project: django-bmf Source File: decorators.py
def login_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks if the user is logged in
otherwise the user will be redirected to an bmf-login-form
"""
@wraps(view_func, assigned=available_attrs(view_func))
def wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
return redirect_to_login(
request.get_full_path(),
force_str(resolve_url('djangobmf:login')),
redirect_field_name)
return wrapped_view
3
Example 12
Project: decode-Django Source File: cookie.py
def load(self, rawdata):
self.bad_cookies = set()
if not six.PY3 and isinstance(rawdata, six.text_type):
rawdata = force_str(rawdata)
super(SimpleCookie, self).load(rawdata)
for key in self.bad_cookies:
del self[key]
3
Example 13
def __repr__(self):
try:
u = six.text_type(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str('<%s: %s>' % (self.__class__.__name__, u))
3
Example 14
def write(self, msg, style_func=None, ending=None):
ending = self.ending if ending is None else ending
if ending and not msg.endswith(ending):
msg += ending
style_func = style_func or self.style_func
self._out.write(force_str(style_func(msg)))
3
Example 15
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
"""
Helper: get a datetime.date object given a format string and a year,
month, and day (only year is mandatory). Raise a 404 for an invalid date.
"""
format = delim.join((year_format, month_format, day_format))
datestr = delim.join((year, month, day))
try:
return datetime.datetime.strptime(force_str(datestr), format).date()
except ValueError:
raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
'datestr': datestr,
'format': format,
})
3
Example 16
Project: django-cryptography Source File: signing.py
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
self.sep = force_str(sep)
if _SEP_UNSAFE.match(self.sep):
raise ValueError(
'Unsafe Signer separator: %r (cannot be empty or consist of '
'only A-z0-9-_=)' % sep,
)
self.salt = force_str(salt or
'%s.%s' % (self.__class__.__module__, self.__class__.__name__))
3
Example 17
Project: cgstudiomap Source File: messages.py
def __str__(self):
from django.db import models
if self.obj is None:
obj = "?"
elif isinstance(self.obj, models.base.ModelBase):
# We need to hardcode ModelBase and Field cases because its __str__
# method doesn't return "applabel.modellabel" and cannot be changed.
obj = self.obj._meta.label
else:
obj = force_str(self.obj)
id = "(%s) " % self.id if self.id else ""
hint = "\n\tHINT: %s" % self.hint if self.hint else ''
return "%s: %s%s%s" % (obj, id, self.msg, hint)
3
Example 18
Project: django-sheets Source File: sheets.py
def _fetch_sheet(self):
try:
gdocs_url = gdocs_format.format(key=self.key)
if self.gid:
gdocs_url += '&gid={}'.format(self.gid)
response = requests.get(gdocs_url)
response.raise_for_status()
return force_str(response.content)
except requests.HTTPError as exp:
logger.error('Error fetching spreadsheet: %s' % exp)
return force_str('')
3
Example 19
def urlunquote_plus(quoted_url):
"""
A wrapper for Python's urllib.unquote_plus() function that can operate on
the result of django.utils.http.urlquote_plus().
"""
return force_text(urllib_parse.unquote_plus(force_str(quoted_url)))
3
Example 20
def get_app_data(self, app_label, models):
model_data = []
for model in models:
model_data.append(self.get_model_data(model))
return {
'app_label': app_label,
'models': model_data,
'app_verbose_name': force_str(self.app_verbose_names.get(app_label))
}
3
Example 21
Project: hue Source File: cookie.py
def load(self, rawdata):
self.bad_cookies = set()
if six.PY2 and isinstance(rawdata, six.text_type):
rawdata = force_str(rawdata)
super(SimpleCookie, self).load(rawdata)
for key in self.bad_cookies:
del self[key]
3
Example 22
Project: hue Source File: cookie.py
def _BaseCookie__set(self, key, real_value, coded_value):
key = force_str(key)
try:
M = self.get(key, Morsel())
M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M)
except http_cookies.CookieError:
self.bad_cookies.add(key)
dict.__setitem__(self, key, http_cookies.Morsel())
3
Example 23
def urlencode(query, doseq=0):
"""
A version of Python's urllib.urlencode() function that can operate on
unicode strings. The parameters are first case to UTF-8 encoded strings and
then encoded as per normal.
"""
if isinstance(query, MultiValueDict):
query = query.lists()
elif hasattr(query, 'items'):
query = query.items()
return urllib_parse.urlencode(
[(force_str(k),
[force_str(i) for i in v] if isinstance(v, (list,tuple)) else force_str(v))
for k, v in query],
doseq)
3
Example 24
def head(self, path, data={}, **extra):
"Construct a HEAD request."
parsed = urlparse(path)
query_string = urlencode(data, doseq=True) or force_str(parsed[4])
if six.PY3:
query_string = query_string.encode('utf-8').decode('iso-8859-1')
r = {
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': query_string,
'REQUEST_METHOD': str('HEAD'),
}
r.update(extra)
return self.request(**r)
3
Example 25
def force_ascii(string, method='backslashreplace'):
"""
Force given string to ASCII str.
:param string: String to convert
:type string: str|unicode|bytes
:param method:
How to handle non-ASCII characters. Accepted values are
'backslashreplace' (default), 'xmlcharrefreplace', 'replace' and
'ignore'.
:type method: str
:rtype: str
"""
return force_str(force_text(string).encode('ascii', errors=method))
3
Example 26
Project: django Source File: client.py
def _get_path(self, parsed):
path = force_str(parsed[2])
# If there are parameters, add them
if parsed[3]:
path += str(";") + force_str(parsed[3])
path = uri_to_iri(path).encode(UTF_8)
# Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
# decoded with ISO-8859-1. We replicate this behavior here.
# Refs comment in `get_bytes_from_wsgi()`.
return path.decode(ISO_8859_1) if six.PY3 else path
3
Example 27
def __call__(self, environ, start_response):
set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__, environ=environ)
request = self.request_class(environ)
response = self.get_response(request)
response._handler_class = self.__class__
status = '%d %s' % (response.status_code, response.reason_phrase)
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
start_response(force_str(status), response_headers)
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
response = environ['wsgi.file_wrapper'](response.file_to_stream)
return response
3
Example 28
def write(self, msg, style_func=None, ending=None):
ending = ending is None and self.ending or ending
if ending and not msg.endswith(ending):
msg += ending
style_func = [f for f in (style_func, self.style_func, lambda x:x)
if f is not None][0]
self._out.write(force_str(style_func(msg)))
3
Example 29
def __call__(self, instance, filename):
if self.original_filename_field and hasattr(instance, self.original_filename_field):
setattr(instance, self.original_filename_field, filename)
parts = filename.split('.')
extension = parts[-1]
directory_path = os.path.normpath(datetime.datetime.now().strftime(force_str(self.sub_path)))
unique_name = "{0}.{1}".format(uuid.uuid4(), extension)
return os.path.join(directory_path, unique_name)
3
Example 30
def unsign(self, signed_value):
signed_value = force_str(signed_value)
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
if constant_time_compare(sig, self.signature(value)):
return force_text(value)
raise BadSignature('Signature "%s" does not match' % sig)
3
Example 31
Project: django-precise-bbcode Source File: test.py
def gen_bbcode_tag_klass(klass_attrs, options_attrs={}):
# Construc the inner Options class
options_klass = type(force_str('Options'), (), options_attrs)
# Construct the outer BBCodeTag class
tag_klass_attrs = klass_attrs
tag_klass_attrs['Options'] = options_klass
tag_klass = type(
force_str('{}Tag'.format(tag_klass_attrs['name'])), (BBCodeTag, ), tag_klass_attrs)
return tag_klass
3
Example 32
Project: splunk-webframework Source File: utils.py
def get_runner(settings, test_runner_class=None):
if not test_runner_class:
test_runner_class = settings.TEST_RUNNER
test_path = test_runner_class.split('.')
# Allow for Python 2.5 relative paths
if len(test_path) > 1:
test_module_name = '.'.join(test_path[:-1])
else:
test_module_name = '.'
test_module = __import__(test_module_name, {}, {}, force_str(test_path[-1]))
test_runner = getattr(test_module, test_path[-1])
return test_runner
3
Example 33
Project: HealthStarter Source File: cookie.py
def _BaseCookie__set(self, key, real_value, coded_value):
key = force_str(key)
try:
M = self.get(key, Morsel())
M.set(key, real_value, coded_value)
dict.__setitem__(self, key, M)
except http_cookies.CookieError:
if not hasattr(self, 'bad_cookies'):
self.bad_cookies = set()
self.bad_cookies.add(key)
dict.__setitem__(self, key, http_cookies.Morsel())
3
Example 34
def urlunquote(quoted_url):
"""
A wrapper for Python's urllib.unquote() function that can operate on
the result of django.utils.http.urlquote().
"""
return force_text(urllib_parse.unquote(force_str(quoted_url)))
3
Example 35
Project: ohai-kit Source File: views.py
def trigger_login_redirect(request, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Code pulled from the auth module, because its nested, preventing reuse.
"""
path = request.build_absolute_uri()
# urlparse chokes on lazy objects in Python 3, force to str
resolved_login_url = force_str(
resolve_url(login_url or settings.LOGIN_URL))
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
3
Example 36
Project: django-rest-framework-mongoengine Source File: repr.py
def mongo_doc_repr(value):
# mimic django models.Model.__repr__
try:
u = six.text_type(value)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str('<%s: %s>' % (value.__class__.__name__, u))
3
Example 37
def __init__(self, key=None, salt=None):
digest = settings.CRYPTOGRAPHY_DIGEST
self._digest_size = digest.digest_size
self.key = key or settings.SECRET_KEY
self.salt = force_str(salt or '%s.%s' % (
self.__class__.__module__, self.__class__.__name__))
3
Example 38
def handle(self, *args, **options):
message = force_str("This will replace all checksums "
"in database with new ones, marking "
"all data as trusted. Are you sure "
"you wish to continue? [Y/n]")
if '--force' in args or input(message).strip().lower() == "y":
self.stdout.write("\nRegenerating checksums...")
secret_key_changed.send(self)
self.stdout.write("\nDone!")
else:
self.stdout.write("\nAborted!")
3
Example 39
Project: django-cryptography Source File: tests.py
def test_sign_unsign(self):
"""sign/unsign should be reversible"""
signer = signing.BytesSigner('predictable-secret')
examples = [
b'q;wjmbk;wkmb',
b'3098247529087',
b'3098247:529:087:',
b'jkw osanteuh ,rcuh nthu aou oauh ,ud du',
b'\u2019',
]
if six.PY2:
examples.append(b'a byte string')
for example in examples:
signed = signer.sign(example)
self.assertIsInstance(signed, six.binary_type)
self.assertNotEqual(force_str(example), signed)
self.assertEqual(example, signer.unsign(signed))
3
Example 40
Project: cgstudiomap Source File: signing.py
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
self.sep = force_str(sep)
if _SEP_UNSAFE.match(self.sep):
warnings.warn('Unsafe Signer separator: %r (cannot be empty or consist of only A-z0-9-_=)' % sep,
RemovedInDjango110Warning)
self.salt = force_str(salt or
'%s.%s' % (self.__class__.__module__, self.__class__.__name__))
3
Example 41
Project: sentry Source File: email.py
def unsign(self, signed_value):
# This unsign is identical to subclass except for the lowercasing
# See: https://github.com/django/django/blob/1.6.11/django/core/signing.py#L165-L172
signed_value = force_str(signed_value)
if self.sep not in signed_value:
raise BadSignature('No "%s" found in value' % self.sep)
value, sig = signed_value.rsplit(self.sep, 1)
if constant_time_compare(sig.lower(), self.signature(value)):
return force_text(value)
raise BadSignature('Signature "%s" does not match' % sig)
3
Example 42
def head(self, path, data={}, **extra):
"Construct a HEAD request."
parsed = urlparse(path)
r = {
'CONTENT_TYPE': str('text/html; charset=utf-8'),
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': urlencode(data, doseq=True) or force_str(parsed[4]),
'REQUEST_METHOD': str('HEAD'),
}
r.update(extra)
return self.request(**r)
3
Example 43
def get_model_data(self, model):
model_admin = self.registry[model]
model_options = utils.model_options(model)
opts = {
'current_app': model_admin.admin.name,
'app_label': model_options.app_label,
'model_name': model_options.object_name.lower(),
}
model_url = reverse(
'%(current_app)s:%(app_label)s_%(model_name)s_api_list' % opts,
request=self.request,
format=self.kwargs.get('format'))
model_options = utils.model_options(model)
return {
'url': model_url,
'verbose_name': force_str(model_options.verbose_name),
'verbose_name_plural': force_str(model_options.verbose_name_plural),
}
3
Example 44
def _run(self):
self._initialize()
for event in self.pubsub.listen():
if event['type'] == 'message':
args = json.loads(force_str(event['data']))
self.callback(*args)
3
Example 45
def encode(self, password, salt):
crypt = self._load_library()
assert len(salt) == 2
data = crypt.crypt(force_str(password), salt)
# we don't need to store the salt, but Django used to do this
return "%s$%s$%s" % (self.algorithm, '', data)
3
Example 46
def post(self, path, data={}, content_type=MULTIPART_CONTENT,
**extra):
"Construct a POST request."
post_data = self._encode_data(data, content_type)
parsed = urlparse(path)
r = {
'CONTENT_LENGTH': len(post_data),
'CONTENT_TYPE': content_type,
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': force_str(parsed[4]),
'REQUEST_METHOD': str('POST'),
'wsgi.input': FakePayload(post_data),
}
r.update(extra)
return self.request(**r)
3
Example 47
def generic(self, method, path,
data='', content_type='application/octet-stream', **extra):
parsed = urlparse(path)
data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': force_str(parsed[4]),
'REQUEST_METHOD': str(method),
}
if data:
r.update({
'CONTENT_LENGTH': len(data),
'CONTENT_TYPE': str(content_type),
'wsgi.input': FakePayload(data),
})
r.update(extra)
return self.request(**r)
3
Example 48
Project: PyClassLessons Source File: signing.py
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.sep = force_str(sep)
self.key = key or settings.SECRET_KEY
self.salt = force_str(salt or
'%s.%s' % (self.__class__.__module__, self.__class__.__name__))
3
Example 49
Project: django-daydreamer Source File: urlresolvers.py
def update_query(url, data):
"""
Update a URL's query string with additional data. The data may be a
dictionary or an instance of django.utils.datastructures.MultiValueDict.
The URL should be a string or a lazy string.
"""
parts = urlparse.urlparse(encoding.force_str(url))
return urlparse.urlunparse(
parts[:4] +
(lang.updated(
request.QueryDict(parts.query, mutable=True),
data or {}).urlencode(safe="/"),) +
parts[5:])
3
Example 50
Project: django Source File: signing.py
def __init__(self, key=None, sep=':', salt=None):
# Use of native strings in all versions of Python
self.key = key or settings.SECRET_KEY
self.sep = force_str(sep)
if _SEP_UNSAFE.match(self.sep):
raise ValueError(
'Unsafe Signer separator: %r (cannot be empty or consist of '
'only A-z0-9-_=)' % sep,
)
self.salt = force_str(salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__))