M
M
MaBa20142020-03-20 15:51:14
Python
MaBa2014, 2020-03-20 15:51:14

How to save current python session while parsing json?

import requests

headers = {
        'Accept': 'application/json',
    }
params = (
    ('userName', 'Login'),
    ('password', 'Pass'),
    ('propertyId', '1'),
)

response = requests.get('http://ссылка на ресурс/api/Account', headers=headers, params=params)
print(" ")
print("Status code: " + str(response.status_code))
print(" ")
if response.status_code == 200:
    print("Запрос выполнен успешно")
else:
    print("Ошибка, проверьте заполненные данные и попробуйте снова")

print(" ")
print(response.json()["User"])#Выдает все данные пользователя, здесь никаких проблем
print(" ")

response = requests.get('http://этот же ресурс/api/Repair', headers=headers, params=params)
print("Status code: " + str(response.status_code))#Выдает статус 401

print(response.json())#Пишет Authorization has been denied for this request

Please tell me how can I save the current session, I assume that with the 2nd request, I simply lose authentication information. I
apologize in advance for the crooked code

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
noremorse_ru, 2020-03-20
@MaBa2014

Well, of course, you need to understand the http theory, if it is an api, then most likely the authorization will return a token in the body and it will need to be added to the headers, there may be 2 tokens, so you need to look at the documentation for the api with which you communicate. Those. the session will not help you here most likely as such, it just does part of the work for you, namely, it stores cookies and headers so as not to mix them up every time. The object itself is initialized like this: requests.Session()
PS In print, you can write lines separated by commas, and not produce dozens of them. And if you check the status of the response code, then it’s better to do it through assert, because the code will be executed further, and in your case the code depends on the response, it makes no sense to continue doing something if the response is not what we expect

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question