Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-requests - user-agent is being overriden

I have

    logindata = {
        'username': 'me',
        'password': 'blbla'
    }
    payload = {'from':'me', 'lang':'en', 'url':csv_url}
    headers = {
        'User-Agent': 'Mozilla/5.0'
    }
    api_url = 'http://dev.mypage.com/admin/app/import/'

    with requests.Session() as s:
        s.post(api_url, data=json.dumps(logindata), headers=headers)

        print s.headers

        # An authorised request.
        r = s.get(api_url, params=payload, headers=headers)

I am getting rejected but it is because of 403 forbidden. And I printed the headers, I get:

..'User-Agent': 'python-requests/2.2.1 CPython/2.7.5 Windows/7'..

Why is my 'User-Agent': 'Mozilla/5.0' getting overriden? what am I missing here?

like image 716
doniyor Avatar asked Jan 15 '15 16:01

doniyor


People also ask

What is user agent in Python requests?

user_agents is a Python library that provides an easy way to identify/detect devices like mobile phones, tablets and their capabilities by parsing (browser/HTTP) user agent strings.

What browser does Python Requests use?

Reading the Response First of all, we need to find out the response header and how it looks. You can use any modern web-browser to find it, but for this example, we will use Google's Chrome browser. This will open a new window within your browser.

How do you use Python requests to fake a browser visit Aka and generate user agent?

To use Python requests to fake a browser visit with a generated user agent,, we can use the fake_useragent library. Then we get the user agent string we want from the ua object. Next, we call requests. get to make a request to the url with the headers .


1 Answers

headers are not kept inside session this way.

You need to either explicitly pass them every time you make a request, or set the s.headers once:

with requests.Session() as s:
    s.headers = {'User-Agent': 'Mozilla/5.0'}

You can check that the correct headers were sent via inspecting response.request.headers:

with requests.Session() as s:
    s.headers = {'User-Agent': 'Mozilla/5.0'}

    r = s.post(api_url, data=json.dumps(logindata))
    print(r.request.headers)

Also see how the Session class is implemented - every time you make a request it merges the request.headers with headers you have set on the session object:

headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
like image 153
alecxe Avatar answered Sep 23 '22 13:09

alecxe