Python Flask Basic Application Structure














































Python Flask Basic Application Structure



flask Basic Structure

Initialization 

All Flask applications must create an application instance. The web server passes all requests it receives from clients to this object for handling, using a protocol called Web Server Gateway Interface (WSGI).

Creating inststance of class Flask

from flask import Flask app = Flask(__name__)

Flask class constructor is the name of the main module or package of the application.

Routes and View Functions

Clients such as web browsers send requests to the web server, which in turn sends them to the Flask application instance. The application instance needs to know what code needs to run for each URL requested, so it keeps a mapping of URLs to Python functions. The association between a URL and the function that handles it is called a route. The most convenient way to define a route in a Flask application is through the app.route decorator exposed by the application instance, which registers the decorated function as a route. 

The following example shows how a route is declared using this decorator:

@app.route('/')
def index():
return '<h1>Hello World!</h1>'

Server Startup 

The application instance has a run method to deploy application : 

if __name__ == '__main__':
app.run(debug=True)

The __name__ == '__main__' when the script is executed directly. 

Flask application with dynamic route

Add a second route that is dynamic. When you visit this URL, you are presented with a personalized greeting

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name
if __name__ == '__main__':
app.run(debug=True)

Output


Return page with staic route

 

Returns page with dynamic route


Comments