baidu_38409770
baidu_38409770
采纳率42.9%
2020-09-01 17:22

为什么python requests包请求接口header参数默认为none请求会失败

5
已采纳

封装了一下get和post请求,但是部分接口的请求不需要header或data,我设置默认参数为None,传进去后直接报错,报错信息如下;
图片说明

代码如下:

import requests
import json
class BaseRequest():
    def request_get(self,session,url, data=None, header=None, cookie=None):
        res = session.get(url=url, params=data, header=header,cookie=cookie)
        return res
    def request_post(self,session,url, data=None, header=None, cookie=None):
        res = session.post(url=url, data=data,header=header)
        return res
    def run_main(self,session,method,url, data=None, header=None, cookie=None):
        try:
            res = ''
            if method == 'get':
                res = BaseRequest().request_get(session=session,url=url,data=data,header=header,cookie=cookie)
            elif method == 'post':
                res = BaseRequest().request_post(session=session,url=url, data=data, header=header, cookie=cookie)
            return res
        except Exception as e:
            print('请求主函数调用失败:{}'.format(e))
    def get_token(self,r):
        a = json.loads(r.text)
        token = a.get('data').get('token')
        return token
        header = {'cookie': 'zuulToken=' + token}
if __name__ == '__main__':
    session = requests.session()
    base_request = BaseRequest()
    base_url = 'https://api-test-admin-zuul.qkduo.cn/'
    login_path = 'auth-center/nologin/login'
    getUserInfo_path = 'auth-center/noauth/getUserInfo'
    login_data = {
        'email': 'admin@qingclass.com',
        'password': 'e10adc3949ba59abbe56e057f20f883e'
    }
    getUserInfo_data = {}
    login_send = base_request.run_main(session=session,method='post',url=base_url+login_path, data=login_data)
    token = BaseRequest().get_token(login_send)
    header = {'cookie': 'zuulToken=' + token}
    print(header)
    # getUserInfo_send = base_request.run_main(session=session,method='get',url=base_url + getUserInfo_path, data=getUserInfo_data,header=header)
    # print(login_send.text)
#print(getUserInfo_send.text)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • caozhy 回答这么多问题就耍赖把我的积分一笔勾销了 7月前

    参数名(argument)是headers
    headers=header不是header=header

    点赞 1 评论 复制链接分享
  • jingluan666 jingluan666 7月前

    把header全部改成headers

    点赞 1 评论 复制链接分享