简体   繁体   English

Django 使用多部分/表单数据和字典测试发布请求

[英]Django testing post request with multipart/form data and a dictionary

My client uses the requests library to make this call to my Django server我的客户端使用请求库来调用我的 Django 服务器

import requests
response = requests.post(url, files=dict({
            'value': 'key',
        }))

This will create a requests that inserts the dictionary into the field request.FILES as a <MultiValueDict: {}>这将创建一个请求,将字典插入字段request.FILES作为<MultiValueDict: {}>

I am trying to recreate this with django.test .我正在尝试使用django.test重新创建它。
I keep seeing to try something like我一直在尝试尝试类似的东西

from django.test import TestCase, Client
client = Client()
response = client.post('/sign', dict(request_data))

but the request.FILES object is empty但是request.FILES object 是空的

edit ---- I have also tried with the same result ( request.FILES -> <MultiValueDict: {}> )编辑 ---- 我也尝试过相同的结果( request.FILES -> <MultiValueDict: {}>

client.post('/sign', {'file': dict({
  'key' : 'value'
})})

Edit 2---编辑 2---

A look at the midldleware where I am checking the value查看我正在检查值的中间件


class ApiAuthenticationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        print(request.FILES)
        

Solution解决方案

        fake_file.name = 'data.json'
        post_data = {
            'data.json': fake_file,
        }
        return self.client.post('/sign', post_data,  content_type=MULTIPART_CONTENT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM