Запросы в python

Алан-э-Дейл       30.08.2023 г.

Введение

Большая часть интернет-ресурсов взаимодействует с помощью HTTP-запросов. Эти HTTP-запросы выполняются устройствами или браузерами (клиентами) при обращении к веб-сервису.

В Python библиотека requests позволяет делать HTTP-запросы в нашем коде, и это очень востребовано, так как многие современные приложения используют данные сторонних сервисов с помощью API.

Python requests — отличная библиотека. Она позволяет выполнять GET и POST запросы с возможностью передачи параметров URL, добавления заголовков, размещения данных в форме и многое другое.

С помощью библиотеки можно делать запросы практически на каждый сайт/веб-страницу, но ее сила заключается в доступе к API для получения данных в виде JSON, с которыми можно работать в своем коде, приложениях и скриптах.

Raw Response Content¶

In the rare case that you’d like to get the raw socket response from the
server, you can access . If you want to do this, make sure you set
in your initial request. Once you do, you can do this:

>>> r = requests.get('https://api.github.com/events', stream=True)

>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>

>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

In general, however, you should use a pattern like this to save what is being
streamed to a file:

with open(filename, 'wb') as fd
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)

Using will handle a lot of what you would otherwise
have to handle when using directly. When streaming a
download, the above is the preferred and recommended way to retrieve the
content. Note that can be freely adjusted to a number that
may better fit your use cases.

Передача параметров в GET

В некоторых случаях вам нужно будет передавать параметры вместе с вашими запросами GET, которые принимают форму строк запроса. Для этого нам нужно передать эти значения в параметре params, как показано ниже:

import requests

payload = {'user_name': 'admin', 'password': 'password'}
r = requests.get('http://httpbin.org/get', params=payload)

print(r.url)
print(r.text)

Здесь мы присваиваем значения наших параметров переменной полезной нагрузки, а затем – запросу GET через params. Приведенный выше код вернет следующий результат:

http://httpbin.org/get?password=passworduser_name=admin
{"args":{"password":"password","user_name":"admin"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.9.1"},"origin":"103.9.74.222","url":"http://httpbin.org/get?password=passworduser_name=admin"}

Как видите, библиотека Reqeusts автоматически превратила наш словарь параметров в строку запроса и прикрепила ее к URL-адресу.

Обратите внимание, что вам нужно быть осторожным, какие данные вы передаете через запросы GET, поскольку полезная нагрузка видна в URL-адресе, как вы можете видеть в выходных данных выше.

Custom Headers¶

If you’d like to add HTTP headers to a request, simply pass in a to the
parameter.

For example, we didn’t specify our user-agent in the previous example:

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent' 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

Note: Custom headers are given less precedence than more specific sources of information. For instance:

  • Authorization headers set with headers= will be overridden if credentials
    are specified in , which in turn will be overridden by the
    parameter. Requests will search for the netrc file at ~/.netrc, ~/_netrc,
    or at the path specified by the NETRC environment variable.

  • Authorization headers will be removed if you get redirected off-host.

  • Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.

  • Content-Length headers will be overridden when we can determine the length of the content.

Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.

Объект сеанса

Объект сеанса в основном используется для сохранения определенных параметров, например файлов cookie, в различных HTTP-запросах. Объект сеанса может использовать одно TCP-соединение для обработки нескольких сетевых запросов и ответов, что приводит к повышению производительности.

import requests

first_session = requests.Session()
second_session = requests.Session()

first_session.get('http://httpbin.org/cookies/set/cookieone/111')
r = first_session.get('http://httpbin.org/cookies')
print(r.text)

second_session.get('http://httpbin.org/cookies/set/cookietwo/222')
r = second_session.get('http://httpbin.org/cookies')
print(r.text)

r = first_session.get('http://httpbin.org/anything')
print(r.text)

Вывод:

{"cookies":{"cookieone":"111"}}

{"cookies":{"cookietwo":"222"}}

{"args":{},"data":"","files":{},"form":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Cookie":"cookieone=111","Host":"httpbin.org","User-Agent":"python-requests/2.9.1"},"json":null,"method":"GET","origin":"103.9.74.222","url":"http://httpbin.org/anything"}

Путь httpbin/cookies/set /{имя}/{значение} установит файл cookie с именем и значением. Здесь мы устанавливаем разные значения cookie для объектов first_session и second_session. Вы можете видеть, что один и тот же файл cookie возвращается во всех будущих сетевых запросах для определенного сеанса.

Точно так же мы можем использовать объект сеанса для сохранения определенных параметров для всех запросов.

import requests

first_session = requests.Session()

first_session.cookies.update({'default_cookie': 'default'})

r = first_session.get('http://httpbin.org/cookies', cookies={'first-cookie': '111'})
print(r.text)

r = first_session.get('http://httpbin.org/cookies')
print(r.text)

Вывод:

{"cookies":{"default_cookie":"default","first-cookie":"111"}}

{"cookies":{"default_cookie":"default"}}

Как видите, default_cookie отправляется с каждым запросом сеанса. Если мы добавим какой-либо дополнительный параметр к объекту cookie, он добавится к файлу default_cookie. «first-cookie»: «111» добавляется к cookie по умолчанию «default_cookie»:»default».

.authenticators

The class or decorator will ensure that this property is automatically set to a list of instances, based on the set on the view or based on the setting.

You won’t typically need to access this property.

Note: You may see a raised when calling the or properties. These errors originate from an authenticator as a standard , however it’s necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the originates from the authenticator and will instead assume that the request object does not have a or property. The authenticator will need to be fixed.

REST framework supports a few browser enhancements such as browser-based , and forms.

Выполнение запросов POST

Запросы HTTP POST противоположны запросам GET, поскольку они предназначены для отправки данных на сервер, а не для их получения. Хотя запросы POST также могут получать данные в ответе, как и запросы GET.

Вместо использования метода get() нам нужно использовать метод post(). Для передачи аргумента мы можем передать его внутри параметра данных:

import requests

payload = {'user_name': 'admin', 'password': 'password'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.url)
print(r.text)

Вывод:

http://httpbin.org/post
{"args":{},"data":"","files":{},"form":{"password":"password","user_name":"admin"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"33","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.9.1"},"json":null,"origin":"103.9.74.222","url":"http://httpbin.org/post"}

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

Использование 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.

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.

Response Headers¶

We can view the server’s response headers using a Python dictionary:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

The dictionary is special, though: it’s made just for HTTP headers. According to
, HTTP Header names
are case-insensitive.

So, we can access the headers using any capitalization we want:

>>> r.headers'Content-Type'
'application/json'

>>> r.headers.get('content-type')
'application/json'

It is also special in that the server could have sent the same header multiple
times with different values, but requests combines them so they can be
represented in the dictionary within a single mapping, as per
:

Legacy interface¶

The following functions and classes are ported from the Python 2 module
(as opposed to ). They might become deprecated at
some point in the future.

(url, filename=None, reporthook=None, data=None)

Copy a network object denoted by a URL to a local file. If the URL
points to a local file, the object will not be copied unless filename is supplied.
Return a tuple where filename is the
local file name under which the object can be found, and headers is whatever
the method of the object returned by returned (for
a remote object). Exceptions are the same as for .

The second argument, if present, specifies the file location to copy to (if
absent, the location will be a tempfile with a generated name). The third
argument, if present, is a callable that will be called once on
establishment of the network connection and once after each block read
thereafter. The callable will be passed three arguments; a count of blocks
transferred so far, a block size in bytes, and the total size of the file. The
third argument may be on older FTP servers which do not return a file
size in response to a retrieval request.

The following example illustrates the most common usage scenario:

>>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()

If the url uses the scheme identifier, the optional data
argument may be given to specify a request (normally the request
type is ). The data argument must be a bytes object in standard
application/x-www-form-urlencoded format; see the
function.

will raise when it detects that
the amount of data available was less than the expected amount (which is the
size reported by a Content-Length header). This can occur, for example, when
the download is interrupted.

The Content-Length is treated as a lower bound: if there’s more data to read,
urlretrieve reads more data, but if less data is available, it raises the
exception.

You can still retrieve the downloaded data in this case, it is stored in the
attribute of the exception instance.

If no Content-Length header was supplied, urlretrieve can not check the size
of the data it has downloaded, and just returns it. In this case you just have
to assume that the download was successful.

()

Cleans up temporary files that may have been left behind by previous
calls to .

class (proxies=None, **x509)

Deprecated since version 3.3.

Base class for opening and reading URLs. Unless you need to support opening
objects using schemes other than , , or ,
you probably want to use .

By default, the class sends a User-Agent header
of , where VVV is the version number.
Applications can define their own User-Agent header by subclassing
or and setting the class attribute
to an appropriate string value in the subclass definition.

The optional proxies parameter should be a dictionary mapping scheme names to
proxy URLs, where an empty dictionary turns proxies off completely. Its default
value is , in which case environmental proxy settings will be used if
present, as discussed in the definition of , above.

Additional keyword parameters, collected in x509, may be used for
authentication of the client when using the scheme. The keywords
key_file and cert_file are supported to provide an SSL key and certificate;
both are needed to support client authentication.

objects will raise an exception if the server
returns an error code.

(fullurl, data=None)

Open fullurl using the appropriate protocol. This method sets up cache and
proxy information, then calls the appropriate open method with its input
arguments. If the scheme is not recognized, is called.
The data argument has the same meaning as the data argument of
.

This method always quotes fullurl using .

(fullurl, data=None)

Overridable interface to open unknown URL types.

(url, filename=None, reporthook=None, data=None)

If the url uses the scheme identifier, the optional data
argument may be given to specify a request (normally the request type
is ). The data argument must in standard
application/x-www-form-urlencoded format; see the
function.

Variable that specifies the user agent of the opener object. To get
to tell servers that it is a particular user agent, set this in a
subclass as a class variable or in the constructor before calling the base
constructor.

BaseHandler Objects¶

objects provide a couple of methods that are directly
useful, and others that are meant to be used by derived classes. These are
intended for direct use:

(director)

Add a director as parent.

()

Remove any parents.

The following attribute and methods should only be used by classes derived from
.

Note

The convention has been adopted that subclasses defining
or methods are named
; all others are named .

A valid , which can be used to open using a different
protocol, or handle errors.

(req)

This method is not defined in , but subclasses should
define it if they want to catch all URLs.

This method, if implemented, will be called by the parent
. It should return a file-like object as described in
the return value of the of , or .
It should raise , unless a truly exceptional
thing happens (for example, should not be mapped to
).

This method will be called before any protocol-specific open method.

This method is not defined in , but subclasses should
define it if they want to handle URLs with the given protocol.

This method, if defined, will be called by the parent .
Return values should be the same as for .

(req)

This method is not defined in , but subclasses should
define it if they want to catch all URLs with no specific registered handler to
open it
.

This method, if implemented, will be called by the
. Return values should be the same as for
.

(req, fp, code, msg, hdrs)

This method is not defined in , but subclasses should
override it if they intend to provide a catch-all for otherwise unhandled HTTP
errors. It will be called automatically by the getting
the error, and should not normally be called in other circumstances.

req will be a object, fp will be a file-like object with
the HTTP error body, code will be the three-digit code of the error, msg
will be the user-visible explanation of the code and hdrs will be a mapping
object with the headers of the error.

Return values and exceptions raised should be the same as those of
.

nnn should be a three-digit HTTP error code. This method is also not defined
in , but will be called, if it exists, on an instance of a
subclass, when an HTTP error with code nnn occurs.

Subclasses should override this method to handle specific HTTP errors.

Arguments, return values and exceptions raised should be the same as for
.

This method is not defined in , but subclasses should
define it if they want to pre-process requests of the given protocol.

This method, if defined, will be called by the parent .
req will be a object. The return value should be a
object.

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython Variables
Python Variables
Variable Names
Assign Multiple Values
Output Variables
Global Variables
Variable Exercises

Python Data TypesPython NumbersPython CastingPython Strings
Python Strings
Slicing Strings
Modify Strings
Concatenate Strings
Format Strings
Escape Characters
String Methods
String Exercises

Python BooleansPython OperatorsPython Lists
Python Lists
Access List Items
Change List Items
Add List Items
Remove List Items
Loop Lists
List Comprehension
Sort Lists
Copy Lists
Join Lists
List Methods
List Exercises

Python Tuples
Python Tuples
Access Tuples
Update Tuples
Unpack Tuples
Loop Tuples
Join Tuples
Tuple Methods
Tuple Exercises

Python Sets
Python Sets
Access Set Items
Add Set Items
Remove Set Items
Loop Sets
Join Sets
Set Methods
Set Exercises

Python Dictionaries
Python Dictionaries
Access Items
Change Items
Add Items
Remove Items
Loop Dictionaries
Copy Dictionaries
Nested Dictionaries
Dictionary Methods
Dictionary Exercise

Python If…ElsePython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython Classes/ObjectsPython InheritancePython IteratorsPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try…ExceptPython User InputPython String Formatting

Установлено несколько версий Python

Итак, Вы установили python, pipe, pipenv, requests и ещё много чего, но
вдруг выяснили, что на компьютере уже не одна, а несколько версий python.

Например, у Вас установлены версии 2.7 и 3.5.

Когда Вы запускаете python, то хотите, чтобы работала последняя версия, но,
почему-то работает версия 2.7.

Выясним, как разобраться в этой ситуации.

Python -V и which python

Узнаем версию python которая вызывается командой python с флаго -V

python -V

Python 2.7.18rcl

Полезная команда, которую можно выполнить, чтобы узнать где расположен ваш Python — which

which python

/usr/bin/python

Как видите, в моей

Ubuntu

Python находится в /usr/bin/python и имеет версию 2.7.18rcl

Третий Python тоже установлен, посмотреть версию и директорию также просто

python3 -V

Python 3.8.5

which python3

/usr/bin/python3

Резюмируем: второй Python вызывается командой python а третий Python командой python3.

Обычно Python установлен в директорию /usr/bin

Ещё один способ получить эту информацию — использование команды type

type python3

python3 is hashed (/usr/bin/python3)

type python

python3 is hashed (/usr/bin/python)

Следующий способ — через sys.executable

здесь я для разнообразия настроил alias в .bashrc и теперь команда python эквивалентна python3

python

Python 3.8.5 (default, Jul 28 2020, 12:59:40)
on linux
Type «help», «copyright», «credits» or «license» for more information.

>>> import sys

>>> sys.executable

‘/usr/bin/python3’

Если у вас уже был третий Python, например 3.8.5, а вы самостоятельно скачали и
установили более позднюю версию, например 3.9.1 как в

то у вас будет два разных третьих Python.

Убедиться в этом можно изучив директорию

ls -la /usr/local/bin/

total 21648
drwxr-xr-x 2 root root 4096 Feb 4 11:08 .
drwxr-xr-x 10 root root 4096 Jul 31 2020 ..
lrwxrwxrwx 1 root root 8 Feb 4 11:08 2to3 -> 2to3-3.9
-rwxr-xr-x 1 root root 101 Feb 4 11:08 2to3-3.9
-rwxr-xr-x 1 root root 238 Feb 4 11:08 easy_install-3.9
lrwxrwxrwx 1 root root 7 Feb 4 11:08 idle3 -> idle3.9
-rwxr-xr-x 1 root root 99 Feb 4 11:08 idle3.9
-rwxr-xr-x 1 root root 229 Feb 4 11:08 pip3
-rwxr-xr-x 1 root root 229 Feb 4 11:08 pip3.9
lrwxrwxrwx 1 root root 8 Feb 4 11:08 pydoc3 -> pydoc3.9
-rwxr-xr-x 1 root root 84 Feb 4 11:08 pydoc3.9
lrwxrwxrwx 1 root root 9 Feb 4 11:08 python3 -> python3.9
-rwxr-xr-x 1 root root 22127472 Feb 4 11:05 python3.9
-rwxr-xr-x 1 root root 3087 Feb 4 11:08 python3.9-config
lrwxrwxrwx 1 root root 16 Feb 4 11:08 python3-config -> python3.9-config

which python3

/usr/local/bin/python3

which python3.9

/usr/local/bin/python3.9

В такой ситуации вам нужно специально указывать полную версию python3.9 для
запуска программ, либо настроить

PATH

Если ни одна из команд pyhon и python3 не работает, бывает полезно проверить переменную PATH

echo $PATH

/home/andrei/.local/bin:/home/andrei/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Как вы можете убедиться моя директория /usr/bin прописана в PATH

Если вам нужно добавить директорию в PATH читайте статью

«PATH в Linux»

или статью

«PATH в Windows»

Важно понимать, что если в каждой из директорий, упомянутых в PATH, будет установлено по какому-то Python выполняться
будет тот, который в первой директории.

Если нужно использовать Python из какой-то определённой директории, нужно прописать её путь. В этом
случае не обязательно наличие этого пути в PATH. /usr/bin/python3

/usr/bin/python3

Python 3.8.5 (default, Jul 28 2020, 12:59:40)
on linux
Type «help», «copyright», «credits» or «license» for more information.
>>>

>>> говорит о том, что Python в интерактивном режиме.

Pip

Выясним куда смотрит

pip

pip -V

/home/andrei/.local/lib/python2.7/site-packages (python 2.7)

Как видите, pip смотрит в директорию python2.7 поэтому всё, что мы до этого
устанавливали командой pip install попало к версии 2.7
а версия 3.5 не имеет ни pipenv ни requests и, например,

протестировать интерфейсы

с её помощью не получится

Если вы выполнили pip -V и получили в ответ

Command ‘pip’ not found, but there are 18 similar ones.

Посмотрите что выдаст

pip3 -V

В моей

Ubuntu

результат такой

pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)

Посмотреть куда pip установил пакет можно командой pip show

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

REST API

pip show requests

Проверка SSL-сертификата

В любое время, когда вы отправляете или получаете данные — важна безопасность. Вы общаетесь с защищенными сайтами через HTTP, устанавливая зашифрованное соединение с использованием SSL, что означает, что проверка SSL-сертификата целевого сервера имеет решающее значение.

Хорошей новостью является то, что делает это за вас по умолчанию. Однако, в некоторых случаях, вы можете изменить это поведение.

Если вы хотите отключить проверку SSL-сертификата, вы передаете в параметр функции :

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

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

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

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

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

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

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

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

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

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

Объект Session

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

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

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

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

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

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

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

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

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

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

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

Cookies¶

If a response contains some Cookies, you can quickly access them:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies'example_cookie_name'
'example_cookie_value'

To send your own cookies to the server, you can use the
parameter:

>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Cookies are returned in a ,
which acts like a but also offers a more complete interface,
suitable for use over multiple domains or paths. Cookie jars can
also be passed in to requests:

Гость форума
От: admin

Эта тема закрыта для публикации ответов.