Python django.test.client 模块,encode_multipart() 实例源码

我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用django.test.client.encode_multipart()

项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_modify_avatar_by_teacher(self):
        # Teacher role not allowed to modify avatar.
        username = "test1"
        password = "123123"
        user = User.objects.get(username=username)

        change_profile_perm = Permission.objects.get(name='Can change profile')
        user.user_permissions.add(change_profile_perm)
        user.save()

        client = Client()
        client.login(username=username, password=password)
        request_url = "/api/v1/profiles/%d" % (user.profile.pk,)
        img_name = 'img0'  # NOTE: seq is 0 not 1, seq of the user 'parent1'
        img_path = os.path.join(
                app_path, 'migrations', 'avatars', img_name + '.jpg')
        # print(img_path)
        img_fd = open(img_path, 'rb')
        data = {'avatar': img_fd}
        encoded_data = encode_multipart(BOUNDARY, data)
        response = client.patch(request_url, content_type=MULTIPART_CONTENT,
                                data=encoded_data)
        self.assertEqual(409, response.status_code)
项目:prestashop-sync    作者:dragoon    | 项目源码 | 文件源码
def add_images(self, product_ids, images):
        domain = self.shop.domain
        headers = {'Content-Type': MULTIPART_CONTENT,
                   'Authorization': self.shop.authheader}
        for i, p_images in enumerate(images):
            # TODO: why sometimes index does not exist?
            if i >= len(product_ids):
                send_email.delay('mail/error', {'domain': domain, 'message': str(product_ids),
                                                'data_list': '',
                                                'full_data': ''}, "Add images error")
                break
            product_id = product_ids[i]
            for image in p_images:
                data = encode_multipart(BOUNDARY, {'image': image})
                req = urllib2.Request(smart_str("http://%s/api/images/products/%s" % (domain, product_id)),
                                      headers=headers, data=smart_str(data))
                urllib2.urlopen(req)
        self.make_first_image_default(product_ids, headers)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_modify_user_avatar(self):
        username = "parent1"
        password = "123123"
        user = User.objects.get(username=username)

        change_profile_perm = Permission.objects.get(name='Can change profile')
        user.user_permissions.add(change_profile_perm)
        user.save()

        client = Client()
        client.login(username=username, password=password)
        request_url = "/api/v1/profiles/%d" % (user.profile.pk,)
        img_name = 'img0'  # NOTE: seq is 0 not 1, seq of the user 'parent1'
        img_path = os.path.join(
                app_path, 'migrations', 'avatars', img_name + '.jpg')
        # print(img_path)
        img_fd = open(img_path, 'rb')
        data = {'avatar': img_fd}
        encoded_data = encode_multipart(BOUNDARY, data)
        response = client.patch(request_url, content_type=MULTIPART_CONTENT,
                                data=encoded_data)
        self.assertEqual(200, response.status_code)
        json_ret = json.loads(response.content.decode())
        self.assertEqual(json_ret["done"], "true")
        profile_after = Profile.objects.get(user=user)
        # print(profile_after.avatar_url())
        self.assertTrue(profile_after.avatar.url.find(img_name) >= 0)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def render(self, data, accepted_media_type=None, renderer_context=None):
        if hasattr(data, 'items'):
            for key, value in data.items():
                assert not isinstance(value, dict), (
                    "Test data contained a dictionary value for key '%s', "
                    "but multipart uploads do not support nested data. "
                    "You may want to consider using format='json' in this "
                    "test case." % key
                )
        return encode_multipart(self.BOUNDARY, data)
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def render(self, data, accepted_media_type=None, renderer_context=None):
        if hasattr(data, 'items'):
            for key, value in data.items():
                assert not isinstance(value, dict), (
                    "Test data contained a dictionary value for key '%s', "
                    "but multipart uploads do not support nested data. "
                    "You may want to consider using format='json' in this "
                    "test case." % key
                )
        return encode_multipart(self.BOUNDARY, data)
项目:django-skivvy    作者:Cadasta    | 项目源码 | 文件源码
def _get_post_data(self, post_data={}, content_type='application/json'):
        post_data = super()._get_post_data(post_data)
        if content_type == 'multipart/form-data':
            self.content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
            post_data = encode_multipart('BoUnDaRyStRiNg', post_data)

        else:
            post_data = json.dumps(post_data).encode()
        return post_data
项目:maas    作者:maas    | 项目源码 | 文件源码
def transparent_encode_multipart(func):
    """Wrap an HTTP client method, transparently encoding multipart data.

    This wraps some of Django's `Client` HTTP verb methods -- delete, options,
    patch, put -- so they accept a dict of data to be sent as part of the
    request body, in MIME multipart encoding.

    This also accepts an optional dict of query parameters (as `query`) to be
    encoded as a query string and appended to the given path.

    Since Django 1.5, these HTTP verb methods require data in the form of a
    byte string. The application (that's us) needs to take care of MIME
    encoding.
    """
    @wraps(func)
    def maybe_encode_multipart(
            self, path, data=b"", content_type=None, secure=False, query=None,
            **extra):

        if isinstance(data, bytes):
            if content_type is None:
                content_type = 'application/octet-stream'
        elif content_type is None:
            content_type = client.MULTIPART_CONTENT
            data = client.encode_multipart(client.BOUNDARY, data)
        else:
            raise TypeError(
                "Cannot combine data (%r) with content-type (%r)."
                % (data, content_type))

        if query is not None:
            query = urlencode(query, doseq=True)
            path = path + ("&" if "?" in path else "?") + query

        return func(self, path, data, content_type, secure, **extra)

    return maybe_encode_multipart