Javascript required
Skip to content Skip to sidebar Skip to footer

Can I Add a New Page to Flask

The writer selected the Costless and Open Source Fund to receive a donation equally part of the Write for DOnations program.

Introduction

Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. It gives developers flexibility and is an accessible framework for new developers because you tin build a web application quickly using only a single Python file. Flask is also extensible and doesn't forcefulness a particular directory structure or crave complicated boilerplate code before getting started.

Learning Flask will allow you to chop-chop create web applications in Python. Y'all tin can take reward of Python libraries to add avant-garde features to your web application, like storing your data in a database, or validating web forms.

In this tutorial, you'll build a pocket-size spider web application that renders HTML text on the browser. You'll install Flask, write and run a Flask awarding, and run the application in development mode. You'll utilise routing to display various web pages that serve unlike purposes in your web awarding. Y'all'll too use view functions to let users to interact with the application through dynamic routes. Finally, you'll use the debugger to troubleshoot errors.

Prerequisites

  • A local Python 3 programming environment. Follow the tutorial for your distribution in How To Install and Set Up a Local Programming Surround for Python 3 series. In this tutorial we'll phone call our project directory flask_app.

  • An understanding of basic Python three concepts, such as data types, lists, functions, and other such concepts. If you are not familiar with Python, check out our How To Code in Python 3 series.

  • An agreement of bones HTML concepts. You lot can review the How To Build a Website with HTML tutorial series for background noesis.

Step 1 — Installing Flask

In this step, yous'll activate your Python environment and install Flask using the pip package installer.

Start, activate your programming environment if you haven't already:

                      
  1. source env/bin/activate

Once yous have activated your programming surroundings, install Flask using the pip install command:

                      
  1. pip install flask

Once the installation is consummate, you volition encounter a listing of installed packages in the terminal parts of the output, similar to the following:

                      

Output

... Installing nerveless packages: Werkzeug, MarkupSafe, Jinja2, itsdangerous, click, flask Successfully installed Jinja2-3.0.1 MarkupSafe-2.0.1 Werkzeug-2.0.one click-eight.0.ane flask-ii.0.1 itsdangerous-2.0.i

This means that installing Flask too installed several other packages. These packages are dependencies Flask needs to perform different functions.

You lot've created the project folder, a virtual environment, and installed Flask. You lot tin now motion on to setting up a simple application.

Step 2 — Creating a Uncomplicated Application

Now that y'all have your programming environs ready, you lot'll start using Flask. In this stride, y'all'll make a small Flask web awarding inside a Python file, in which you'll write HTML code to display on the browser.

In your flask_app directory, open up a file named app.py for editing, employ nano or your favorite text editor:

                      
  1. nano app.py

Write the post-obit lawmaking within the app.py file:

flask_app/app.py

                      from            flask            import            Flask  app            =            Flask(__name__)            @app.road            (            '/'            )            def            hello            (            )            :            return            '<h1>Hello, World!</h1>'                  

Save and close the file.

In the above lawmaking block, you kickoff import the Flask object from the flask package. Yous so employ it to create your Flask application instance, giving it the proper name app. You lot laissez passer the special variable __name__, which holds the name of the current Python module. This proper noun tells the instance where information technology's located; you lot need this because Flask sets up some paths backside the scenes.

Once you create the app case, y'all tin use it to handle incoming spider web requests and transport responses to the user. @app.route is a decorator that turns a regular Python function into a Flask view part, which converts the function's return value into an HTTP response to exist displayed by an HTTP client, such as a spider web browser. Yous pass the value '/' to @app.route() to signify that this function will respond to spider web requests for the URL /, which is the main URL.

The hi() view part returns the string '<h1>Hi, World!</h1>' equally an HTTP response.

You now take a unproblematic Flask application in a Python file called app.py, in the adjacent step, you will run the application to see the result of the hi() view function rendered in a web browser.

Stride 3 — Running the Awarding

Afterward creating the file that contains the Flask awarding, you'll run it using the Flask command line interface to start the development server and render on the browser the HTML code you lot wrote as a return value for the hello() view function in the previous step.

Kickoff, while in your flask_app directory with your virtual environment activated, tell Flask where to find the application (app.py in your case) using the FLASK_APP environment variable with the following command (on Windows, use set instead of export):

                      
  1. export FLASK_APP =app

And so specify that you desire to run the application in evolution mode (so yous can use the debugger to catch errors) with the FLASK_ENV environment variable:

                      
  1. export FLASK_ENV =evolution

Lastly, run the awarding using the flask run command:

                      
  1. flask run

One time the application is running, the output will exist something like this:

                      

Output

* Serving Flask app "app" (lazy loading) * Environs: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Printing CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger Pivot: 296-353-699

The preceding output has several pieces of information, such as:

  • The proper noun of the awarding you're running ("app").
  • The environment in which the application is existence run (development).
  • Debug manner: on signifies that the Flask debugger is running. This is useful when developing because it provides detailed error letters when things become wrong, which makes troubleshooting easier.
  • The awarding is running locally on the URL http://127.0.0.1:5000/. 127.0.0.ane is the IP that represents your machine's localhost and :5000 is the port number.

Open a browser and type in the URL http://127.0.0.i:5000/. You will see the text How-do-you-do, Globe! in an <h1> heading as a response. This confirms that your application is successfully running.

"Hello, World!" in an H1 heading

If you want to terminate the evolution server, press CTRL+C.

Alert: Flask uses a simple web server to serve your application in a development environment, which also means that the Flask debugger is running to brand catching errors easier. You should non utilize this development server in a production deployment. See the Deployment Options page on the Flask documentation for more data. You can besides check out this Flask deployment tutorial with Gunicorn or this one with uWSGI or you can use DigitalOcean App Platform to deploy your Flask application past following the How To Deploy a Flask App Using Gunicorn to App Platform tutorial.

To continue developing the app.py application, leave the development server running and open another terminal window. Motion into the flask_app directory, activate the virtual environment, set the environment variables FLASK_ENV and FLASK_APP, and continue to the next steps. (These commands are listed earlier in this pace.)

Note: When opening a new last, or when you lot close the i y'all are running the development server on and want to rerun it, it is of import to remember activating the virtual environment and setting the environment variables FLASK_ENV and FLASK_APP for the flask run control to work properly.

You only need to run the server once in 1 last window.

While a Flask application's evolution server is already running, information technology is not possible to run some other Flask application with the same flask run command. This is because flask run uses the port number 5000 by default, and in one case information technology is taken, it becomes unavailable to run another application on so you would receive an error similar to the following:

                          

Output

OSError: [Errno 98] Address already in employ

To solve this trouble, either end the server that'south currently running via CTRL+C, then run flask run again, or if yous want to run both applications at the same fourth dimension, you can pass a different port number to the -p statement, for example, to run some other application on port 5001 utilise the following control:

                          
  1. flask run -p 5001

With this you can have one application running on http://127.0.0.1:5000/ and another one on http://127.0.0.1:5001/ if y'all desire to.

You now have a small Flask web application. You've run your application and displayed information on the web browser. Next, you'll acquire nearly routes and how to employ them to serve multiple web pages.

Step iv — Routes and View Functions

In this step, you'll add a few routes to your application to display different pages depending on the requested URL. You lot'll also learn most view functions and how to use them.

A route is a URL y'all can apply to determine what the user receives when they visit your web application on their browser. For instance, http://127.0.0.ane:5000/ is the main route that might be used to brandish an alphabetize page. The URL http://127.0.0.1:5000/about may be another route used for an almost page that gives the visitor some data about your web application. Similarly, you can create a road that allows users to sign in to your awarding at http://127.0.0.ane:5000/login.

Your Flask application currently has one route that serves users who asking the master URL (http://127.0.0.1:5000/). To demonstrate how to add a new web page to your awarding, you will edit your application file to add together some other route that provides information on your web application at http://127.0.0.1:5000/about.

Get-go, open your app.py file for editing:

                      
  1. nano app.py

Edit the file by calculation the following highlighted code at the stop of the file:

flask_app/app.py

                      from            flask            import            Flask  app            =            Flask(__name__)            @app.route            (            '/'            )            def            hello            (            )            :            return            '<h1>Hello, World!</h1>'                          @app.route              (              '/almost/'              )                                      def              about              (              )              :                                      return              '<h3>This is a Flask web application.</h3>'                              

Save and close the file.

Yous added a new function chosen about(). This office is busy with the @app.route() decorator that transforms it into a view function that handles requests for the http://127.0.0.1:5000/virtually endpoint.

With the development server running, visit the following URL using your browser:

          http://127.0.0.one:5000/nigh                  

Yous volition come across the text This is a Flask web application. rendered in an <h3> HTML heading.

You can as well use multiple routes for ane view function. For instance, yous can serve the index page at both / and /index/. To exercise this, open your app.py file for editing:

                      
  1. nano app.py

Edit the file by adding some other decorator to the hello() view function:

flask_app/app.py

                      from            flask            import            Flask  app            =            Flask(__name__)            @app.route            (            '/'            )                          @app.route              (              '/index/'              )                        def            hello            (            )            :            return            '<h1>Hello, World!</h1>'            @app.road            (            '/about/'            )            def            about            (            )            :            return            '<h3>This is a Flask web awarding.</h3>'                  

Save and shut the file.

After adding this new decorator, you tin can access the alphabetize page at both http://127.0.0.ane:5000/ and http://127.0.0.1:5000/index.

You now understand what routes are, how to use them to brand view functions, and how to add new routes to your application. Next, yous'll use dynamic routes to allow users to control the application's response.

Step 5 — Dynamic Routes

In this footstep, yous'll employ dynamic routes to permit users to interact with the application. Yous'll make a road that capitalizes words passed through the URL, and a road that adds ii numbers together and displays the result.

Normally, users don't interact with a web application by manually editing the URL. Rather, the user interacts with elements on the folio that atomic number 82 to different URLs depending on the user's input and action, but for the purposes of this tutorial, you will edit the URL to demonstrate how to make the application respond differently with different URLs.

First, open your app.py file for editing:

                      
  1. nano app.py

If yous allow the user to submit something to your web awarding, such as a value in the URL as you are going to practice in the post-obit edit, y'all should always keep in mind that your app should not directly display untrusted information (data the user submits). To display user information safely, use the escape() part that comes with the markupsafe bundle, which was installed along with Flask.

Edit app.py and add the post-obit line to the acme of the file, in a higher place the Flask import:

flask_app/app.py

                                    from              markupsafe              import              escape            from            flask            import            Flask            # ...                  

Then, add the following route to the end of the file:

flask_app/app.py

                      # ...            @app.route            (            '/capitalize/<word>/'            )            def            capitalize            (word)            :            return            '<h1>{}</h1>'            .            format            (escape(word.capitalize(            )            )            )                  

Save and close the file.

This new route has a variable section <word>. This tells Flask to take the value from the URL and pass information technology to the view function. The URL variable <word> passes a keyword argument to the capitalize() view function. The argument has the same name as the URL variable (word in this case). With this you can access the word passed through the URL and respond with a capitalized version of it using the capitalize() method in Python.

You use the escape() function you imported before to return the word string as text. This is of import to avert Cross Site Scripting (XSS) attacks. If the user submits malicious JavaScript instead of a word, escape() volition it render as text and the browser will not run it, keeping your web application safe.

To display the capitalized word inside an <h1> HTML heading, you use the format() Python method, for more on this method, see How To Use Cord Formatters in Python iii

With the evolution server running, open up your browser and visit the following URLs. You can replace the highlighted words with whatever word of your pick.

          http://127.0.0.i:5000/capitalize/hello            http://127.0.0.1:5000/capitalize/flask            http://127.0.0.1:5000/capitalize/python                  

Y'all can run across the word in the URL capitalized in an <h1> tag on the folio.

You can besides use multiple variables in a route. To demonstrate this, you will add together a route that adds two positive integer numbers together and displays the result.

Open up your app.py file for editing:

                      
  1. nano app.py

Add together the following road to the cease of the file:

flask_app/app.py

                      # ...            @app.route            (            '/add/<int:n1>/<int:n2>/'            )            def            add            (n1,            n2)            :            return            '<h1>{}</h1>'            .            format            (n1            +            n2)                  

Save and close the file.

In this route, you use a special converter int with the URL variable (/add/<int:n1>/<int:n2>/) which just accepts positive integers. By default, URL variables are assumed to be strings and are treated as such.

With the development server running, open your browser and visit the following URL:

          http://127.0.0.one:5000/add/v/5/                  

The result will be the sum of the ii numbers (x in this instance).

You now accept an understanding of how to apply dynamic routes to display unlike responses in a single route depending on the requested URL. Next, you'll larn how to troubleshoot and debug your Flask application in case of an mistake.

Step half-dozen — Debugging A Flask Application

When developing a web application, you will frequently run into situations where the application displays an error instead of the behavior y'all expect. You may misspell a variable or forget to define or import a function. To brand fixing these issues easier, Flask provides a debugger when running the application in development mode. In this stride, you will learn how to gear up errors in your awarding using the Flask debugger.

To demonstrate how to handle errors, you will create a road that greets a user from a listing of usernames.

Open your app.py file for editing:

                      
  1. nano app.py

Add the following road to the end of the file:

flask_app/app.py

                      # ...            @app.road            (            '/users/<int:user_id>/'            )            def            greet_user            (user_id)            :            users            =            [            'Bob'            ,            'Jane'            ,            'Adam'            ]            render            '<h2>Hi {}</h2>'            .            format            (users[user_id]            )                  

Save and close the file.

In the road above, the greet_user() view role receives a user_id argument from the user_id URL variable. Y'all use the int converter to accept positive integers. Inside the function, you take a Python list chosen users, which contains three strings representing usernames. The view function returns a string that is constructed depending on the provided user_id. If the user_id is 0, the response will exist How-do-you-do Bob in an <h2> tag because Bob is the first detail in the listing (the value of users[0]).

With the development server running, open your browser and visit the post-obit URLs:

          http://127.0.0.one:5000/users/0 http://127.0.0.i:5000/users/ane http://127.0.0.1:5000/users/2                  

You volition receive the following responses:

                      

Output

Hi Bob Hi Jane Hello Adam

This works well and then far, just it can become incorrect when you request a greeting for a user who doesn't exist. To demonstrate how the Flask debugger works, visit the following URL:

          http://127.0.0.one:5000/users/3                  

You'll see a page that looks like this:

Flask Debugger

At the elevation, the page gives you the proper name of the Python exception, which is IndexError, indicating that the list index (three in this case) is out of the listing's range (which is simply from 0 to ii because the list has but three items). In the debugger, you tin see the traceback that tells y'all the lines of lawmaking that raised this exception.

The last two lines of the traceback usually give the source of the error. In your instance the lines may be something like the following:

          File "/home/USER/flask_app/app.py", line 28, in greet_user            return '<h2>Hullo {}</h2>'.format(users[user_id])                  

This tells you that the fault originates from the greet_user() function inside the app.py file, specifically in the return line.

Knowing the original line that raises the exception will help yous determine what went wrong in your lawmaking, and determine what to do to fix it.

In this instance you can use a elementary endeavor...except clause to fix this error. If the requested URL has an index outside the list's range, the user will receive a 404 Not Found error, which is an HTTP error that tells the user the page they are looking for does not exist.

Open up your app.py file for editing:

                      
  1. nano app.py

To answer with an HTTP 404 error, you lot will need Flask'southward abort() function, which tin be used to make HTTP fault responses. Change the 2d line in the file to besides import this part:

flask_app/app.py

                      from            markupsafe            import            escape            from            flask            import            Flask              ,              abort                  

Then edit the greet_user() view function to look as follows:

flask_app/app.py

                      # ...            @app.route            (            '/users/<int:user_id>/'            )            def            greet_user            (user_id)            :            users            =            [            'Bob'            ,            'Jane'            ,            'Adam'            ]                          try              :                                      render              '<h2>Hi {}</h2>'              .              format              (users[user_id]              )                                      except              IndexError:                        arrest(              404              )                              

You utilise try in a higher place to test the render expression for errors. If there was no fault, meaning that user_id has a value that matches an alphabetize in the users list, the awarding volition answer with the appropriate greeting. If the value of user_id is outside the listing's range, an IndexError exception will be raised, and y'all use except to grab the error and respond with an HTTP 404 fault using the arrest() Flask helper function.

At present, with the development server running, visit the URL again:

          http://127.0.0.ane:5000/users/3                  

This time you'll see a standard 404 fault page informing the user that the folio does not exist.

Past the end of this tutorial, your app.py file volition await like this:

flask_app/app.py

                      from            markupsafe            import            escape            from            flask            import            Flask,            arrest  app            =            Flask(__name__)            @app.route            (            '/'            )            @app.road            (            '/index/'            )            def            hello            (            )            :            return            '<h1>Howdy, Globe!</h1>'            @app.route            (            '/about/'            )            def            about            (            )            :            render            '<h3>This is a Flask web application.</h3>'            @app.route            (            '/capitalize/<word>/'            )            def            capitalize            (discussion)            :            return            '<h1>{}</h1>'            .            format            (escape(word.capitalize(            )            )            )            @app.route            (            '/add/<int:n1>/<int:n2>/'            )            def            add            (n1,            n2)            :            return            '<h1>{}</h1>'            .            format            (n1            +            n2)            @app.route            (            '/users/<int:user_id>/'            )            def            greet_user            (user_id)            :            users            =            [            'Bob'            ,            'Jane'            ,            'Adam'            ]            try            :            return            '<h2>Hi {}</h2>'            .            format            (users[user_id]            )            except            IndexError:            arrest(            404            )                  

You now take a general idea of how to use the Flask debugger to troubleshoot your errors and assistance yous make up one's mind the advisable course of action to fix them.

Decision

Y'all now have a general agreement of what Flask is, how to install it, and how to employ information technology to write a web awarding, how to run the development server, and how to use routes and view functions to display different web pages that serve specific purposes. Yous've also learned how to use dynamic routes to permit users to interact with your web application via the URL, and how to use the debugger to troubleshoot errors.

If you lot would similar to read more virtually Flask, check out the Flask topic page.

wunderlichmilatichated.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-create-your-first-web-application-using-flask-and-python-3