當前位置: 首頁>>代碼示例>>Python>>正文


Python encoding.smart_bytes方法代碼示例

本文整理匯總了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') 
開發者ID:yunojuno-archive,項目名稱:django-inbound-email,代碼行數:23,代碼來源:test_mailgun.py

示例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') 
開發者ID:yunojuno-archive,項目名稱:django-inbound-email,代碼行數:23,代碼來源:test_sendgrid.py

示例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()),
        } 
開發者ID:2buntu,項目名稱:2buntu-blog,代碼行數:23,代碼來源:views.py

示例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 
開發者ID:modoboa,項目名稱:modoboa-webmail,代碼行數:26,代碼來源:attachments.py

示例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 
開發者ID:impak-finance,項目名稱:django-oidc-rp,代碼行數:13,代碼來源:utils.py

示例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 
開發者ID:mozilla,項目名稱:mozilla-django-oidc,代碼行數:29,代碼來源:auth.py

示例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))) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:16,代碼來源:models.py

示例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))) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:8,代碼來源:django_orm.py

示例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 
開發者ID:mishbahr,項目名稱:django-responsive2,代碼行數:28,代碼來源:middleware.py

示例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))) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:11,代碼來源:models.py

示例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 
開發者ID:yunojuno-archive,項目名稱:django-inbound-email,代碼行數:32,代碼來源:mandrill.py

示例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']) 
開發者ID:yunojuno-archive,項目名稱:django-inbound-email,代碼行數:38,代碼來源:test_mandrill.py

示例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,
    ) 
開發者ID:2buntu,項目名稱:2buntu-blog,代碼行數:14,代碼來源:gravatar.py

示例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()),
        } 
開發者ID:2buntu,項目名稱:2buntu-blog,代碼行數:17,代碼來源:views.py

示例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() 
開發者ID:2buntu,項目名稱:2buntu-blog,代碼行數:13,代碼來源:tests.py


注:本文中的django.utils.encoding.smart_bytes方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。