Runtimeerror: No Destination for Set Images Flask Uploads
Flask is a lightweight or micro spider 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 strength a particular structure or require complicated boilerplate code before getting started. It gives developers flexibility.
Introduction
One of import feature in web applications is the power to let users upload files. These files could be pictures, PDF, audio CSV, etc. In this article, we will expect at how to set up a basic flask app that volition allow users to upload files.
Prerequisites
Going through this guide, it is causeless that the reader has a basic noesis of Python programming language, HTML, and they must have a fundamental noesis of flask; fifty-fifty though this guide volition be beginner-friendly.
In this guide, we will exist using Python iii, and VS Lawmaking text editor y'all can download vscode and Python
Goal
We will be edifice a flask app that will enable users to upload files to a server. At the end of this guide, the reader will be familiar with:
- Creating a virtual environment
- Activating a virtual environs
- Setting upwardly a flask app
- Enabling file uploads
Python virtual surround
A virtual environment is an isolated environment for Python projects. At that place is a module created past Python chosen venv which gives a developer a unique surroundings that enables the installation of all packages that are unique to a particular project.
The virtual environs doesn't change the default Python version or default packages installed in a system, instead, it gives you freedom from the interference of other packages installed in the arrangement. This makes it piece of cake to run whatever Python project on any computer irrespective of the Python version or packages installed in the system.
How to create a virtual environs
The procedure of creating a virtual environment differs based on the operating system. In this guide, we will look at the process in the context of a windows operating organisation.
Follow the link to run across how it's done on a Mac and on a Ubuntu.
To start, on a Windows device open PowerShell and make a directory using the command beneath:
Become into the new directory using the cd directory-name and so install the virtual environment using the control:
Then create the virtual surroundings using the command:
Note that myenv is the name of my virtual environment it can be any proper noun you wish. Next, activate the virtual environment using the command:
If yous are using the control-line interface (CMD) your control will be every bit below:
myenv\Scripts\actuate.bat Creating our project
After activating our virtual environment, we can at present create our project. To exercise that, we will make a new directory for the projection.
Use the command below:
NOTE:
tutorialis my project'due south proper name. You tin can give yours any name you like. To build a flask application, nosotros must showtime install flask.
To do that, nosotros will use the command below:
After the installation, we will create a new file with the proper 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 to a higher place we are importing flask from the flask library we installed.
The @app.road is doing the routing for usa.
The alphabetize() is our view function which will return our folio content to the browser.
The if statement returns the app.run, which will enable the states to run our app 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 proper noun of my app yours can be dissimilar. If everything goes well you will accept a result like the one shown beneath.
To upload files, nosotros will use the WTforms and the flask-uploads libraries. To work with these libraries we demand to install them.
Do that with the command below:
pip install flask_wtf, WTForms pip install flask-uploads Afterward the installation, we will create a file field, by updating the lawmaking to the 1 below:
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import FileField app = Flask(__name__) class MyForm(FlaskForm): image = FileField('image') @app.road('/') def index(): class = MyForm() return render_template('alphabetize.html') if __name__==('__main__'): app.run(debug=True) From the code above, we beginning by importing FlaskForm from flask_wtf and FileField from wtforms. Next, we created a class for our form as Myform image is the file field our paradigm files will be saved to. We call our Grade class in our index office. We changed our render to render template.
This is also a flask library used for rendering HTML templates. From the code nosotros rendered index.html. When nosotros utilise render_template in Flask we create a binder called templates where we store the HTML files. Now let us create the HTML template we are rendering, inside our templates folder.
Update the HTML file with the code below:
!doctype html> <html> <caput> <title>File Upload</title> </caput> <body> <course action= "/" method= "Mail" enctype= "multipart/form-data" > {{ form.csrf_token }} {{ form.image }} <button type= "submit" >upload</button> </form> </trunk> </html> From the code to a higher place, our form takes a method POST because nosotros volition be posting a file. The csrf_token is a built-in office that handles security for u.s.a., then nosotros phone call our class field we created in our Class Class using form.paradigm. Now nosotros can run our app using python app.py. If everything is correct y'all volition get a runtime error like in the image below.
This error occurs whenever you try to use a csrf_token without adding a secret_key to your project file. Let's add a secret key to our code.
Update your code 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): prototype = FileField('image') @app.route('/') def alphabetize(): form = MyForm() render render_template('index.html') if __name__==('__main__'): app.run(debug=True) The secret_key can be anything you desire.
Let'due south update our code to the ane beneath:
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.route('/') def index(): form = MyForm() render render_template('index.html', grade = form) if __name__==('__main__'): app.run(debug=True) Our page should at present await similar the motion picture below:
From the code above, course=form is parsed so that our course tin can be displayed on our HTML page. If we try to upload an prototype, we will see some other mistake as shown beneath:
This error is often thrown when we don't specify a method to our road. To solve this, we volition add the code below to our route.
@app.route('/', methods=['Get', 'POST']) After calculation the to a higher place lawmaking, our upload volition work but it won't be saved because we didn't give it a path to salve to. This is where flask uploads come into play.
Let's import flask-uploads using the control:
from flask_uploads import configure_uploads, IMAGES, UploadSet configure_uploads enables u.s. to fix the path for the image to exist saved, IMAGES is the file type we are uploading.
We volition update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images this volition set the file path where the images will exist saved, images = UploadSet('images', IMAGES) and configure_uploads(app, images) saves the file extension and configure the uploads.
if grade.validate_on_submit(): filename = images.save(form.image.data) return f'Filename: {filename}' return render_template('index.html', form = form) The higher up snippet volition validate and salve our paradigm file.
Our final code will look similar the one below:
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) class MyForm(FlaskForm): image = FileField('image') @app.route('/', methods=['Get', 'Post']) def index(): grade = MyForm() if form.validate_on_submit(): filename = images.save(class.prototype.data) render f'Filename: {filename}' return render_template('index.html', grade = form) if __name__==('__main__'): app.run(debug=Truthful) Afterward uploading a file, the file proper noun will be return equally seen in the image below:
Conclusion
At present we tin upload images. To upload other types of files all we need to practise 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 further 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
Source: https://www.section.io/engineering-education/how-to-handle-file-uploads-with-flask/
0 Response to "Runtimeerror: No Destination for Set Images Flask Uploads"
Post a Comment