banner



How To Upload File And Display In Python Flask Uploadset

Flask is a lightweight or micro web framework built with Python that helps in creating spider web applications. It provides useful tools and features that brand building web applications easier. Flask is extensible and doesn't force a particular structure or crave complicated average code earlier getting started. It gives developers flexibility.

Introduction

One important feature in web applications is the ability to let users upload files. These files could be pictures, PDF, audio CSV, etc. In this commodity, nosotros will await at how to set up up a basic flask app that volition allow users to upload files.

Prerequisites

Going through this guide, information technology is causeless that the reader has a basic knowledge of Python programming language, HTML, and they must accept a fundamental cognition of flask; fifty-fifty though this guide volition be beginner-friendly.

In this guide, we will exist using Python iii, and VS Code text editor y'all can download vscode and Python

Goal

We volition exist edifice a flask app that will enable users to upload files to a server. At the cease of this guide, the reader will be familiar with:

  • Creating a virtual environment
  • Activating a virtual environment
  • Setting upwards a flask app
  • Enabling file uploads

Python virtual environs

A virtual environment is an isolated environs for Python projects. There is a module created past Python called venv which gives a developer a unique surround that enables the installation of all packages that are unique to a particular projection.

The virtual environment doesn't alter the default Python version or default packages installed in a organisation, instead, information technology gives you liberty from the interference of other packages installed in the arrangement. This makes it like shooting fish in a barrel to run any Python projection on any computer irrespective of the Python version or packages installed in the organization.

How to create a virtual environment

The process of creating a virtual environment differs based on the operating arrangement. In this guide, we will wait at the procedure in the context of a windows operating organization.

Follow the link to see how it's done on a Mac and on a Ubuntu.

To start, on a Windows device open up PowerShell and make a directory using the command beneath:

Get into the new directory using the cd directory-proper name and so install the virtual surroundings using the command:

Then create the virtual environment using the command:

Notation that myenv is the name of my virtual surroundings it can be any proper name you wish. Next, activate the virtual environment using the command:

If you are using the control-line interface (CMD) your command will exist as beneath:

            myenv\Scripts\activate.bat                      

Creating our project

Afterwards activating our virtual environment, nosotros can now create our project. To do that, we volition brand a new directory for the project.

Use the command below:

NOTE: tutorial is my projection's name. Yous can give yours whatever name you like. To build a flask application, we must start install flask.

To do that, we will utilize the command beneath:

After the installation, we volition create a new file with the proper noun app.py, update the file with the lawmaking beneath:

                          from              flask              import              Flask  app              =              Flask(__name__)              @app.road('/')              def              index():              render              "hi earth"              if              __name__==('__main__'):     app.run(debug=True)                      

From the code above nosotros are importing flask from the flask library we installed.

The @app.route is doing the routing for the states.

The index() is our view function which will render our page content to the browser.

The if statement returns the app.run, which will enable us to run our app and so refresh our page whenever nosotros relieve 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 dissimilar. If everything goes well yous will have a result similar the one shown below.

App running

To upload files, nosotros will apply the WTforms and the flask-uploads libraries. To piece of work with these libraries we need to install them.

Do that with the command below:

            pip install flask_wtf, WTForms                      
            pip install flask-uploads                      

Later on the installation, we volition create a file field, by updating the code to the one below:

                          from              flask              import              Flask, render_template              from              flask_wtf              import              FlaskForm              from              wtforms              import              FileField  app              =              Flask(__name__)              course              MyForm(FlaskForm):     prototype              =              FileField('image')              @app.route('/')              def              index():     form              =              MyForm()              render              render_template('index.html')              if              __name__==('__main__'):     app.run(debug=Truthful)                      

From the code in a higher place, we beginning by importing FlaskForm from flask_wtf and FileField from wtforms. Side by side, nosotros created a form for our grade as Myform image is the file field our epitome files will exist saved to. We call our Form course in our alphabetize function. We changed our return to render template.

This is also a flask library used for rendering HTML templates. From the code we rendered alphabetize.html. When we utilise render_template in Flask we create a folder called templates where we store the HTML files. At present let us create the HTML template we are rendering, within our templates folder.

Update the HTML file with the lawmaking below:

                          !doctype html>              <html>              <head>              <title>File Upload</championship>              </head>              <trunk>              <form activity=              "/"              method=              "POST"              enctype=              "multipart/form-information"              >              {{ form.csrf_token }}         {{ class.image }}              <button blazon=              "submit"              >upload</button>              </course>              </body>              </html>                      

From the code above, our form takes a method Post because we will be posting a file. The csrf_token is a built-in function that handles security for us, then we call our grade field we created in our Form Class using grade.epitome. At present we can run our app using python app.py. If everything is correct you will get a runtime mistake like in the image beneath.

RuntimeError

This error occurs whenever y'all attempt to utilize a csrf_token without adding a secret_key to your project file. Let's add a secret key to our code.

Update your lawmaking to the i 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('image')              @app.route('/')              def              alphabetize():     form              =              MyForm()              return              render_template('index.html')              if              __name__==('__main__'):     app.run(debug=True)                      

The secret_key can be anything yous want.

Let's update our 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):     image              =              FileField('paradigm')              @app.route('/')              def              index():     form              =              MyForm()              return              render_template('index.html', form              =              class)              if              __name__==('__main__'):     app.run(debug=True)                      

Our page should now wait similar the moving-picture show below:

App running

From the code above, course=course is parsed so that our form can be displayed on our HTML page. If we try to upload an image, we will encounter another fault equally shown below:

Method Not Allowed

This error is ofttimes thrown when we don't specify a method to our road. To solve this, nosotros volition add the code beneath to our route.

                          @app.road('/', methods=['GET',              'POST'])                      

Later on calculation the above code, our upload volition work but it won't be saved because we didn't give it a path to save to. This is where flask uploads come into play.

Allow's import flask-uploads using the command:

                          from              flask_uploads              import              configure_uploads, IMAGES, UploadSet                      

configure_uploads enables us to gear up the path for the image to be saved, IMAGES is the file type nosotros are uploading.

We will update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images this will set 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              course.validate_on_submit():         filename              =              images.relieve(form.paradigm.data)              return              f'Filename: {filename}'              return              render_template('alphabetize.html', class              =              form)                      

The to a higher place snippet will validate and relieve our image 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)              class              MyForm(FlaskForm):     image              =              FileField('epitome')              @app.road('/', methods=['GET',              'Postal service'])              def              alphabetize():     form              =              MyForm()              if              class.validate_on_submit():         filename              =              images.salvage(form.image.data)              return              f'Filename: {filename}'              return              render_template('index.html', form              =              class)              if              __name__==('__main__'):     app.run(debug=True)                      

Later uploading a file, the file name will exist return as seen in the image below:

File Uploaded

Determination

Now we tin upload images. To upload other types of files all we need to do is to import them through flask upload, configure their destination path, and specify their file extension.

Larn more about flask-uploads past 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

Source: https://www.section.io/engineering-education/how-to-handle-file-uploads-with-flask/

Posted by: harriswassen.blogspot.com

0 Response to "How To Upload File And Display In Python Flask Uploadset"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel