banner



How To Check For File Upload Flask

Flask is a lightweight or micro web framework built with Python that helps in creating spider web applications. Information technology provides useful tools and features that make edifice web applications easier. Flask is extensible and doesn't force a detail structure or require complicated boilerplate lawmaking 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 be pictures, PDF, audio CSV, etc. In this article, nosotros will await at how to set up a bones flask app that volition 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 have a central knowledge of flask; even though this guide volition be beginner-friendly.

In this guide, we will exist using Python 3, and VS Code text editor you lot tin download vscode and Python

Goal

We 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 environment
  • Setting upward 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 environment that enables the installation of all packages that are unique to a particular projection.

The virtual environment doesn't modify the default Python version or default packages installed in a system, instead, it gives you liberty from the interference of other packages installed in the system. This makes it easy to run whatever Python project on whatever figurer irrespective of the Python version or packages installed in the organisation.

How to create a virtual surroundings

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

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

To beginning, on a Windows device open PowerShell and make a directory using the command below:

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

And so create the virtual environment using the control:

Note that myenv is the proper noun of my virtual environment it can be any name you lot wish. Next, activate the virtual environs using the control:

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

            myenv\Scripts\activate.bat                      

Creating our project

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

Use the command beneath:

Notation: tutorial is my projection's name. Yous can give yours any name you like. To build a flask awarding, we must kickoff install flask.

To practise that, we will use the control beneath:

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

From the lawmaking above we are importing flask from the flask library we installed.

The @app.route is doing the routing for united states of america.

The index() is our view function which will return 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 folio whenever nosotros save changes. To run our app we run the command below on our last.

Annotation that app.py is the name of my app yours can be unlike. If everything goes well you will have a result like the one shown below.

App running

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

Practice that with the control beneath:

            pip install flask_wtf, WTForms                      
            pip install flask-uploads                      

Afterward the installation, we will create a file field, past updating the code to the ane below:

                          from              flask              import              Flask, render_template              from              flask_wtf              import              FlaskForm              from              wtforms              import              FileField  app              =              Flask(__name__)              class              MyForm(FlaskForm):     epitome              =              FileField('image')              @app.road('/')              def              index():     grade              =              MyForm()              return              render_template('index.html')              if              __name__==('__main__'):     app.run(debug=True)                      

From the code above, we start by importing FlaskForm from flask_wtf and FileField from wtforms. Next, we created a course for our form as Myform prototype is the file field our image files will exist saved to. We call our Grade class in our index function. Nosotros changed our return to render template.

This is besides a flask library used for rendering HTML templates. From the code we rendered index.html. When we employ 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, within our templates binder.

Update the HTML file with the lawmaking below:

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

From the lawmaking above, our form takes a method Postal service because we will exist posting a file. The csrf_token is a built-in role that handles security for u.s.a., then we phone call our form field we created in our Grade Form using course.epitome. Now we can run our app using python app.py. If everything is correct you volition get a runtime error like in the epitome below.

RuntimeError

This error occurs whenever you lot try 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 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):     epitome              =              FileField('prototype')              @app.route('/')              def              alphabetize():     form              =              MyForm()              return              render_template('index.html')              if              __name__==('__main__'):     app.run(debug=True)                      

The secret_key can be anything y'all desire.

Allow'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):     prototype              =              FileField('prototype')              @app.road('/')              def              index():     form              =              MyForm()              return              render_template('alphabetize.html', form              =              grade)              if              __name__==('__main__'):     app.run(debug=True)                      

Our page should now look like the picture below:

App running

From the lawmaking in a higher place, form=course is parsed and then that our form can be displayed on our HTML page. If we effort to upload an prototype, we will encounter another error equally shown below:

Method Not Allowed

This fault is frequently 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=['Go',              'POST'])                      

After adding the to a higher place code, our upload will piece of work but it won't be saved because nosotros didn't requite it a path to relieve to. This is where flask uploads come up into play.

Let's import flask-uploads using the command:

                          from              flask_uploads              import              configure_uploads, IMAGES, UploadSet                      

configure_uploads enables united states of america to fix the path for the image to be saved, IMAGES is the file type nosotros are uploading.

Nosotros volition update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images this will set the file path where the images volition 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.salve(form.image.data)              render              f'Filename: {filename}'              render              render_template('alphabetize.html', form              =              class)                      

The above snippet will validate and save our image file.

Our final code volition look like the i 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):     epitome              =              FileField('paradigm')              @app.route('/', methods=['Become',              'Postal service'])              def              index():     course              =              MyForm()              if              course.validate_on_submit():         filename              =              images.save(grade.image.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 exist return equally seen in the image beneath:

File Uploaded

Decision

Now we can 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 than virtually flask-uploads by clicking the link in the further reading department. 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: wongunwho1946.blogspot.com

0 Response to "How To Check For File Upload Flask"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel