You are on page 1of 9

Initialization

To install Flask into the virtual environment, use the following


command:
$ pip install flask
With this command, Falsk and its dependencies are installed in the
virtual environment. You can verify that flask was installed
correctky by starting the Python interpreter and trying to import it:
$python
>>>import flask
>>>
If no errors appear, you can congratulate yourself.

All Flask applications must create an appllicationinstance. The web


server passes all requests it receives from clients to this object for
handling, using a protocol called Web server Gateway
Interface(WSGI). The application instance is an object of class
Flask, usually created as follows:
From flask import Flask
app = Flask(__name__)
The only required argument to the Flask ckass constructor is the
name of the mainmodule or package of the application. For most
application, Python’s__name__ variable is the correct value.
***The name argument that is passed to the Flask application
constructor is a source of confusion among new Flask developers.
Flask uses this argument to determine the root path of the
application so that it later can find resource files relative to location
of the application.***
There is more complex examples of application initialization, but
for simple application this is all that is needed.

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 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>
***Decorators are a standard feature of the python language; they
can modify the behavior of a function in different ways. A common
pattern is to use decorators to register functions as handlers for an
event.***
The previous example registers the function index() as the handler
for the application’s root URL. If this application were deployed on
a server associated with the www.example.com domain name,then
navigating to http://www.example.com on your browser would
trigger index() to run on the server. The return value of this
function, called the response, is what the client receives. If the
client is a web browser, the response is the document that is
displayed that is displayed to the user.
Functons like index() are called view functions. A response returned
by a view function can be a simple string with HTML content, but it
can also take more complex forms, as you will see later.
***Response strings embedded in Python code lead to code that is
difficult to maintain, and it is done here only to introduce the
concept of responses.***
If you pay attention to how some URLs for services that you use
every day are formed, you will notice that many have variable
sections. For example, the URL for your facebook profile page is
http://www.facebook.com/nae.imUam, so your username is part
of it. Flask suprts these types pf URLs using a special syntax in the
route decorator. The following example defines a route that has a
dynamic name component:
@app.route(‘/user/<name>’)
def user(name):
return ‘<h1> Hello, %s!</h1>’ % name
The portion enclosed in angle brackets is the dynamic part, so any
URLs that match the static portion will be mapped to this route.
When the view function is invoked, Flask sends the dynamic
component as an argument. In the earlier example view function,
this argument is used to generate a personalized greeting as a
response.
The dynamic components in routes are strings by default but can
also be defined with a type. For example, route/user/<int:id>
would match only URLs that have an integer in the id dynamic
segment. Flask support types int, float, and path for routes. The
path type also represents a string but does not consider slashes as
separators and instead considers them part of the dynamic
component.

SERVER STARTUP
The application instance has a run method that launches Flask’s
integrated development web server:
If __name__ == ‘__main__’:
app.run(debug=True)
The __name__ == ‘__main__’ Python idiom is used here to ensure
that the development web server is started onlu when the script is
executed directly. When the script is imported by another script, it
is assumed that the parent script will launch a different server , so
the app.run() call is skipped.
Once the server starts up, it goes into a loop that waits for requests
and services them. This loop continues until the application is
stopped, for example by hitting Ctrl- C.
There are several option argument that can be given to app.run() to
configure the mode of operation of the web server. During
development, it is convenient to enable debug mode, which among
other things activates the debugger and the reloader. This is done
by passing the argument debug set to True.
***The web server provided by Flask is not intended for production
use.***

A Complete Application
hello.py
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)
Application and Request contexts
When Flask receives a request from a client, it needs to make a few
objects available to the view functuin that will handel it. A good
example is the rewuest object, which encapsulates the HTTP
request sent by the client.
The obvious way in which Flask coukd give a view function access
to the request object is by sending it as an argument, but that
would require every single view function in the application to have
an extra argument. Things get more complicated if you consider
that the request object is not the only object that view functions
might need to access to fulfill a request.
To avoid cluttering view functions with lots of arguments that may
or may not be needed, Flask uses contexts to temporarily make
certain objects globally accessible. Thanks to contexts, view
function like the following one can be written:
from flask import request
@app.route(‘/’)
def index():
user_agent = request.header.get(‘User-Agent’)
return ‘<p>Your browser is %s</p> % user_agent
Note how in this view function request is used as if it was a global
variable . In reality, request cannot be a global variable if you
consider that in a multithreaded server the threads are working on
different requests from different clients at the same time, so each
threads needs to see a different object in request. Contexts enable
Flask to make certain variables globally accessible to a thread
without interfering with the other threads.
***A thread is the smallest sequence of instructions that can be
managed independently. It is common for a process to have
multiple active threads, sometimes sharing resources such as
memory or file handles. Multithreaded web servers start a pool of
threads and select a thread from the pool to handle each incoming
request.***
There are two contexts inFlask : the application context and the
request context.
Flask activates ( or pushes) the application and request contexts
before dispatching a request and then removes them when the
request is handled. When the application context is pushed, the
current_ app and g variables become available to thread; likewise,
when the request contextis pushed , request and session become
available as well. If any of these variables are accessed without an
active application or request context, an error is generated. The
four context variables will be revisited in later chapters in detail , so
don’t worry if you don’t understand why they are useful yet.
Request Dispatching
When the application receives a request from a client, it
needs to find what view function to invoke to service it.
For this task, Flask looks up the URL given in the request
in the application’s URL map, which contains a mapping
of URLs to the views functions that handle them. Flask
builds this map using the app.route decorators or the
equivalent non decorator version app.add_url_rule().
The HEAD, OPTIONS, GET elements shown in the URL
map are the request methods that are handled by the
route. Flask attaches methods to each route so that
different request methods that are handled by the route.
Flask attaches methods to each route so that different
request methods sent to the same URL can be handled
by different view functions. The HEAD and OPTIONS
methods are managed automatically by Flask, so in
practice it can be said that in this application the three
routes in the URL map are attached to the GET method.

Request Hooks
Sometimes it is useful to execute code before or after each request
is proceed. For example, at the start of each request it may be
necessary to create a database connection, or authenticate the
user making the request. Instead of duplicating the code that does
this in every view function, Flask gives you the option to register
common functions to be invoked before or after a request is
dispatched to a view function.
• before_first_request: Register a function to run before the first
request is handled.
• before_request: Register a function to run before each request.
• after_request: Register a function to run after each request, if no
unhandled exceptions occurred.
• teardown_request: Register a function to run after each request,
even if unhandled exceptions occurred.

You might also like