在对 web2py 端点的单个请求中将具有 json 负载的文件传递

Pass files with json payload in single requests to web2py endpoint

我在 web2pydefault.py 控制器中写了名为 foobar 的端点,它看起来像

@service.json
def foobar(*args, **vars):
    payload = request.vars.student
    print(payload)
    #Above payload prints [rollNo, firstName, lastName]
    #Expected is {"rollNo": 6299857, "FirstName": Prasad, "LastName": Telkikar}

    fileObj= request.vars.video
    studentActivity = fileObj.file.read()
    
    #Currently I am unable to do it from unit test, but it works from postman
    print(f"Student's Roll number = {payload.rollNo} \n FirstName = {payload.firstName},  \n lastName = {payload.lastName}, fileSize = {fileObj.file.tell()}")

    #storing studentActivity video to specific location
    #Doing business logic

现在我正在为此端点编写单元测试,我正在尝试使用 requests

调用此端点
import requests
import unittest

...
    
class TestStudentsData(unittest.TestCase):
    def test_Individual_student(self):
        payload = dict(rollNo=6299857, firstName="Prasad", lastName="Telkikar")
        url = "http://127.0.0.1:8000/v1/foobar"
        header = dict(Authorization="Bearer <Token>")
        response = requests.post(url,files={'studentActivity':open("Activity.mp4", 'rb')},  data=payload, headers=headers)

        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main(verbosity=2)

这里我无法将学生负载作为 json.

How can I pass json payload with studentActivity file using requests?


到目前为止我尝试了什么?

我通过将适当的 content-type 添加到 payload

解决了这个问题
import os

...

filePath = os.getcwd()
files = {'studentActivity':open(filePath, "Activity.mp4", 'rb'), 
             'payload':(None, payload, 'application/json')}
                                       #^^^^^^^^^^^^^^^^^ This was missing
 
response = requests.post(url,files={'studentActivity':open("Activity.mp4", 'rb')},  data=payload, headers=headers)