Uploaded Dot Net Slash File Slash 23tendzb
Receive or Return files-Flask API
Serve files or Download files every bit output using Flask
Hither we are going to see "How to Render Single File and Multiple Files with Flask using Python"
Why this tutorial ???
Sometimes you want to permit users to download reports or files from your website or application is an often required feature of any website or application. . . ,
Flask provides u.s. with some useful function to practise so
Subsequently seeing people writing blogs about "Flask for Beginners" tutorial. I've noticed that, they didn't comprehend the "Sending Files and let users to download files". And then, I took an interest on writing well-nigh the "Serving Files". I am sure this Blog walks you to "Serve Files" and makes you lot simple. . . ,
In my Previous web log, discussed about "Uploading File(south) to the Server"
Why Chosen Flask ???
Though people say Flask is elementary and easy to become started with while Django is heavy for building web applications.
Flask is a widely used micro web framework for creating APIs in Python. Information technology is a simple yet powerful spider web framework which is designed to get started quick and easy, with the ability to calibration up to complex applications.
From the documentation,
"Micro" does not mean that your whole web application has to fit into a single Python file (although it certainly tin), nor does information technology mean that Flask is lacking in functionality. The "micro" in micro framework ways Flask aims to go on the core uncomplicated but extensible.
Requirements and Installation
- Of course, We demand Python 3.5 or above. But why?? encounter this
- Install Flask
pip install flask
# Elementary Send file from Server using Flask
A simple File Ship Python Script using Flask API . . ,
# servefile.py from flask import Flask,send_from_directoryapp = Flask(__name__)
# Specify directory to download from . . . DOWNLOAD_DIRECTORY = "<your folder directory>"@app.road('/get-files/<path:path>',methods = ['Become','POST'])
def get_files(path):"""Download a file."""
try:
render send_from_directory(DOWNLOAD_DIRECTORY, path, as_attachment=True)
except FileNotFoundError:
abort(404)if __name__ == '__main__':
app.run(host='0.0.0.0', port = 8000, threaded = True, debug = True)
Run the Awarding by running "python servefile.py". Go to browser and blazon "http://localhost:8000/go-files/<filename with extension>".
If the Specified file that yous mentioned in the URL is exists, you can download the file. Otherwise 404 fault volition occur . . ,
# Returning Various File based on requests
File Downloading is the procedure of receiving the binary or normal files from the server. Flask facilitates us to Download the files easily.
Returning Various files based on the Routes
Create a file named "variousfiledownloadflask.py"
ane. Importing the Libraries
from flask import Flask,send_file,send_from_directory
2. Create Instance and Specify the File Location
app = Flask(__name__) # The absolute path of the directory containing images for users to download
app.config["CLIENT_IMAGES"] = "E:/AudiotoText/Flask_File_Downloads/filedownload/files/image" # The absolute path of the directory containing CSV files for users to download
app.config["CLIENT_CSV"] = "Due east:/AudiotoText/Flask_File_Downloads/filedownload/files/csv" # The absolute path of the directory containing PDF files for users to download
app.config["CLIENT_PDF"] = "E:/AudiotoText/Flask_File_Downloads/filedownload/files/pdf"
iii. Awarding Routing
# Get CSV File Routing
@app.route('/get-csv/<csv_filename>',methods = ['Go','POST'])
def get_csv(csv_filename): effort:
return send_from_directory(app.config["CLIENT_CSV"], filename=csv_filename, as_attachment=True)
except FileNotFoundError:
arrest(404)
# Go PDF file Routing
@app.road('/become-pdf/<pdf_filename>',methods = ['GET','Mail service'])
def get_pdf(pdf_filename):
try:
return send_from_directory(app.config["CLIENT_PDF"], filename=pdf_filename, as_attachment=Truthful)
except FileNotFoundError:
abort(404)
# Go Prototype file Routing
@app.route("/get-image/<path:image_name>",methods = ['Become','Post'])
def get_image(image_name):
endeavour:
return send_from_directory(app.config["CLIENT_IMAGES"], filename=image_name, as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == '__main__':
app.run(host='0.0.0.0',port = 8000, threaded = True, debug = True)
Routes tin have the following variable types:
- cord: Accepts whatsoever text without a slash (by default).
- int: Accepts positive integers
- bladder: Accepts positive numerical values containing decimal points.
- path: Similar to a string, but accepts slashes
- uuid: Accepts UUID strings (Universally unique identifier) (e.chiliad 118bc9c3–1af4–4d46–87a1–266db2e64e7a)
Different static routes, routes created with variable rules practice have parameters, with those parameters being the road variables themselves.
For instance, if you define a url with <int:some_integer>
, Flask will try to catechumen it into an integer, <path:path_to_some_file>
will allow a path like string, including slashes etc..
Here is the Full lawmaking for Various File Formats
Run the Application by running "python variousfiledownloadflask.py". Go to browser and type "http://localhost:8000/get-csv/<filename>", you can download the specified CSV File . . . ,
![](https://miro.medium.com/max/986/1*QJdRsCpe6BbFVMKGWOy3Aw.png)
# Returning Multiple Files using Flask
Suppose, If nosotros desire to send Multiple files to someone, this will help you
Yous can't send all files into downloadable one.Only if you convert all the files into ZIP and then y'all tin can send information technology as 1 file(nada file)
Create a file named "multiplefiledownloadflask.py"
- Importing the Libraries
import zipfile
import os
from flask import send_file,Flask,send_from_directory
two. Create an Case and Flask Routing
app = Flask(__name__)@app.route('/download_files')
def download_all():
# Cipher file Initialization
zipfolder = zipfile.ZipFile('Audiofiles.zero','w', compression = zipfile.ZIP_STORED) # Pinch type
# zip all the files which are inside in the binder
for root,dirs, files in os.walk('<foldername>'):
for file in files:
zipfolder.write('<foldername>'+file)
zipfolder.close()
return send_file('Audiofiles.zilch',
mimetype = 'zip',
attachment_filename= 'Audiofiles.zero',
as_attachment = True)
# Delete the zip file if not needed
os.remove("Audiofiles.nix")
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8000 , debug= Faux, threaded = True)
Here, I am using ZIP_STORED Pinch which means "Only Archiving without Compressing the files"
Some of the Compression Types are ZIP_STORED, ZIP_DEFLATED , ZIP_BZIP2, ZIP_LZMA
ZIP_STORED
: It'due south just archiving the Files and it's a Lossless Pinch ane
ZIP_DEFLATED
: This is usual Zero Compression Method
ZIP_BZIP2
: This method uses BZIP2 compression technique
ZIP_LZMA
: This method uses LZMA compression technique
For Detailed info about Pinch types, Hither is the link
Complete code for Returning Multiple Files
Run the Application past running "python multiplefiledownloadflask.py". Get to browser and type "http://localhost:8000/download_files", you will get a Zip File as downloadable one . . . ,
![](https://miro.medium.com/max/800/1*GVm0VWgoDwzMFhHvr78o4w.png)
Annotation : Ever use Incognito Style,while downloading files because cache may crusade to improper downloads . . .
The complete code is uploaded to the following GitHub repository
For Flask File Uploads, Check this . . ,
Conclusion
The commodity is a summary of "How to Return Single File and Multiple Files with Flask using Python"
Did you like this mail service and helpful to you . . .
Give me an Appreciation with Clap as much as you can and share
Thank you,
Bala Murugan N 1000
Source: https://medium.com/analytics-vidhya/receive-or-return-files-flask-api-8389d42b0684
0 Response to "Uploaded Dot Net Slash File Slash 23tendzb"
Post a Comment