Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

python - 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

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: {}>

I am trying to recreate this with 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

edit ---- I have also tried with the same result ( request.FILES -> <MultiValueDict: {}>)

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

Edit 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)
        
question from:https://stackoverflow.com/questions/65940236/django-testing-post-request-with-multipart-form-data-and-a-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...