Skip to content

Instantly share code, notes, and snippets.

@dvmn-tasks
Last active April 14, 2021 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvmn-tasks/6ccad07025c24bd451f639f069b2b056 to your computer and use it in GitHub Desktop.
Save dvmn-tasks/6ccad07025c24bd451f639f069b2b056 to your computer and use it in GitHub Desktop.
Как отправить файл с помощью Requests

Этот сниппет кода основан на ответе к вопросу о загрузке файлов через Requests на сайте StackOverflow.

import requests

with open('image.jpg', 'rb') as file:
    url = '...'
    files = {
        'media': file,  # Вместо ключа "media" скорее всего нужно подставить другое название ключа. Какое конкретно см. в доке API ВК.
    }
    response = requests.post(url, files=files)
    response.raise_for_status()

Контекстный менеджер with здесь используется для того, чтобы явно закрыть файл после его использования. Is explicitly closing files important?

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment