baidu_38409770
2020-09-01 17:22
采纳率: 42.9%
浏览 354
已采纳

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

封装了一下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条回答 默认 最新

  • threenewbee 2020-09-01 18:08
    已采纳

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • jingluan666 2020-09-01 17:48

    把header全部改成headers

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题