简体   繁体   中英

my python requests return 401 while postman returns 200

i make my requests class, the code is as below:

class RunMethod:

def post_main(self, url, data, header=None):
    res = None
    if header != None:
        res = requests.post(url=url, data=data, headers=header)
    else:
        res = requests.post(url=url, data=data)

    return res.json()

def get_main(self, url, data=None,header=None):
    res = None
    if header != None:
        res = requests.get(url=url,data=data,headers=header,verify=False)
    else:
        res = requests.get(url=url,data=data,verify=False)

    return res.json()

def run_main(self, method,url,data=None,headers=None):
    res = None
    if method == 'get':
        res = self.get_main(url, data, headers)
    else:
        res = self.post_main(url, data, headers)

and i capture an api from charles and test it in postman, it returns 200. i export python code from postman and it is like this:

import requests

url = "https://stargate.ar.elenet.me/minimart.service/intelligent/invoke"

querystring = {"traceId": "1000000294010",
           "shelfCode": "lu8ssMgCpgq00FDYdpX76Q..", "tracedAt": "1545641563164"}

payload = ""
headers = {
'X-STARGATE-ACCESS-TOKEN': "d7594351-0663-43a8-ad55-180c8b29db82",
'Cookie': "SID=NTVMAu8FKskyj06ln8J9uhS45fgcRNk1V3jQ; USERID=2228440841",
'Authorization': "ElemeAPI token",
'cache-control': "no-cache"
}

response = requests.request(
"GET", url, data=payload, headers=headers, params=querystring)

print(response.text)

it works, and i changed my class, put the data like this:

url = "https://stargate.ar.elenet.me/minimart.service/intelligent/invoke?traceId=1000000294010&shelfCode=lu8ssMgCpgq00FDYdpX76Q..&tracedAt=1545641563164"
headers = {
    'X-STARGATE-ACCESS-TOKEN': "d7594351-0663-43a8-ad55-180c8b29db82",
    'Cookie': "SID=NTVMAu8FKskyj06ln8J9uhS45fgcRNk1V3jQ; USERID=2228440841",
    'Authorization': "ElemeAPI token",
    'cache-control': "no-cache",
    'Content-Type':'application/json'
}

exam = RunMethod()
res = exam.run_main('get', url, headers)

i just put querystring into url, but it returns 401. i don't know where it's wrong. could anybody help me? thanks a lot!

The run_main accepts 4 arguments, exam.run_main('get', url, headers) provides only 3 of them ( method='get', url=url, data=headers, headers=None ).

I would recommend to use named arguments when skipping some of the optional ones:

exam.run_main('get', url, headers=headers)

Update your code in get_main method as per below code.

res = requests.get(url=url,params=data,headers=header,verify=False)

Here we are calling instantiated RunMethod class and calling run_main method.

exam = RunMethod()

res = exam.run_main('get', url, querystring, headers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM