Uploading Images to Flask From Ios Not Working
Flask is a lightweight or micro web framework built with Python that helps in creating web applications. It provides useful tools and features that brand building web applications easier. Flask is extensible and doesn't force a particular construction or crave complicated boilerplate code before getting started. It gives developers flexibility.
Introduction
One important feature in web applications is the ability to let users upload files. These files could exist pictures, PDF, sound CSV, etc. In this article, we will look at how to gear up a bones flask app that will allow users to upload files.
Prerequisites
Going through this guide, it is assumed that the reader has a basic knowledge of Python programming language, HTML, and they must take a cardinal knowledge of flask; fifty-fifty though this guide will exist beginner-friendly.
In this guide, nosotros will exist using Python 3, and VS Lawmaking text editor y'all can download vscode and Python
Goal
We will be building a flask app that will enable users to upload files to a server. At the cease of this guide, the reader volition be familiar with:
- Creating a virtual surroundings
- Activating a virtual surround
- Setting up a flask app
- Enabling file uploads
Python virtual environment
A virtual environs is an isolated environment for Python projects. There is a module created by Python called venv which gives a developer a unique environs that enables the installation of all packages that are unique to a detail project.
The virtual environment doesn't alter the default Python version or default packages installed in a system, instead, information technology gives you freedom from the interference of other packages installed in the system. This makes it easy to run any Python project on whatsoever computer irrespective of the Python version or packages installed in the arrangement.
How to create a virtual environment
The process of creating a virtual surround differs based on the operating system. In this guide, we will wait at the procedure in the context of a windows operating arrangement.
Follow the link to meet how it's washed on a Mac and on a Ubuntu.
To outset, on a Windows device open PowerShell and make a directory using the control below:
Get into the new directory using the cd directory-name
and so install the virtual environment using the command:
Then create the virtual environment using the command:
Note that myenv
is the name of my virtual surroundings it can exist any name you wish. Next, activate the virtual environment using the command:
If you are using the control-line interface (CMD) your command volition be as below:
myenv\Scripts\activate.bat
Creating our project
After activating our virtual environs, we tin can now create our projection. To do that, nosotros will brand a new directory for the project.
Apply the control below:
Notation:
tutorial
is my project'south name. You can requite yours any name y'all like. To build a flask application, we must beginning install flask.
To do that, we will utilise the command below:
Afterwards the installation, we will create a new file with the name app.py
, update the file with the code below:
from flask import Flask app = Flask(__name__) @app.route('/') def alphabetize(): return "hello world" if __name__==('__main__'): app.run(debug=True)
From the code higher up we are importing flask from the flask library we installed.
The @app.route
is doing the routing for us.
The index()
is our view function which will render our page content to the browser.
The if statement returns the app.run
, which volition enable u.s.a. to run our app and then refresh our page whenever nosotros save changes. To run our app we run the command below on our terminal.
Note that app.py
is the name of my app yours tin be unlike. If everything goes well you will have a consequence like the ane shown beneath.
To upload files, we will use the WTforms
and the flask-uploads
libraries. To piece of work with these libraries we need to install them.
Do that with the control beneath:
pip install flask_wtf, WTForms
pip install flask-uploads
After the installation, we will create a file field, by updating the code to the one beneath:
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import FileField app = Flask(__name__) class MyForm(FlaskForm): prototype = FileField('paradigm') @app.route('/') def index(): form = MyForm() return render_template('alphabetize.html') if __name__==('__main__'): app.run(debug=True)
From the code above, nosotros offset by importing FlaskForm
from flask_wtf
and FileField
from wtforms
. Next, we created a class for our form every bit Myform
image is the file field our image files will be saved to. We call our Form class in our index function
. We inverse our return
to render template
.
This is also a flask library used for rendering HTML templates. From the code we rendered index.html
. When we use render_template in Flask we create a folder called templates where we store the HTML files. Now let us create the HTML template nosotros are rendering, inside our templates folder.
Update the HTML file with the code below:
!doctype html> <html> <head> <championship>File Upload</title> </caput> <torso> <form action= "/" method= "Post" enctype= "multipart/course-information" > {{ form.csrf_token }} {{ grade.image }} <button blazon= "submit" >upload</button> </form> </body> </html>
From the lawmaking in a higher place, our form takes a method POST
because we will be posting a file. The csrf_token
is a congenital-in function that handles security for u.s.a., then we call our course field we created in our Form Class
using form.image
. Now we tin run our app using python app.py
. If everything is right you lot will get a runtime mistake similar in the epitome below.
This error occurs whenever y'all try to employ a csrf_token
without adding a secret_key
to your project file. Permit's add a hole-and-corner key
to our code.
Update your code to the 1 below:
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import FileField app = Flask(__name__) app.config['SECRET_KEY'] = 'mysecretkey' class MyForm(FlaskForm): image = FileField('prototype') @app.road('/') def alphabetize(): grade = MyForm() return render_template('index.html') if __name__==('__main__'): app.run(debug=True)
The secret_key
can exist anything you want.
Let'south update our lawmaking to the one below:
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import FileField app = Flask(__name__) app.config['SECRET_KEY'] = 'mysecretkey' class MyForm(FlaskForm): image = FileField('image') @app.route('/') def index(): form = MyForm() return render_template('index.html', class = form) if __name__==('__main__'): app.run(debug=True)
Our page should at present expect like the picture below:
From the lawmaking to a higher place, grade=class
is parsed and so that our form can exist displayed on our HTML page. If we try to upload an image, nosotros will encounter another fault as shown below:
This error is oftentimes thrown when we don't specify a method to our road
. To solve this, we will add the code below to our route.
@app.road('/', methods=['Become', 'POST'])
After adding the above code, our upload will work but it won't exist saved considering we didn't give it a path to save to. This is where flask uploads
come up into play.
Let'southward import flask-uploads
using the command:
from flask_uploads import configure_uploads, IMAGES, UploadSet
configure_uploads
enables u.s.a. to gear up the path for the prototype to be saved, IMAGES
is the file type we are uploading.
We will update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images
this will ready the file path where the images will be saved, images = UploadSet('images', IMAGES)
and configure_uploads(app, images)
saves the file extension and configure the uploads.
if form.validate_on_submit(): filename = images.save(form.prototype.data) return f'Filename: {filename}' return render_template('index.html', form = form)
The above snippet will validate and relieve our prototype file.
Our final code will look like the one beneath:
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import FileField from flask_uploads import configure_uploads, IMAGES, UploadSet app = Flask(__name__) app.config['SECRET_KEY'] = 'thisisasecret' app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images' images = UploadSet('images', IMAGES) configure_uploads(app, images) course MyForm(FlaskForm): image = FileField('image') @app.route('/', methods=['Go', 'Mail service']) def index(): form = MyForm() if class.validate_on_submit(): filename = images.relieve(grade.prototype.data) return f'Filename: {filename}' render render_template('index.html', course = form) if __name__==('__main__'): app.run(debug=True)
Afterward uploading a file, the file name will be return as seen in the image below:
Conclusion
Now we can upload images. To upload other types of files all nosotros need to do is to import them through flask upload, configure their destination path, and specify their file extension.
Learn more about flask-uploads by clicking the link in the farther reading section. Link to project Github Repo.
Happy coding!
Further reading
- flask-upload
- WTForms
- flask Documentation for file uploads
Peer Review Contributions by: Jerim Kaura
harrisprityruccon.blogspot.com
Source: https://www.section.io/engineering-education/how-to-handle-file-uploads-with-flask/
0 Response to "Uploading Images to Flask From Ios Not Working"
Post a Comment