Post Multipart Form Data in Python with Requests: Flask File Upload Example

Post Multipart Form Data in Python with Requests: Flask File Upload Example

In this tutorial we'll demonstrate how to upload a file from a Python server to another server by sending a POST request with multipart/form-data using the Python requests library.

We'll be using two servers. The server that receives the file doesn't need to be a Python server but since we'he previously created one with Django in this tutorial, let's use it instead of re-inventing the wheel.

Note: Typically we upload files from a client to a server but in this tutorial, we'll see how we can upload files from a server to another web server using Python and the Requests library.

Open a new terminal and create and activate a virtual environment:

$ python3 -m venv .env
$ source .env/bin/activate

Next, clone the GitHub repository and install the dependencies:

$ git clone https://github.com/techiediaries/django-rest-file-upload.git server2
$ cd server2
$ pip install -r requirments.txt

Next, run the server using the following commands:

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

The server will be available from the 127.0.0.1:8000 and will expose an /upload endpoint that accepts a POST request.

Note: This server has also CORS enabled which means it can accept requests from different domains so make sure to enable CORS if you are using any other server.

Creating the Flask Server

Now, let's proceed to create the uploading Python server that will make use of the Requests library to send a POST requests to the 127.0.0.1:8000/upload endpoint for uploading a file between two servers.

Installing requests

Let's install the requests library using pip:

$ pip install requests

Installing Flask

We'll be using Flask; a single file and lightweight web framework for creating the Python server that uploads the file. First install flask using pip:

$ pip install flask

Next, create a server.py file and add the following code:

import os
from flask import Flask, request, render_template
import requests

app = Flask(name)

@app.route('/handle_form', methods=['POST']) def handle_form(): print("Posted file: {}".format(request.files['file'])) file = request.files['file'] return ""

@app.route("/") def index(): return render_template("index.html");

if name == "main": app.run(host='0.0.0.0', port=8080, debug=True)

We create a / route for rendering the index.html template that will display a form and /handle_formroute that will process the multipart form, get the uploaded file from the requests.files[] array and return. We'll use this method to send the form to the django server using the requests library.

Next, create a templates folder and add an index.html file with the following code:

<!DOCTYPE html>
<html>

<head> <title>Upload New File</title> </head>

<body> <h1>Upload Files</h1>

&lt;form action="handle_form" method="post" enctype="multipart/form-data"&gt;
    &lt;input type="file" name="file"&gt;
    &lt;input type="submit" value="Upload"&gt;
&lt;/form&gt;

</body>

</html>

We create a form of multipart/form-data encoding type that has a file field for selecting a file from the hard drive.

Sending Files with the Requests Library

The handle_form() of our flask application receives the posted file but doesn't save it. Instead, we'll use the requests library to upload it to the django server.

Simply change the handle_form() method as follows:

@app.route('/handle_form', methods=['POST'])
def handle_form():
    print("Posted file: {}".format(request.files['file']))
    file = request.files['file']
    files = {'file': file.read()}
    r = requests.post("http://127.0.0.1:8000/upload/", files=files)

if r.ok:
    return "File uploaded!"
else:
    return "Error uploading file!"

We get the posted form from the request.Files array, next we use the requests.post() method to upload the file to the other server using a POST request. If the requests is successful, r.ok will be True.

Next, run the server using the following command:

$ python server.py

Your Python server will be available from the 127.0.0.1:8080 address.

If you select a file and upload it, you should have the file uploaded in the media folder of the django server.

Conclusion

In this tutorial, you've seen how you can use Python and the requests library to upload a file from a server to another server.

Originally published at  techiediaries.com on 11 Mar 2019

===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python and Django Full Stack Web Developer Bootcamp

☞ Python for Time Series Data Analysis

☞ Python Programming For Beginners From Scratch

☞ Beginner’s guide on Python: Learn python from scratch! (New)

☞ Python for Beginners: Complete Python Programming

☞ Django 2.1 & Python | The Ultimate Web Development Bootcamp

☞ Python eCommerce | Build a Django eCommerce Web Application

☞ Python Django Dev To Deployment

python django

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

Python Tricks Every Developer Should Know

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

How to Remove all Duplicate Files on your Drive via Python

Today you're going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates. We gonna use Python OS remove( ) method to remove the duplicates on our drive. Well, that's simple you just call remove ( ) with a parameter of the name of the file you wanna remove done.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Main Pros and Cons of Django As A Web Framework for Python Developers

India's best Institute for Django Online Training Course & Certification. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.