本文整理汇总了Python中django.utils.encoding.smart_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python encoding.smart_bytes方法的具体用法?Python encoding.smart_bytes怎么用?Python encoding.smart_bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.encoding
的用法示例。
在下文中一共展示了encoding.smart_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_attachments
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def test_attachments(self):
"""Test inbound email with attachments."""
data = mailgun_payload
attachment_1 = open(self.test_upload_txt, 'r').read()
attachment_2 = open(self.test_upload_png, 'rb').read()
data['attachment-1'] = open(self.test_upload_txt, 'r')
data['attachment-2'] = open(self.test_upload_png, 'rb')
request = self.factory.post(self.url, data=data)
email = self.parser.parse(request)
self._assertEmailParsedCorrectly(email, data)
# for each attachmen, check the contents match the input
self.assertEqual(len(email.attachments), 2)
# convert list of 3-tuples into dict so we can lookup by filename
attachments = {k[0]: (k[1], k[2]) for k in email.attachments}
self.assertEqual(smart_bytes(attachments['attachment-1'][0]), smart_bytes(attachment_1))
self.assertEqual(attachments['attachment-1'][1], 'text/plain')
self.assertEqual(attachments['attachment-2'][0], attachment_2)
self.assertEqual(attachments['attachment-2'][1], 'image/jpeg')
示例2: test_attachments
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def test_attachments(self):
"""Test inbound email with attachments."""
data = sendgrid_payload
attachment_1 = open(self.test_upload_txt, 'r').read()
attachment_2 = open(self.test_upload_png, 'rb').read()
data['attachment1'] = open(self.test_upload_txt, 'r')
data['attachment2'] = open(self.test_upload_png, 'rb')
request = self.factory.post(self.url, data=data)
email = self.parser.parse(request)
self._assertEmailParsedCorrectly(email, data)
# for each attachmen, check the contents match the input
self.assertEqual(len(email.attachments), 2)
# convert list of 3-tuples into dict so we can lookup by filename
attachments = {k[0]: (k[1], k[2]) for k in email.attachments}
self.assertEqual(smart_bytes(attachments['test_upload_file.txt'][0]), smart_bytes(attachment_1))
self.assertEqual(attachments['test_upload_file.txt'][1], 'text/plain')
self.assertEqual(attachments['test_upload_file.jpg'][0], attachment_2)
self.assertEqual(attachments['test_upload_file.jpg'][1], 'image/jpeg')
示例3: _encode_article
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _encode_article(self, article):
"""
Encode an article.
"""
return {
'id': article.id,
'title': smart_text(article),
'author': {
'id': article.author.id,
'name': smart_text(article.author.profile),
'email_hash': md5(smart_bytes(article.author.email)).hexdigest(),
},
'category': {
'id': article.category.id,
'name': article.category.name,
},
'body': article.render(),
'cc_license': article.cc_license,
'date': timegm(article.date.utctimetuple()),
'url': self._request.build_absolute_uri(article.get_absolute_url()),
}
示例4: save_attachment
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def save_attachment(f):
"""Save a new attachment to the filesystem.
The attachment is not saved using its own name to the
filesystem. To avoid conflicts, a random name is generated and
used instead.
:param f: an uploaded file object (see Django's documentation) or bytes
:return: the new random name
"""
from tempfile import NamedTemporaryFile
dstdir = os.path.join(settings.MEDIA_ROOT, "webmail")
try:
fp = NamedTemporaryFile(dir=dstdir, delete=False)
except Exception as e:
raise InternalError(str(e))
if isinstance(f, (six.binary_type, six.text_type)):
fp.write(smart_bytes(f))
else:
for chunk in f.chunks():
fp.write(chunk)
fp.close()
return fp.name
示例5: _get_jwks_keys
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _get_jwks_keys(shared_key):
""" Returns JWKS keys used to decrypt id_token values. """
# The OpenID Connect Provider (OP) uses RSA keys to sign/enrypt ID tokens and generate public
# keys allowing to decrypt them. These public keys are exposed through the 'jwks_uri' and should
# be used to decrypt the JWS - JSON Web Signature.
jwks_keys = KEYS()
jwks_keys.load_from_url(oidc_rp_settings.PROVIDER_JWKS_ENDPOINT)
# Adds the shared key (which can correspond to the client_secret) as an oct key so it can be
# used for HMAC signatures.
jwks_keys.add({'key': smart_bytes(shared_key), 'kty': 'oct'})
return jwks_keys
示例6: _verify_jws
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _verify_jws(self, payload, key):
"""Verify the given JWS payload with the given key and return the payload"""
jws = JWS.from_compact(payload)
try:
alg = jws.signature.combined.alg.name
except KeyError:
msg = 'No alg value found in header'
raise SuspiciousOperation(msg)
if alg != self.OIDC_RP_SIGN_ALGO:
msg = "The provider algorithm {!r} does not match the client's " \
"OIDC_RP_SIGN_ALGO.".format(alg)
raise SuspiciousOperation(msg)
if isinstance(key, six.string_types):
# Use smart_bytes here since the key string comes from settings.
jwk = JWK.load(smart_bytes(key))
else:
# The key is a json returned from the IDP JWKS endpoint.
jwk = JWK.from_json(key)
if not jws.verify(jwk):
msg = 'JWS token verification failed.'
raise SuspiciousOperation(msg)
return jws.payload
示例7: to_python
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def to_python(self, value):
"""Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class"""
if value is None:
return None
elif isinstance(value, oauth2client.client.Credentials):
return value
else:
try:
return jsonpickle.decode(
base64.b64decode(encoding.smart_bytes(value)).decode())
except ValueError:
return pickle.loads(
base64.b64decode(encoding.smart_bytes(value)))
示例8: to_python
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(smart_bytes(value)))
示例9: process_response
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def process_response(self, request, response):
html_types = ('text/html', 'application/xhtml+xml')
content_type = response.get('Content-Type', '').split(';')[0]
content_encoding = response.get('Content-Encoding', '')
if any((getattr(response, 'streaming', False),
'gzip' in content_encoding,
content_type not in html_types)):
return response
if settings.RESPONSIVE_COOKIE_NAME not in request.COOKIES \
or getattr(request, 'INVALID_RESPONSIVE_COOKIE', False):
expires = datetime.datetime.utcnow() + \
datetime.timedelta(days=settings.RESPONSIVE_COOKIE_AGE)
snippet = render_to_string('responsive/snippet.html', {
'cookie_name': settings.RESPONSIVE_COOKIE_NAME,
'cookie_age': 60 * 60 * 24 * settings.RESPONSIVE_COOKIE_AGE, # convert to secs
'cookie_expires': expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
})
pattern = re.compile(b'<head()>|<head (.*?)>', re.IGNORECASE)
response.content = pattern.sub(b'<head\g<1>>' + smart_bytes(snippet), response.content)
if response.get('Content-Length', None):
response['Content-Length'] = len(response.content)
patch_vary_headers(response, ('Cookie', ))
return response
示例10: to_python
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def to_python(self, value):
"""Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class"""
if value is None:
return None
elif isinstance(value, oauth2client.client.Credentials):
return value
else:
return pickle.loads(base64.b64decode(encoding.smart_bytes(value)))
示例11: _process_attachments
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _process_attachments(self, email, attachments):
for key, attachment in list(attachments.items()):
is_base64 = attachment.get('base64')
name = attachment.get('name')
mimetype = attachment.get('type')
content = attachment.get('content', "")
if is_base64:
content = base64.b64decode(content)
# watchout: sometimes attachment contents are base64'd but mandrill doesn't set the flag
elif _detect_base64(content):
content = base64.b64decode(content)
content = smart_bytes(content, strings_only=True)
if len(content) > self.max_file_size:
logger.debug(
"File attachment %s is too large to process (%sB)",
name,
len(content)
)
raise AttachmentTooLargeError(
email=email,
filename=name,
size=len(content)
)
if name and mimetype and content:
email.attach(name, content, mimetype)
return email
示例12: _assertEmailParsedCorrectly
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _assertEmailParsedCorrectly(self, emails, mandrill_payload, has_html=True):
def _parse_emails(to):
ret = []
for address, name in to:
if not name:
ret.append(address)
else:
ret.append("\"%s\" <%s>" % (name, address))
return ret
def _parse_from(name, email):
if not name:
return email
return "\"%s\" <%s>" % (name, email)
for i, e in enumerate(emails):
msg = json.loads(mandrill_payload['mandrill_events'])[i]['msg']
self.assertEqual(e.subject, msg['subject'])
self.assertEqual(e.to, _parse_emails(msg['to']))
self.assertEqual(e.cc, _parse_emails(msg['cc']))
self.assertEqual(e.bcc, _parse_emails(msg['bcc']))
self.assertEqual(
e.from_email,
_parse_from(msg.get('from_name'), msg.get('from_email'))
)
if has_html:
self.assertEqual(e.alternatives[0][0], msg['html'])
for name, contents, mimetype in e.attachments:
# Check that base64 contents are decoded
is_base64 = msg['attachments'][name].get('base64')
req_contents = msg['attachments'][name]['content']
if is_base64:
req_contents = base64.b64decode(req_contents)
self.assertEqual(smart_bytes(req_contents), smart_bytes(contents))
self.assertEqual(msg['attachments'][name]['type'], mimetype)
self.assertEqual(e.body, msg['text'])
示例13: gravatar
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def gravatar(email, size=64):
"""
Return the Gravatar URL for the provided email.
:param email: the email address to hash
:param size: the size of the Gravatar to generate
:returns: the URL of the image
"""
return '//gravatar.com/avatar/%s?d=identicon&size=%s' % (
md5(smart_bytes(email)).hexdigest(),
size,
)
示例14: _encode_profile
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def _encode_profile(self, profile):
"""
Encode a profile.
"""
return {
'id': profile.user.id,
'name': smart_text(profile),
'email_hash': md5(smart_bytes(profile.user.email)).hexdigest(),
'age': profile.age(),
'location': profile.location,
'website': profile.website,
'bio': profile.bio,
'last_seen': timegm(profile.user.last_login.utctimetuple()) if profile.user.last_login else 0,
'url': self._request.build_absolute_uri(profile.get_absolute_url()),
}
示例15: setUp
# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import smart_bytes [as 别名]
def setUp(self):
# Create a dummy user, category, and article
user = User.objects.create_user('user', 'user@example.com', 'user')
category = Category(name='Test')
category.save()
self.article = Article(author=user, category=category, title='Test', body='Test', status=Article.PUBLISHED, date=now())
self.article.save()
# Create a dummy image
o = BytesIO(smart_bytes('x\x9cb`\x01\x00\x00\x00\xff\xff\x03\x00\x00\x06\x00\x05'))
self.image = Image(caption='Test', image=File(o, name='test.png'))
self.image.save()