Requests в python

Коды состояния

Проверим код состояния ответа. Коды состояния HTTP варьируются от 1XX до 5XX. Скорее всего, вы сталкивались с кодами состояния 200, 404 и 500.

Что обозначает каждый из них:

  • 1XX – информация.
  • 2XX – успешно.
  • 3XX – перенаправление.
  • 4XX — Ошибка клиента.
  • 5XX — Ошибка сервера.

Обычно при выполнении запросов приходят коды состояния 2ХХ. Коды 4XX и 5XX являются ошибками. При их получении ответ расценивается как False.

Вы можете проверить результативность запроса с помощью следующего кода:

if res:
    print('Response OK')
else:
    print('Response Failed')

Чтобы увидеть ответ с ошибкой 404, измените URL-адрес на произвольные знаки. Можно проверить код состояния, выполнив:

print(res.status_code)

Также можно проверить код состояния самостоятельно.

Производительность

При использовании , особенно в продакшене, важно учитывать влияние на производительность. Такие функции, как контроль времени ожидания, сеансы и ограничения повторных попыток, могут обеспечить вам бесперебойную работу приложения

Время ожидания

Когда вы отправляете запрос во внешнюю службу, вашей системе потребуется дождаться ответа, прежде чем двигаться дальше. Если ваше предложение слишком долго ожидает ответа — запросы к службе могут быть скопированы, пользовательский интерфейс может пострадать или фоновые задания могут зависнуть.

По умолчанию, будет ждать ответа до бесконечности, поэтому вы почти всегда должны указывать время ожидания. Чтобы установить время ожидания, используйте параметр . Тайм-аут может быть целым числом или числом с плавающей запятой, представляющим количество секунд ожидания ответа:

В первом запросе, время ожидания истекает через одну секунду. Во втором — через 3,05 секунд.

Вы также можете передать кортеж тайм-ауту. Первый элемент в кортеже является тайм-аутом соединения (время, которое позволяет установить клиенту соединение с сервером), а второй элемент — время ожидания чтения (время ожидания ответа после того, как клиент установил соединение):

Если запрос устанавливает соединение в течение 2 секунд и получает данные в течение 5 секунд после установки соединения, то ответ будет возвращен. Если время ожидания истекло — функция вызовет исключение :

Ваша программа может перехватить исключение и ответить соответствующим образом.

Объект Session

До сих пор вы имели дело с интерфейсами API высокого уровня, такими как и . Эти функции являются абстракциями над тем, что происходит когда вы делаете свои запросы. Они скрывают детали реализации, такие как управление соединениями, так что вам не нужно беспокоиться о них.

Под этими абстракциями находится класс . Если вам необходимо настроить контроль над выполнением запросов и повысить производительность вашего приложения — вам может потребоваться использовать экземпляр напрямую.

Сеансы используются для сохранения параметров в запросах. Например, если вы хотите использовать одну и ту же аутентификацию для нескольких запросов, вы можете использовать сеанс:

Каждый раз, когда вы делаете запрос в сеансе, после того, как он был инициализирован с учетными данными аутентификации, учетные данные будут сохраняться.

Первичная оптимизация производительности сессий происходит в форме постоянных соединений. Когда ваше приложение устанавливает соединение с сервером, используя , оно сохраняет это соединение в пуле с остальными соединениями. Когда ваше приложение снова подключиться к тому же серверу, оно будет повторно использовать соединение из пула, а не устанавливать новое.

Максимальное количество попыток

В случае сбоя запроса, вы можете захотеть, чтобы приложение отправило запрос повторно. Однако не делает этого за вас по умолчанию. Чтобы реализовать эту функцию, вам необходимо реализовать собственный .

Транспортные адаптеры позволяют вам определять набор конфигураций для каждой службы , с которой вы взаимодействуете. Например, вы хотите, чтобы все запросы к https://api.github.com, повторялись по три раза, прежде чем вызовется исключение . Вы должны сконструировать транспортный адаптер, установить его параметр и подключить его к существующему сеансу:

Когда вы монтируете и в — будет придерживаться этой конфигурации в каждом запросе к https://api.github.com.

Время ожидания, транспортные адаптеры и сеансы, предназначены для обеспечения эффективности вашего кода и отказоустойчивости приложения.

Using the Translate API

So now let’s move on to something more interesting. We’ll use the Yandex Translate API to perform a request to translate some text to a different language.

To use the API, first you need to sign up. After you sign up, go to the Translate API and create an API key. Once you have the API key, add it to your file as a constant. Here’s the link where you can do all those things: https://tech.yandex.com/translate/

The reason why we need an API key is so Yandex can authenticate us every time we want to use their API. The API key is probably the simplest form of authentication, because it’s simply added on to the end of the request URL when being sent.

To know which URL we need to send to use the API, we can look at the documentation for Yandex here: https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/

If we look there, we’ll see all the information needed to use their Translate API to translate text.

API documentation can be difficult to read at times, but in this case it’s simple. When we see a URL with ampersands (&), question marks (?), and equals signs (=), you can be sure that the URL is for GET requests. Those symbols specify the parameters that go along with the URL.

Normally things in square brackets ([]) will be optional. In this case, format, options, and callback are optional, while the key, text, and lang are required for the request.

And of course it’s easy to see the URL. So let’s add some code to send to that URL. You can replace the first request we created with this:

There are two ways we can add the parameters. We can either append it to the end of the URL directly, or we can have Requests do it for us. Having Requests do it for us is much easier.

To do that, we can create a dictionary for our parameters. The three items we need are the key, the text, and the language.

Let’s create the dictionary using the API key, ‘Hello’ for the text, and ‘en-es’ as the lang, which means we want to translate from English to Spanish.

If you need to know any other language codes, you can look here: https://en.wikipedia.org/wiki/List\_of\_ISO\_639-1\_codes You are looking for the 639-1 column.

We create a params dictionary by using the dict() function and passing in the keys and values we want in our dictionary.

Now we take the parameters dictionary and pass it to the .get() function.

When we pass the parameters this way, Requests will go ahead and add the parameters to the URL for us.

Now let’s add a print statement for the response text and view what gets returned in the response.

We see three things. We see the status code, which is exactly the same status code of the response itself, we see the language that we specified, and we see the translated text inside of the list. So you should see ‘Hola’ for the translated text.

Try again with en-fr as the language code, and you should see ‘Boujour’ in the response now.

Let’s take a look at the headers for this particular response.

Obviously the headers should be different because we’re communicating with a different server, but in this case the content type is application/json instead of text/html. What this means that the data can be interpreted as JSON.

When application/json is the content type of the response, we are able to have Requests convert the response to a dictionary and list so we can access the data easier.

To have the data parsed as JSON, we use the .json() method on the response object.

If you print it, you’ll see that the data looks the same, but the format is slightly different.

The reason why it’s different is because it’s no longer plain text that you get from res.text. This time it’s a printed version of a dictionary.

Let’s say we want to access the text. Since this is now a dictionary, we can use the text key.

And now we only see the data for that one key. In this case we are looking at a list of one item, so if we wanted to get that text in the list directly, we can access it by the index.

And now the only thing we see is the translated word.

So of course if we change things in our parameters, we’ll get different results. Let’s change the text to be translated from Hello to Goodbye, change the target language back to Spanish, and send the request again.

Try translating longer text in different languages and see what responses the API gives you.

Parameter Values

Parameter Description
url Try it Required. The url of the request
params Try it Optional. A dictionary, list of tuples or bytes to send as a query string.Default
allow_redirects Try it Optional. A Boolean to enable/disable redirection.Default
(allowing redirects)
auth Try it Optional. A tuple to enable a certain HTTP authentication.Default

cert Try it Optional. A String or Tuple specifying a cert file or key.Default

cookies Try it Optional. A dictionary of cookies to send to the specified url.Default

headers Try it Optional. A dictionary of HTTP headers to send to the specified url.Default
proxies Try it Optional. A dictionary of the protocol to the proxy url.Default

stream Try it Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True).Default

timeout Try it Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response.Default which means the request will continue
until the connection is closed
verify Try it
Try it
Optional. A Boolean or a String indication to verify the servers TLS certificate or not.Default

Python requests get method

The method issues a GET request to the server.
The GET method requests a representation of the specified resource.

The is a freely available HTTP Request & Response Service.

mget.py

#!/usr/bin/env python3

import requests as req

resp = req.get("https://httpbin.org/get?name=Peter")
print(resp.text)

The script sends a variable with a value to the
server. The variable is specified directly in the URL.

$ ./mget.py
{
  "args": {
    "name": "Peter"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.21.0"
  },
  ...
}

This is the output of the example.

mget2.py

#!/usr/bin/env python3

import requests as req

payload = {'name': 'Peter', 'age': 23}
resp = req.get("https://httpbin.org/get", params=payload)

print(resp.url)
print(resp.text)

The method takes a parameter where
we can specify the query parameters.

payload = {'name': 'Peter', 'age': 23}

The data is sent in a Python dictionary.

resp = req.get("https://httpbin.org/get", params=payload)

We send a GET request to the site and
pass the data, which is specified in the parameter.

print(resp.url)
print(resp.text)

We print the URL and the response content to the console.

$ ./mget2.py
http://httpbin.org/get?name=Peter&age=23
{
  "args": {
    "age": "23",
    "name": "Peter"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.21.0"
  },
  ...
}

This is the output of the example.

Python GET request with urllib3

A GET request is created with the method, which receives
the value as its first parameter.

get_req.py

#!/usr/bin/python

import urllib3

http = urllib3.PoolManager()

url = 'http://webcode.me'

resp = http.request('GET', url)
print(resp.data.decode('utf-8'))

A GET request is sent to webcode.me.

$ ./get_req.py 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>
    
    <p>
         Hello there. How are you?
    </p>
    
</body>
</html>

Использование Translate API

Теперь перейдем к чему-то более интересному. Мы используем API Яндекс.Перевод (Yandex Translate API) для выполнения запроса на перевод текста на другой язык.

Чтобы использовать API, нужно предварительно войти в систему. После входа в систему перейдите к Translate API и создайте ключ API. Когда у вас будет ключ API, добавьте его в свой файл в качестве константы. Далее приведена ссылка, с помощью которой вы можете сделать все перечисленное: https://tech.yandex.com/translate/

script.py

Ключ API нужен, чтобы Яндекс мог проводить аутентификацию каждый раз, когда мы хотим использовать его API. Ключ API представляет собой облегченную форму аутентификации, поскольку он добавляется в конце URL запроса при отправке.

Чтобы узнать, какой URL нам нужно отправить для использования API, посмотрим документацию Яндекса.

Там мы найдем всю информацию, необходимую для использования их Translate API для перевода текста.

Если вы видите URL с символами амперсанда (&), знаками вопроса (?) или знаками равенства (=), вы можете быть уверены, что это URL запроса GET. Эти символы задают сопутствующие параметры для URL.

Обычно все, что размещено в квадратных скобках ([]), будет необязательным. В данном случае для запроса необязательны формат, опции и обратная связь, но обязательны параметры key, text и lang.

Добавим код для отправки на этот URL. Замените первый созданный нами запрос на следующий:

script.py

Существует два способа добавления параметров. Мы можем прямо добавить параметры в конец URL, или библиотека Requests может сделать это за нас. Для последнего нам потребуется создать словарь параметров. Нам нужно указать три элемента: ключ, текст и язык. Создадим словарь, используя ключ API, текст и язык , т. к. нам требуется перевод с английского на испанский.

Другие коды языков можно посмотреть здесь. Нам нужен столбец 639-1.

Мы создаем словарь параметров, используя функцию , и передаем ключи и значения, которые хотим использовать в нашем словаре.

script.py

Теперь возьмем словарь параметров и передадим его функции .

script.py

Когда мы передаем параметры таким образом, Requests автоматически добавляет параметры в URL за нас.

Теперь добавим команду печати текста ответа и посмотрим, что мы получим в результате.

script.py

Мы видим три вещи. Мы видим код состояния, который совпадает с кодом состояния ответа, мы видим заданный нами язык и мы видим переведенный текст внутри списка. Итак, мы должны увидеть переведенный текст .

Повторите эту процедуру с кодом языка en-fr, и вы получите ответ .

script.py

Посмотрим заголовки полученного ответа.

script.py

Разумеется, заголовки должны быть другими, поскольку мы взаимодействуем с другим сервером, но в данном случае мы видим тип контента application/json вместо text/html. Это означает, что эти данные могут быть интерпретированы в формате JSON.

Если ответ имеет тип контента application/json, библиотека Requests может конвертировать его в словарь и список, чтобы нам было удобнее просматривать данные.

Для обработки данных в формате JSON мы используем метод на объекте response.

Если вы распечатаете его, вы увидите те же данные, но в немного другом формате.

script.py

Причина отличия заключается в том, что это уже не обычный текст, который мы получаем из файла res.text. В данном случае это печатная версия словаря.

Допустим, нам нужно получить доступ к тексту. Поскольку сейчас это словарь, мы можем использовать ключ текста.

script.py

Теперь мы видим данные только для этого одного ключа. В данном случае мы видим список из одного элемента, так что если мы захотим напрямую получить текст в списке, мы можем использовать указатель для доступа к нему.

script.py

Теперь мы видим только переведенное слово.

Разумеется, если мы изменим параметры, мы получим другие результаты. Изменим переводимый текст с на , изменим язык перевода на испанский и снова отправим запрос.

script.py

Попробуйте перевести более длинный текст на другие языки и посмотрите, какие ответы будет вам присылать API.

Текст ответа

Если мы посмотрим на файл (это работает для текстовых данных, таких как просматриваемая нами страница HTML), мы увидим весь код HTML, требуемый для построения домашней страницы Scotch. Рендеринг выполняться не будет, но мы увидим, что он принадлежит Scotch. Если вы сохраните этот код в файл и откроете его, вы увидите что-то похожее на сайт Scotch. В реальных условиях для загрузки на одну веб-страницу изображений, скриптов, таблиц стилей и т. д. отправляется несколько запросов, так что если вы сохраните в файл только код HTML и откроете его в браузере, результат не будет похож на страницу Scotch.io, поскольку для получения данных HTML был отправлен только один запрос.

script.py

Используем Translate API

Мы будем использовать Yandex Translate API. После регистрации перейдите в Translate API и создайте ключ API. Получив ключ API, добавьте его в свой файл. Вот ссылка на сайт, где это можно сделать: https://yandex.ru/dev/translate/

API_KEY = 'your yandex api key'

Ключ API нужен, чтобы Яндекс мог аутентифицировать нас. Ключ API добавляется в конец URL-адреса запроса при отправке.

Чтобы узнать, какой URL-адрес нам нужно отправить для использования API, обратимся к документации Яндекса:

https://yandex.ru/dev/translate/doc/dg/reference/translate-docpage/

Здесь доступна вся информация по использованию Translate API для перевода текста.

Если в документации указан URL с амперсандами (&), вопросительными знаками (?) и знаками равенства (=), значит он предназначен для отправки GET- запросов

Параметры, размещенные в квадратных скобках ([]), не является обязательными. В данном случае format, options и callback являются необязательными. Но key, text и lang обязательны для запроса.

Добавим код для отправки на этот URL. Можно заменить созданный нами запрос следующим образом:

url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'
res = requests.get(url)

Параметры можно добавить в конец URL-адреса. Но библиотека  Requests может сделать это за нас. Причем второй вариант гораздо проще.

Для его реализации создадим словарь для параметров. Понадобятся только key, text и language. Создадим словарь, используя следующие значения: API key, «Hello» для текста и «en-es» для lang (для перевода с английского на испанский).

Передадим функции dict() нужные ключи и значения:

params = dict(key=API_KEY, text='Hello', lang='en-es')

Теперь передаем словарь параметров в функцию .get().

res = requests.get(url, params=params)

После этого библиотека Requests добавит параметры к URL-адресу. Теперь используем оператор print для response text и посмотрим, что вернется в ответе.

print(res.text)

Мы получили code (код состояния), совпадающий с кодом состояния ответа. А также language (язык), который мы указали, и перевод. Поэтому вы должны увидеть переведенный текст «Hola».

Попробуйте еще раз со значением кода языка en-fr и получите «Bonjour».

params = dict(key=API_KEY, text='Hello', lang='en-fr')

Посмотрим на заголовки этого ответа:

print(res.headers)

Заголовки отличаются, потому что мы обращаемся к другому серверу. Но в этом случае тип контента будет application/json вместо text/html. Это означает, что данные могут быть интерпретированы как JSON.

Когда application/json является типом содержимого ответа, Requests может преобразовать ответ в словарь и список.

Чтобы данные были идентифицированы как JSON, используем метод .json() для объекта ответа. Если вывести результат его работы, то будет видно, что данные выглядят одинаково, но формат отличается.

json = res.json()
print(json)

Причина этого заключается в том, что теперь это не обычный текст из res.text. Теперь это печатная версия словаря.

Допустим, что нужно получить доступ к тексту. Поскольку теперь это словарь, мы можем использовать текстовый ключ.

print(json)

Теперь мы видим только данные этого ключа. Чтобы получить этот текст, можно использовать индекс.

print(json)

Теперь единственное, что мы видим, это переведенное слово. Поэтому если изменить значения параметров, то получим разные результаты. Давайте изменим текст для перевода с Hello на Goodbye, целевой язык на испанский и отправим запрос снова.

params = dict(key=API_KEY, text='Goodbye', lang='en-es')

Request Header Fields

We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For now, let’s check what Request header fields are.

The request-header fields allow the client to pass additional information about the request, and about the client itself, to the server. These fields act as request modifiers.Here is a list of some important Request-header fields that can be used based on the requirement:

  • Accept-Charset

  • Accept-Encoding

  • Accept-Language

  • Authorization

  • Expect

  • From

  • Host

  • If-Match

  • If-Modified-Since

  • If-None-Match

  • If-Range

  • If-Unmodified-Since

  • Max-Forwards

  • Proxy-Authorization

  • Range

  • Referer

  • TE

  • User-Agent

You can introduce your custom fields in case you are going to write your own custom Client and Web Server.

urllib.request Restrictions¶

  • Currently, only the following protocols are supported: HTTP (versions 0.9 and
    1.0), FTP, local files, and data URLs.

    Changed in version 3.4: Added support for data URLs.

  • The caching feature of has been disabled until someone
    finds the time to hack proper processing of Expiration time headers.

  • There should be a function to query whether a particular URL is in the cache.

  • For backward compatibility, if a URL appears to point to a local file but the
    file can’t be opened, the URL is re-interpreted using the FTP protocol. This
    can sometimes cause confusing error messages.

  • The and functions can cause arbitrarily
    long delays while waiting for a network connection to be set up. This means
    that it is difficult to build an interactive Web client using these functions
    without using threads.

  • The data returned by or is the raw data
    returned by the server. This may be binary data (such as an image), plain text
    or (for example) HTML. The HTTP protocol provides type information in the reply
    header, which can be inspected by looking at the Content-Type
    header. If the returned data is HTML, you can use the module
    to parse it.

  • The code handling the FTP protocol cannot differentiate between a file and a
    directory. This can lead to unexpected behavior when attempting to read a URL
    that points to a file that is not accessible. If the URL ends in a , it is
    assumed to refer to a directory and will be handled accordingly. But if an
    attempt to read a file leads to a 550 error (meaning the URL cannot be found or
    is not accessible, often for permission reasons), then the path is treated as a
    directory in order to handle the case when a directory is specified by a URL but
    the trailing has been left off. This can cause misleading results when
    you try to fetch a file whose read permissions make it inaccessible; the FTP
    code will try to read it, fail with a 550 error, and then perform a directory
    listing for the unreadable file. If fine-grained control is needed, consider
    using the module, subclassing , or changing
    _urlopener to meet your needs.

Conclusion

Here’s what we learned:

  • How HTTP requests work
  • The various status codes possible in a response
  • How to send requests and receive responses using the Python Requests library
  • How to use a language translation API to translate text
  • How to convert application/json content responses to dictionariesThat covers the basics of Requests in Python. Of course you can do so much more, but what I talked about in this article is the foundation of most requests. Things may change slightly depending on the circumstances, but the basic ideas will remain the same.

If you want to do more, check out https://apilist.fun/ to see different APIs that are available, and try to use them with Python Requests.

What Are the Various Types of HTTP Request Methods?

GET

GET is used to retrieve and request data from a specified resource in a server. GET is one of the most popular HTTP request techniques. In simple words, the GET method is used to retrieve whatever information is identified by the Request-URL.

HEAD

The HEAD technique requests a reaction that is similar to that of GET request, but doesn’t have a message-body in the response. The HEAD request method is useful in recovering meta-data that is written according to the headers, without transferring the entire content. The technique is commonly used when testing hypertext links for accessibility, validity, and recent modification.

POST

Another popular HTTP request method is POST. In web communication, POST requests are utilized to send data to a server to create or update a resource.  The information submitted to the server with POST request method is archived in the request body of the HTTP request. The HTTP POST method is often used to send user-generated data to a server. One example is when a user uploads a profile photo.

PUT

PUT is similar to POST as it is used to send data to the server to create or update a resource. The difference between the two is that PUT requests are idempotent. This means that if you call the same PUT requests multiple times, the results will always be the same.

DELETE

Just as it sounds, the DELETE request method is used to delete resources indicated by a specific URL. Making a DELETE request will remove the targeted resource.

PATCH

A PATCH request is similar to POST and PUT. However, its primary purpose is to apply partial modifications to the resource. And just like a POST request, the PATCH request is also non-idempotent. Additionally, unlike POST and PUT which require a full user entity, with PATCH requests, you may only send the updated username.

TRACE

TRACE requests are used to invoke a remote, application loop-back test along the path to the target resource. The TRACE method allows clients to view whatever message is being received at the other end of the request chain so that they can use the information for testing or diagnostic functions.

CONNECT

The CONNECT request method is used by the client to create a network connection to a web server over a particular HTTP. A good example is SSL tunneling. In a nutshell, CONNECT request establishes a tunnel to the server identified by a specific URL.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector