Basic Structure of Flask Application

Introduction

In this article, we will learn about the enriched parts of a Flask application. The initially and most imperative decision that we will ever make for our project is how can organize it. We should ask ourselves following questions;

  • What the best Flask project structure is?
  • What will our project need?
  • Is it changed from other project’s we’ve done already?
  • How can we have one single project structure that will make sure our project will not have a problem?
  • How can that project at the same time will likewise permit us to develop and keep emergent?

Description

  • Altogether Flask applications need to create an application instance.
  • The web server clearances all requests it obtains from clients to this object.
  • Those are for controlling and using a protocol called Web Server Gateway Interface (WSGI).
  • The application instance is created as an object of class Flask.
  • That is commonly created as follows:
from flask import Flask
app = Flask(__name__)
  • The first necessary argument to the Flask class constructor is the name of the main module or package of the application.
  • For best applications, Python’s __name__ variable is the right value.
  • Flask practices this argument to regulate the root path of the application.
  • Therefore that it far along may find resource files relative to the location of the application.

Routes and View Functions

  • Clients for example web browsers send requests to the web server.
  • That in sequence sends them to the Flask application instance.
  • The application instance requires to identify what code needs to run for each URL requested.
  • Therefore it saves a mapping of URLs to Python functions.
  • The relationship between a URL and the function that grips it is named a route.
  • The most suitable method to define a route in a Flask application is via the app.route decorator.
  • That is unprotected by the application instance.
  • That registers the decorated function as a route.
  • The following illustration demonstrates how a route is stated using this decorator:
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
  • The preceding illustration registers the function index () by way of the handler for the application’s root URL.
  • Navigating to http://www.example.com on our browser would trigger index () to run on the server if this application were set up on a server related with the www.example.com domain name.
  • The return value of this function the client receives is known as the response.
  • The response is the document that is showed to the user if the client is a web browser.
  • Functions corresponding index () are named view functions.
  • A response returned with a view function may be a simple string with HTML content. It may also take extra difficult forms.
  • Some URLs for services have variable sections. For instance, the URL for our Facebook profile page is http://www.facebook.com/<our-name>.
  • Therefore our username is part of it.
  • Flask supports these types of URLs by a special syntax in the route decorator.
  • The below example describes a route that has a vibrant name component.
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name
  • The part bounded in angle brackets is the dynamic part.
  • Consequently any URLs matches the static portions will be mapped to this route.
  • Flask sends the forceful component as an argument when the view function is raised.
  • This argument is used to make a personalized greeting as a response in the prior example view function.
  • The active components in routes are strings by default.
  • On the other hand may also be defined with a type.
  • For instance, route /user/<int:id> will match only URLs that have an integer in the id active segment.
  • Flask provisions type’s int, float, and path for routes.
  • The path type similarly indicates a string.
  • That consider slashes as part of the forceful component.

Server Startup

  • The application instance has a run method.
  • That presents Flask’s integrated development web server.
if __name__ == '__main__':
app.run(debug=True)
  • The __name__ == ‘__main__’ Python idiom is used to make sure that the development web server is started only when the script is performed openly.
  • It is expected that the parent script will launch a different server when the script is imported by another script.
  • Therefore, the app.run() call is missed.
  • The server goes into a loop.
  • That waits for requests and services them when starts up.
  • This loop continues up to the application is stopped.
  • For instance by hitting Ctrl-C.
  • There are many option arguments that may be given to app.run() to configure the mode of operation of the web server.
  • It is suitable to allow debug mode during development.
  • That between other things activates the debugger and the reloader.
  • This is completed by passing the argument debug set to True.

A Complete Application

  • We have learnt about the different parts of a Flask web application up till now.
  • Currently, we will write those parts.
  • The complete hello.py application script is associated with three parts defined prior joint in a single file.
  • The application is shown in the following example.

Example: hello.py: A complete Flask application

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
if __name__ == '__main__':
app.run(debug=True)
  • Make assure the earlier created virtual environment is activated to run the application and has Flask installed.
  • At the present open the web browser and type http:// 127.0.0.1:5000/ in the address bar.
  • Below figure displays the web browser after linking to the application.

Hello World

  • At that time launch the application with the following command:
(venv) $ python hello.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader
  • The application will not recognize how to handle it if we type any other URL.
  • That will return an error code 404 to the browser.
  • That is used to error that we get when navigate to a web page that does not exist.

1 thought on “Basic Structure of Flask Application”

Leave a Comment