- How to Upload Files with Python’s requests Library
- Uploading a Single File with Python’s Requests Library
- Free eBook: Git Essentials
- Uploading Multiple Files with Python’s requests Library
- Conclusion
- Использование модуля Requests в Python
- Создание запроса GET
- Python requests: POST Request Explained
- Understanding the Python requests POST Function
How to Upload Files with Python’s requests Library
Python is supported by many libraries which simplify data transfer over HTTP. The requests library is one of the most popular Python packages as it’s heavily used in web scraping. It’s also popular for interacting with servers! The library makes it easy to upload data in a popular format like JSON, but also makes it easy to upload files as well.
In this tutorial, we will take a look at how to upload files using Python’s requests library. The article will start by covering the requests library and the post() function signature. Next, we will cover how to upload a single file using the requests package. Last but not least, we upload multiple files in one request.
Uploading a Single File with Python’s Requests Library
This tutorial covers how to send the files, we’re not concerned about how they’re created. To follow along, create three files called my_file.txt , my_file_2.txt and my_file_3.txt .
The first thing we need to do is install our the request library in our workspace. While not necessary, it’s recommended that you install libraries in a virtual environment:
Activate the virtual environment so that we would no longer impact the global Python installation:
Now let’s install the requests library with pip :
Create a new file called single_uploader.py which will store our code. In that file, let’s begin by importing the requests library:
Now we’re set up to upload a file! When uploading a file, we need to open the file and stream the content. After all, we can’t upload a file we don’t have access to. We’ll do this with the open() function.
The open() function accepts two parameters: the path of the file and the mode. The path of the file can be an absolute path or a relative path to where the script is being run. If you’re uploading a file in the same directory, you can just use the file’s name.
The second argument, mode, will take the «read binary» value which is represented by rb . This argument tells the computer that we want to open the file in the read mode, and we wish to consume the data of the file in a binary format:
test_file = open("my_file.txt", "rb")
Note: it’s important to read the file in binary mode. The requests library typically determines the Content-Length header, which is a value in bytes. If the file is not read in bytes mode, the library may get an incorrect value for Content-Length , which would cause errors during file submission.
For this tutorial, we’ll make requests to the free httpbin service. This API allows developers to test their HTTP requests. Let’s create a variable that stores the URL we’ll post our files to:
test_url = "http://httpbin.org/post"
We now have everything to make the request. We’ll use the post() method of the requests library to upload the file. We need two arguments to make this work: the URL of the server and files property. We’ll also save the response in a variable, write the following code:
test_response = requests.post(test_url, files = "form_field_name": test_file>)
The files property takes a dictionary. The key is the name of the form field that accepts the file. The value is the bytes of the opened file you want to upload.
Normally to check if your post() method was successful we check the HTTP status code of the response. We can use the ok property of the response object, test_url . If it’s true, we’ll print out the response from the HTTP server, in this case, it will echo the request:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
if test_response.ok: print("Upload completed successfully!") print(test_response.text) else: print("Something went wrong!")
Let’s try it out! In the terminal, execute your script with the python command:
Your output would be similar to this:
Upload completed successfully! < "args": <>, "data": "", "files": < "form_field_name": "This is my file\nI like my file\n" >, "form": <>, "headers": < "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "189", "Content-Type": "multipart/form-data; boundary=53bb41eb09d784cedc62d521121269f8", "Host": "httpbin.org", "User-Agent": "python-requests/2.25.0", "X-Amzn-Trace-Id": "Root=1-5fc3c190-5dea2c7633a02bcf5e654c2b" >, "json": null, "origin": "102.5.105.200", "url": "http://httpbin.org/post" >
As a sanity check, you can verify the form_field_name value matches what’s in your file.
Uploading Multiple Files with Python’s requests Library
Uploading multiple files using requests is quite similar to a single file, with the major difference being our use of lists. Create a new file called multi_uploader.py and the following setup code:
import requests test_url = "http://httpbin.org/post"
Now create a variable called test_files that’s a dictionary with multiple names and files:
test_files = < "test_file_1": open("my_file.txt", "rb"), "test_file_2": open("my_file_2.txt", "rb"), "test_file_3": open("my_file_3.txt", "rb") >
Like before, the keys are the names of the form fields and the values are the files in bytes.
We can also create our files variables as a list of tuples. Each tuple contains the name of the form field accepting the file, followed by the file’s contents in bytes:
test_files = [("test_file_1", open("my_file.txt", "rb")), ("test_file_2", open("my_file_2.txt", "rb")), ("test_file_3", open("my_file_3.txt", "rb"))]
Either works so choose whichever one you prefer!
Once the list of files is ready, you can send the request and check its response like before:
test_response = requests.post(test_url, files = test_files) if test_response.ok: print("Upload completed successfully!") print(test_response.text) else: print("Something went wrong!")
Execute this script with the python command:
Upload completed successfully! < "args": <>, "data": "", "files": < "test_file_1": "This is my file\nI like my file\n", "test_file_2": "All your base are belong to us\n", "test_file_3": "It's-a me, Mario!\n" >, "form": <>, "headers": < "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "470", "Content-Type": "multipart/form-data; boundary=4111c551fb8c61fd14af07bd5df5bb76", "Host": "httpbin.org", "User-Agent": "python-requests/2.25.0", "X-Amzn-Trace-Id": "Root=1-5fc3c744-30404a8b186cf91c7d239034" >, "json": null, "origin": "102.5.105.200", "url": "http://httpbin.org/post" >
Good job! You can upload single and multiple files with requests !
Conclusion
In this article, we learned how to upload files in Python using the requests library. Where it’s a single file or multiple files, only a few tweaks are needed with the post() method. We also verified our response to ensure that our uploads were successful.
Использование модуля Requests в Python
Monty Shokeen Last updated Mar 9, 2017
Requests — это модуль Python, который вы можете использовать для отправки всех видов HTTP-запросов. Это простая в использовании библиотека с множеством функций, начиная от передачи параметров в URL-адресах до отправки пользовательских заголовков и проверки SSL. В этом уроке вы узнаете, как использовать эту библиотеку для отправки простых HTTP-запросов в Python.
Вы можете использовать Запросы с Python версии 2.6-2.7 и 3.3-3.6. Прежде чем продолжить, вы должны знать о том, что Requests является внешним модулем, поэтому сначала вам нужно будет установить его, прежде чем попробовать примеры из этого урока. Вы можете установить его, выполнив следующую команду в терминале:
После установки модуля вы можете проверить, был ли он успешно установлен, импортировав его с помощью этой команды:
Если установка прошла успешно, вы не увидите никаких сообщений об ошибках.
Создание запроса GET
Очень просто отправить HTTP-запрос с помощью Requests. Сначала вы импортируете модуль и затем выполните запрос. Вот пример:
req = requests.get('https://tutsplus.com/')
Вся информация о нашем запросе теперь хранится в объекте Response, называемом req . Например, вы можете получить кодировку веб-страницы, используя свойство req.encoding . Вы также можете получить код состояния запроса, используя свойство req.status_code .
req.encoding # returns 'utf-8'
req.status_code # returns 200
Вы можете получить доступ к файлам cookie, отправленным сервером с помощью req.cookies . Аналогично, вы можете получить заголовки ответов, используя req.headers . Свойство req.headers возвращает нечувствительный к регистру словарь заголовков ответов. Это означает, что req.headers[‘Content-Length’] , req.headers[‘content-length’] и req.headers[‘CONTENT-LENGTH’] вернут значение заголовка ответа Content-Length .
Вы можете проверить, является ли ответ корректным HTTP-перенаправлением, которое могло быть обработано автоматически с использованием свойства req.is_redirect . Он будет возвращать True или False на основе ответа. Вы также можете получить время, прошедшее между отправкой запроса и возвратом ответа с использованием свойства req.elapsed .
URL, который вы первоначально передали функции get() , может отличаться от конечного URL-адреса ответа по целому ряду причин, включая перенаправления. Чтобы увидеть окончательный URL-адрес ответа, вы можете использовать свойство req.url .
req = requests.get('http://www.tutsplus.com/')
req.encoding # returns 'utf-8'
req.status_code # returns 200
req.elapsed # returns datetime.timedelta(0, 1, 666890)
req.url # returns 'https://tutsplus.com/'
# returns 'text/html; charset=utf-8'
Получение всей этой информации о веб-странице, к которой вы обращаетесь, приятно, но вы, скорее всего, хотите получить доступ к фактическому контенту. Если контент, к которому вы обращаетесь, является текстом, вы можете использовать свойство req.text для доступа к нему. Затем содержимое анализируется как unicode. Вы можете передать кодировку, с помощью которой можно декодировать текст, используя свойство req.encoding .
В случае нетекстовых ответов вы можете получить к ним доступ в двоичной форме, используя req.content . Модуль автоматически расшифровывает gzip и deflate кодирование передачи. Это может быть полезно, когда вы имеете дело с медиафайлами. Аналогично, вы можете получить доступ к json-закодированному контенту ответа, если он существует, используя req.json() .
Вы также можете получить исходный ответ с сервера, используя req.raw . Имейте в виду, что вам придется передать stream=True в запросе, чтобы получить исходный ответ.
Некоторые файлы, которые вы загружаете из Интернета с помощью модуля Requests, могут иметь огромный размер. В таких случаях неразумно загружать весь ответ или файл в память сразу. Вы можете загрузить файл на куски или фрагменты, используя метод iter_content(chunk_size = 1, decode_unicode = False) .
Этот метод выполняет итерацию по данным ответа в chunk_size количество байтов одновременно. Когда в запросе задан stream = True , этот метод не позволит сразу считывать весь файл в память для больших ответов. Параметр chunk_size может быть integer или None . Когда установлено значение integer, chunk_size определяет количество байтов, которые должны быть прочитаны в памяти.
Если для параметра chunk_size установлено значение None , а для stream установлено значение True , данные будут считаны по мере того, как он достигнет любого размера кусков. Если для параметра chunk_size установлено значение None , а для stream установлено значение False , все данные будут возвращены как один кусок.
Давайте загрузим этот образ леса на Pixabay с помощью модуля Requests. Вот фактическое изображение:
Это код, который вам нужен:
req = requests.get('path/to/forest.jpg', stream=True)
Python requests: POST Request Explained
In this tutorial, you’ll learn how to use the Python requests library’s POST function to post data via HTTP. The Python requests library abstracts the complexities in making HTTP requests. The requests.post() function allows you to post data to a web resource.
By the end of this tutorial, you’ll have learned:
- How the Python requests post function works
- How to customize the Python requests post function with headers
- How to use the Python response objects when working with the post function
Understanding the Python requests POST Function
An HTTP POST request is used to send data to a server, where data are shared via the body of a request. In the request.post() function, data are sent with the data parameter, which accepts a dictionary, a list of tuples, bytes or a file object.
Let’s take a look at what the requests.post() function looks like in Python:
# Understanding the requests.post() Function import requests requests.post( url, data=None, json=None, **kwargs )
We can see that the function accepts three parameters:
- url , which defines the URL to post to
- data , which accepts a dictionary, list of tuples, butes, or a file-like object to send in the body of the request
- json , which represents json data to send in the body of the request
Additionally, the function accept a number of different keyword arguments inherited from the requests.request() function. These keyword arguments can be passed in directly and are described in the table below: