Uploading Images to Flask From Ios Swift

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 make building web applications easier. Flask is extensible and doesn't force a particular construction or crave complicated average code before getting started. It gives developers flexibility.

Introduction

One important feature in spider web applications is the ability 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 bones flask app that will permit users to upload files.

Prerequisites

Going through this guide, it is assumed that the reader has a basic cognition of Python programming language, HTML, and they must have a central knowledge of flask; even though this guide will exist beginner-friendly.

In this guide, we will be using Python 3, and VS Lawmaking text editor you can download vscode and Python

Goal

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

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

Python virtual environment

A virtual environment is an isolated surroundings for Python projects. There is a module created past Python called venv which gives a developer a unique environs 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 organization, instead, information technology gives you freedom from the interference of other packages installed in the system. This makes it like shooting fish in a barrel to run any Python project on any computer irrespective of the Python version or packages installed in the arrangement.

How to create a virtual surround

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

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

To commencement, on a Windows device open PowerShell and make a directory using the control below:

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

Then create the virtual environment using the control:

Note that myenv is the name of my virtual environs it tin be whatsoever name you wish. Adjacent, actuate the virtual environment using the command:

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

            myenv\Scripts\actuate.bat                      

Creating our projection

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

Utilise the control below:

Note: tutorial is my project's name. Y'all can give yours any proper name y'all like. To build a flask application, we must start install flask.

To do that, we will use the command beneath:

After the installation, we will create a new file with the name app.py, update the file with the lawmaking below:

                          from              flask              import              Flask  app              =              Flask(__name__)              @app.route('/')              def              index():              return              "hello world"              if              __name__==('__main__'):     app.run(debug=Truthful)                      

From the lawmaking to a higher place we are importing flask from the flask library we installed.

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

The index() is our view role which volition return 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 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 dissimilar. If everything goes well yous will have a result like the ane shown below.

App running

To upload files, we volition employ the WTforms and the flask-uploads libraries. To piece of work with these libraries we demand to install them.

Do that with the command below:

            pip install flask_wtf, WTForms                      
            pip install flask-uploads                      

After the installation, nosotros will create a file field, by updating the code to the 1 beneath:

                          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.route('/')              def              index():     form              =              MyForm()              return              render_template('index.html')              if              __name__==('__main__'):     app.run(debug=True)                      

From the code above, we commencement by importing FlaskForm from flask_wtf and FileField from wtforms. Next, nosotros created a class for our form as Myform image is the file field our paradigm files will be saved to. We call our Form class in our index function. Nosotros inverse our return to render template.

This is likewise a flask library used for rendering HTML templates. From the code we rendered alphabetize.html. When nosotros employ render_template in Flask we create a folder called templates where nosotros store the HTML files. Now allow us create the HTML template we are rendering, within our templates folder.

Update the HTML file with the code below:

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

From the lawmaking above, our grade takes a method POST because we will exist posting a file. The csrf_token is a built-in function that handles security for us, and so we call our form field we created in our Form Class using form.image. Now we can run our app using python app.py. If everything is correct you will get a runtime error similar in the paradigm below.

RuntimeError

This error occurs whenever y'all try to use a csrf_token without calculation a secret_key to your project file. Let'southward add together a secret key to our code.

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

The secret_key can be anything you want.

Permit'south 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('image')              @app.route('/')              def              index():     grade              =              MyForm()              render              render_template('alphabetize.html', form              =              course)              if              __name__==('__main__'):     app.run(debug=True)                      

Our page should now look similar the picture below:

App running

From the lawmaking in a higher place, form=form is parsed and then that our form tin can be displayed on our HTML page. If we try to upload an epitome, nosotros volition run into 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, nosotros will add the code below to our route.

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

Afterward adding the above code, our upload will work only it won't be saved because we didn't give it a path to save to. This is where flask uploads come up into play.

Let'south import flask-uploads using the command:

                          from              flask_uploads              import              configure_uploads, IMAGES, UploadSet                      

configure_uploads enables united states to set the path for the image to be saved, IMAGES is the file type we are uploading.

We volition update our code with: app.config['UPLOADED_IMAGES_DEST'] = 'uploads/images this will 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              class.validate_on_submit():         filename              =              images.save(form.image.information)              return              f'Filename: {filename}'              return              render_template('index.html', class              =              form)                      

The above snippet will validate and save our image file.

Our final code will look similar the 1 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):     paradigm              =              FileField('image')              @app.road('/', methods=['Go',              'POST'])              def              index():     grade              =              MyForm()              if              form.validate_on_submit():         filename              =              images.save(form.image.data)              return              f'Filename: {filename}'              return              render_template('index.html', course              =              form)              if              __name__==('__main__'):     app.run(debug=True)                      

Afterwards uploading a file, the file name will be return as seen in the epitome below:

File Uploaded

Conclusion

Now nosotros can upload images. To upload other types of files all we demand 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 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

cooperconswited.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 Swift"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel