doniyor
doniyor

Reputation: 37846

python requests - 403 forbidden

I have this

payload = {'from':'me', 'lang':lang, 'url':csv_url}
headers = {
   'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
}

api_url = 'http://dev.mypage.com/app/import/'
sent = requests.get(api_url , params=payload, headers=headers)

I just keep getting 403. I am looking up to this requests docs

what am I doing wrong?

UPDATE:

The url only accepts loggedin users. how can I login there with requests?

Upvotes: 1

Views: 11999

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

This is how it's usually done using a Session object:

# start new session to persist data between requests
session = requests.Session()

# log in session
response = session.post(
    'http://dev.mypage.com/login/',
    data={'user':'username', 'password':'12345'}
)

# make sure log in was successful
if not 200 <= response.status_code < 300:
    raise Exception("Error while logging in, code: %d" % response. status_code)

# ... use session object to make logged-in requests, your example:
api_url = 'http://dev.mypage.com/app/import/'
sent = session.get(api_url , params=payload, headers=headers)

You should obviously adapt this to your usage scenario.

The reason a session is needed is that the HTTP protocol does not have the concept of a session, so sessions are implemented over HTTP.

Upvotes: 1

Related Questions