晚上写了一个请求类,传了一个动态参数进去,实例化测试的时候,发现请求数据根本没法读到,先附上代码
import requests class MyRequests: def send_request(self, method, url, **kwargs): if method.lower()== "get": res = requests.request(method, url, params=kwargs) elif method.lower() == "post": res = requests.request(method, url, data=kwargs) print(res.text) mr = MyRequests() mr.send_request("get", "http://localhost:8080/futureloan/mvc/api/member/register",params={"mobilephone":"13923715845","pwd":"test123"})
期望的数据是注册成功,但是怎么试都是手机号为空
{"status":0,"code":"20103","data":null,"msg":"手机号不能为空"}
为什么?问题就出在if判断之后,如果请求方式是get,就让params=kwargs,如果请求方式是post,data=kwargs,但是实例化的时候就出问题了,**kwargs要求必须以关键字参数(key=value的形式)传入,传入的是params={"mobilephone":"13923715845","pwd":"test123"}),这时候经过if判断后,就成了
res = requests.request(method, url, params=‘params={"mobilephone":"13923715845","pwd":"test123"}‘)
这种请求参数,服务器当然是识别不到参数"mobilephone"和"pwd"了,所以这是一个容易出问题的写法,如何避免呢?
import requests class MyRequests: def send_request(self, method, url, **kwargs): res = requests.request(method, url, **kwargs) print(res.text) mr = MyRequests() mr.send_request("get", "http://localhost:8080/futureloan/mvc/api/member/register",params={"mobilephone":"13923715845","pwd":"test123"})
这就得到了我们想要的结果
{"status":1,"code":"10001","data":null,"msg":"注册成功"}
原文地址:https://www.cnblogs.com/cnhkzyy/p/9315634.html
时间: 2024-10-16 02:31:15