Web Application Framework Flask

FLASK

Flask is a micro web framework written in Python

What is Web Framework?

Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.

Installation:

virtualenv which is a virtual Python environment builder, is used to help a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.

The following command installs virtualenv

Once installed, a new virtual environment is created in a folder.

So now we have a virtual environment Test created in the FlaskTest folder

We now install Flask in this environment.

Now we have Flask installed in our system and we can import it in our projects.

As we have setup environment to work with Flask library, lets run a sample code to test Flask. Let’s create a python file HelloWorld.py and write the following code:

  • The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be displayed.
  • The run() method of Flask class runs the application on the local development server.

All parameters for the run function are optional

host

Hostname to listen on. Defaults to 127.0.0.1 (localhost). You have to set it to ‘0.0.0.0’ to have server available externally

port

Default value is 5000

debug

Default value is false. If it is set to true, we get debug information

options

To be forwarded to underlying Werkzeug server.

Now we can execute the program and see its working. Execute the program using the command

You will get the following output.

Now if you open your browser and type in your localhost address that is, 127.0.0.1 along with the port number 5000

127.0.0.1:5000

You can see HELLO WORLD being printed on your browser.

You can use Ctrl+C to stop running the program.

Now if you need to set a specific URL other than the homepage of localhost, you can specify it in the route() function.

If you change the route function in the above code to:

And run the program again, you can see that opening the homepage of localhost renders no output, but instead if you add the URL specified in route function to the homepage address:

127.0.0.1:5000/hello

Now you can see your program being run…

Benefits of Flask:

  • Extensibility
  • Faster development
  • Easier to read, write and maintain

Have fun working with Flask library

Leave a Reply

bodrum escort - eskişehir esc - mersin escort - mersin escort bayan - mersin esc