How to Retrieve Files to Upload in Flask

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 detail structure or require complicated average code before getting started. Information technology gives developers flexibility.

Introduction

I important characteristic in web applications is the ability to let users upload files. These files could exist pictures, PDF, audio CSV, etc. In this article, we volition look at how to set up a basic flask app that will permit users to upload files.

Prerequisites

Going through this guide, it is causeless that the reader has a bones noesis of Python programming language, HTML, and they must have a fundamental knowledge of flask; fifty-fifty though this guide volition be beginner-friendly.

In this guide, nosotros will be using Python three, and VS Code text editor you can download vscode and Python

Goal

Nosotros will exist 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 up a flask app
  • Enabling file uploads

Python virtual environment

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

The virtual environment doesn't change the default Python version or default packages installed in a system, instead, information technology gives you liberty 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 system.

How to create a virtual surroundings

The procedure of creating a virtual environment differs based on the operating system. In this guide, we volition await at the procedure in the context of a windows operating organisation.

Follow the link to meet how information technology'south washed on a Mac and on a Ubuntu.

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

Get into the new directory using the cd directory-proper name then install the virtual environment using the command:

And then create the virtual environment using the command:

Note that myenv is the proper noun of my virtual environment information technology can be whatever name you wish. Next, activate the virtual environment using the command:

If you lot are using the command-line interface (CMD) your control will be as below:

            myenv\Scripts\activate.bat                      

Creating our project

Afterward activating our virtual environment, we tin can now create our project. To do that, we will make a new directory for the project.

Use the command below:

Note: tutorial is my project's name. You lot tin can give yours whatever name you like. To build a flask awarding, nosotros must first install flask.

To do that, we will employ the command below:

After 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              index():              return              "hello earth"              if              __name__==('__main__'):     app.run(debug=True)                      

From the code above we 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 volition render our page content to the browser.

The if statement returns the app.run, which will enable us to run our app then refresh our folio whenever we salve changes. To run our app we run the command beneath on our terminal.

Note that app.py is the name of my app yours can exist unlike. If everything goes well you will have a effect like the i shown below.

App running

To upload files, we volition use the WTforms and the flask-uploads libraries. To work with these libraries we need to install them.

Do that with the command below:

            pip install flask_wtf, WTForms                      
            pip install flask-uploads                      

Afterwards the installation, we volition create a file field, by updating the code to the i below:

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

From the lawmaking above, we start 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 epitome files will be saved to. We call our Form course in our alphabetize function. Nosotros 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 chosen templates where we store the HTML files. Now let us create the HTML template we are rendering, inside our templates binder.

Update the HTML file with the code below:

                          !doctype html>              <html>              <head>              <championship>File Upload</title>              </head>              <torso>              <form activity=              "/"              method=              "POST"              enctype=              "multipart/form-data"              >              {{ course.csrf_token }}         {{ form.image }}              <push button type=              "submit"              >upload</push>              </form>              </body>              </html>                      

From the code in a higher place, our class takes a method POST because we will be posting a file. The csrf_token is a built-in function that handles security for u.s., so nosotros call our form field we created in our Form Class using form.paradigm. At present we can run our app using python app.py. If everything is correct you will get a runtime mistake similar in the paradigm below.

RuntimeError

This error occurs whenever you endeavour to use a csrf_token without adding a secret_key to your project file. Let's add a secret key to our lawmaking.

Update your 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('image')              @app.road('/')              def              alphabetize():     form              =              MyForm()              return              render_template('alphabetize.html')              if              __name__==('__main__'):     app.run(debug=Truthful)                      

The secret_key can be anything you lot desire.

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

Our page should at present await like the moving-picture show below:

App running

From the code above, course=form is parsed so that our form can be displayed on our HTML page. If we try to upload an prototype, we volition encounter another error as shown below:

Method Not Allowed

This error is often thrown when we don't specify a method to our route. To solve this, we will add the code below to our route.

                          @app.route('/', methods=['GET',              'Post'])                      

Later on calculation the above code, our upload will work but it won't exist saved because we didn't requite it a path to relieve 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 us to prepare the path for the paradigm to be saved, IMAGES is the file type nosotros are uploading.

Nosotros will update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images this will gear up 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.image.data)              return              f'Filename: {filename}'              render              render_template('index.html', class              =              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)              grade              MyForm(FlaskForm):     image              =              FileField('image')              @app.route('/', methods=['GET',              'POST'])              def              index():     form              =              MyForm()              if              form.validate_on_submit():         filename              =              images.save(course.image.data)              render              f'Filename: {filename}'              return              render_template('index.html', form              =              grade)              if              __name__==('__main__'):     app.run(debug=Truthful)                      

Subsequently uploading a file, the file name volition exist return equally seen in the prototype beneath:

File Uploaded

Decision

Now nosotros can 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 almost 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

feuersteinthemarly.blogspot.com

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

0 Response to "How to Retrieve Files to Upload in Flask"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel