Michio JP

Michio JP

1566811528

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

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

What is GEEK

Buddha Community

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

Hú Ńtęr

1566819667

thank you very much <3

I am Developer

1615040237

PHP jQuery Ajax Post Form Data Example

PHP jquery ajax POST request with MySQL. In this tutorial, you will learn how to create and submit a simple form in PHP using jQuery ajax post request. And how to submit a form data into MySQL database without the whole page refresh or reload. And also you will learn how to show an error message to the user if the user does not fill any form field.

And this tutorial also guide on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.

PHP jQuery AJAX POST Form Data In Into MySQL DB Example

Just follow the few below steps and easily create and submit ajax form in PHP and MySQL with client-side validation.

  • Create Database And Table
  • Create a Database Connection File
  • Create An Ajax POST Form in PHP
  • Create An Ajax Data Store File

https://www.tutsmake.com/php-jquery-ajax-post-tutorial-example/

#jquery ajax serialize form data example #submit form using ajax in php example #save form data using ajax in php #how to insert form data using ajax in php #php jquery ajax form submit example #jquery ajax and jquery post form submit example with php

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

I am Developer

1597559012

Multiple File Upload in Laravel 7, 6

in this post, i will show you easy steps for multiple file upload in laravel 7, 6.

As well as how to validate file type, size before uploading to database in laravel.

Laravel 7/6 Multiple File Upload

You can easily upload multiple file with validation in laravel application using the following steps:

  1. Download Laravel Fresh New Setup
  2. Setup Database Credentials
  3. Generate Migration & Model For File
  4. Make Route For File uploading
  5. Create File Controller & Methods
  6. Create Multiple File Blade View
  7. Run Development Server

https://www.tutsmake.com/laravel-6-multiple-file-upload-with-validation-example/

#laravel multiple file upload validation #multiple file upload in laravel 7 #multiple file upload in laravel 6 #upload multiple files laravel 7 #upload multiple files in laravel 6 #upload multiple files php laravel

Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition