Build the first Web application using the Python Flask framework

Source: Internet
Author: User
Tags error status code passthrough
The Flask framework is a lightweight Web development framework that has gained great popularity in the Web field over the past two years. here we will look at how to use the Python Flask framework to build the first Web application. 1. initialization

In this chapter, you will learn different parts of the Flask application. At the same time, you will write and run your first Flask web application.

All Flask applications must create an application instance. Use the web Server Gateway Interface protocol to send all requests received from the client to this object for processing. This application instance is an object of the Flask class and is usually created using the following method:


from flask import Flaskapp = Flask(__name__)


The only parameter required by the Flask constructor is the main module or package of the application. For most applications, the Python _ name _ variable is the correct value you need to pass.

Note: For Flask developers, the name parameter passed to the Flask application constructor is confusing. Flask uses this parameter to determine the root directory of the application. in this way, you can find the resource file from this path.
You can see more complex application instance initialization later, but it is sufficient for simple applications.

2. routing and view functions
A client, for example, a web browser, sends requests to the web service and then sends them to the Flask application instance. The application instance needs to know the code to be run for each URL request, so it creates a URLs ing for the Python function. These operations that establish connections between URLs and functions are called routes.

The most convenient way to define a route in the Flask application is to register the decorated function as a route by displaying the app. route decorator defined on the application instance. The following example demonstrates how to declare a route using the decorator:


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


Note: decorator is a standard feature of the Python language. they can change the behavior of functions in different ways. A common mode is to use the decorator to register a function as an event handler.
In the previous example, the index () function is registered for the root URL of the application as the event handler. If the application is deployed on the server and bound to the domain name www.example.com, then entering # in your browser address bar will trigger index () to run the service. The return value of the function received by the client is called a response. If the client is a web browser, the response is the document displayed to the user.

A function similar to index () is called a View function. The response returned by the view can be a string of simple HTML content, but it can also be in a more complex form, as you will see.

Note: When the response string is embedded in Python code, the code is difficult to control. this is just a brief introduction to the concept of response. In chapter 3, you will learn the correct method to generate a response.
If you notice how the URLs of some websites you use every day are formed, you will find many variables. For example, the URL of your Facebook personal information page is #; username>, so your user name is part of it. Flask supports these types of URLs with special syntax in the route decorator. The following example defines a route with a dynamic name component:


@app.route('/user/
 
  ') def user(name): return 'Hello, %s!' % name
 


The parts enclosed in angle brackets are dynamic parts, so any URL matching static parts will be mapped to this route. When a View function is called, Flask sends a dynamic component as a parameter. In the view function in the previous example, this parameter is used to generate a personalized greeting as a response.

In routing, dynamic components are strings by default, but can be defined as other types. For example, route/user/ Match only the URLs of an integer in the id dynamic segment. Flask routes support int, float, and path. Path is also a string type, but it is not considered as a delimiter but as part of a dynamic component.

3. start the service
An application instance has a run method used to start the Flask integrated web service:


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


_ Name _ = '_ main _' is used here to ensure that the web service is started and the script is executed immediately. When a script is imported by another script, it is regarded as a parent script that starts different services, so the app. run () call will be skipped.

Once the service is started, it enters the loop waiting for the request and serving it. This loop continues until the application stops, for example, by pressing Ctrl-C.

There are several Option parameters that can be used to configure the web service operation mode for app. run. During development, you can easily enable the debug mode to activate debugger and reloader. This is done by passing debug to True.

Note: The web service provided by Flask is not used in the production environment. You will learn about web services in the production environment in chapter 17.

4. a complete application
In the previous section, you learned different parts of the Flask web application and now it is time to write one. The whole hello. py application script only combines the three parts described above into one file. The application example is 2-1.

Example hello. py: a complete Flask application


from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return 'Hello World!'if __name__ == '__main__': app.run(debug=True)


Suggestion: If you have an application cloned on GitHub, you can run git checkout 2a to switch to this version of the application.
Before running the application, make sure that the virtual environment you created is activated and Flask is installed. Open your web browser and enter #: 5000/in the address bar /. Displays the web browser connected to the application.

(venv) $ python hello.py  * Running on http://127.0.0.1:5000/ * Restarting with reloader


If you enter any other URL, the application will not know how to operate it and return error code 404 to the browser-this error will also be returned when you access a webpage that does not exist.

The enhanced version of the application shown below adds the second dynamic route. When you access this URI, you should be able to see personalized greetings.

Example hello. py: Flask application with dynamic routing


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


Suggestion: If you have an application cloned on GitHub, you can run git checkout 2b to switch to this version of the application.
Test dynamic routing to ensure that the service is running and then access http: // localhost: 5000/user/Dave. The generated application uses the dynamic parameter name to respond to a customized greeting. Try different names to see if the view function always generates a response based on the given name.

from flask import request@app.route('/')def index(): user_agent = request.headers.get('User-Agent') return '

Your browser is %s

' % user_agent


Note: In this view function, how is a request used as a global variable. In reality, a request cannot be used as a global variable. for a multi-threaded server, a thread acts on different requests of different clients at the same time. Therefore, each thread needs to see different objects in the request. Contexts allows Flask to determine accessible global variables without interfering with other threads.

Note: a thread is the smallest sequence of commands that can be managed independently. It is very common for a process to have multiple active threads, sometimes sharing memory or file handle resources. A multi-threaded web server starts a thread pool and selects a thread from the pool to process each incoming request.
Flask has two types of context: application-level context and request-level context. Table 2-1 shows the variables provided by these context.

>>> from hello import app>>> from flask import current_app>>> current_app.nameTraceback (most recent call last):...RuntimeError: working outside of the application context>>> app_ctx = app.app_context()>>> app_ctx.push()>>> current_app.name'hello'>>> app_ctx.pop()


In this example, when the application-level context is not activated but is pushed into the stack as a valid context, current_app.name reports an error. Note how to obtain an application-level context in an application instance by calling app. app_context.

5.2 request scheduling

When an application receives a request from the client, it needs to find the View function of the response to serve it. For this task, Flask searches for the requested URL in the URL ING of the application. the ing contains URLs and view functions that operate on them. Flask uses the app. route decorator or the app. add_url_rule () version of the non-decorator to establish this ING.

Check the URL ing in the Flask application. you can check the hello ing created by hello. py in Python shell. During the test, make sure that your virtual environment is active:


(venv) % python>>> from hello import app>>> app.url_mapMap([
 
   index>, 
  
   ' (HEAD, OPTIONS, GET) -> static>, 
   
    ' (HEAD, OPTIONS, GET) -> user>])
   
  
 


The headers, OPTIONS, and GET elements shown in the URL ing are request methods processed by routes. Flask connection method to each route, so that different request methods can be processed by different View functions to send to the same URL. The HEAD and OPTIONS methods are automatically managed by Flask. In fact, the three routes mapped by URL in this application are connected to the GET method. In chapter 4, you will learn how to specify different request methods for routes.

5.3 request Hooks

Sometimes it is very useful to execute code before or after each request is processed. For example, it may be necessary to create a database connection or verify user requests before starting each request. To avoid copying the code that processes these operations to every View function, Flask gives you the option to register the same function for calling before or after the request is assigned to the View function.

The request hooks is implemented by the decorator. The following are the hooks supported by four Flask:

(1) before_first_request: register a function before the first request is processed.
(2) before_request: register a function before each request to run.
(3) after_request: if no unprocessed exception occurs, register a function to run after each request.
(4) teardown_request: register a function after each request even if an unhandled exception occurs.
The common way to share data between the request hook function and the View function is to use g global context. For example, the before_request handler can load logged-on users from the database and save them in g. user. Then, when the View function is called, you can access the user from there.

The example of requesting hooks will be shown in future chapters, so don't worry,

5.4. response

When Flask calls a View function and expects its return value to respond to the request. Most responses are to send the HTML page consisting of simple strings back to the client.

However, the HTTP protocol requires more information than the string as the request response. A very important part of an HTTP response is the status code. Flask sets 200 by default to indicate that the request has been processed successfully.

When the View function needs to respond with different status codes, you can add a number code after the response text as the second return value. For example, the following view function returns a 400 error status code request:


@app.route('/')def index(): return 'Bad Request', 400


The response returned by the view function can also carry the third parameter and add a header dictionary to the HTTP response. It is rarely used, but you can see the example in chapter 14th.

In addition to one, two, or three values, the Flask View function can choose to return the response object. The make_response () function can carry one, two, or three parameters. it returns the same value as the value returned by the view function and a response object. Sometimes it is very useful to execute this conversion in the View function, and then use the method in the response object to further configure the response. The following example creates a response object and sets the cookie:


from flask import make_response@app.route('/')def index(): response = make_response('This document carries a cookie!') response.set_cookie('answer', '42') return response


There is a special type of response called redirection. This type of response does not contain page documents; it just loads a new page for the browser with a new URL. Redirection is usually used with web forms. you will learn it in Chapter 4.

Redirection is usually indicated by the 302 response status code and the redirected URL is given by the Location of the header. The redirection response can be generated by returning three values or by using the response object. However, Flask provides the redirect () function to create such a response due to its frequent usage:


from flask import redirect@app.route('/')def index(): return redirect('http://www.example.com')


Another special response with the interrupt function is used for error handling. In the following example, status code 404 is returned when the id dynamic parameter provided by the URL is not a valid user:


from flask import abort@app.route('/user/
 
  ')def get_user(id): user = load_user(id) if not user:  abort(404) return 'Hello, %s' % user.name
 


Note that termination does not mean to return the control to the function that calls it, but to return the control to the web service by throwing an exception.

6. Flask extension
Flask is extensible. It deliberately makes room for important functions, such as database and user authorization, giving you the freedom to select the package that best suits your application, or write what you want.

Many extensions have been developed in the community for various purposes. if this is not enough, you can use any Python Standard package and library. To let you know how an extension is incorporated into an application, the following section adds an extension to hello. py and adds the command line parameters of the application.

6.1. Flask-Script command line options

Flask Development, its web server supports a series of startup configuration options, but the only way to configure them is to pass parameters to app. run () in the script and call it. This is not very convenient. the ideal method is to pass configuration options through command line parameters.

Flask-Script is an extension that adds Command Line interpretation to your Flask application. It packages a set of common options and supports custom commands.

Use pip to install extensions:


(venv) $ pip install flask-script


The following shows the changes in command line Interpretation added to the hello. py application.
Example. hello. py: use Flask-Script


from flask.ext.script import Managermanager = Manager(app)# ...if __name__ == '__main__': manager.run()


Extensions designed for Flask are exposed in the flask. ext namespace. Flask-Script exports a class named Manager from flask. ext. script.

The method for initializing this extension is the same as that for many other extensions: the initialization of the main class instance is implemented by passing the application instance as a parameter to the constructor. The created object is suitable for each extension. In this example, the server is started to route through manager. run () and the command line is parsed here.

Suggestion: If you have an application cloned on GitHub, you can run git checkout 2c to switch to this version of the application.
Because of these changes, the application obtains a set of basic command line options. Run hello. py to display available information:


$ python hello.py



Usage: hello. py [-h] {shell, runserver}... positional arguments: {shell, runserver} shell runs a Python Shell in the context of the Flask application. Runserver runs the Flask development server. for example, app. run () optional arguments:-h, -- help displays the help information and exits.


The shell command is used to enable a Python shell session in the application context. You can use this session to run maintenance tasks, test tasks, or debug errors.

The runserver command starts the web service just like its name. Run python hello. py runserver to start the web service in debug mode. there are more options:


(venv) $ python hello.py runserver --helpusage: hello.py runserver [-h] [-t HOST] [-p PORT] [--threaded]       [--processes PROCESSES] [--passthrough-errors] [-d]       [-r]


Run the Flask development server, for example, app. run ()


Optional arguments:-h, -- help displays the help information and exits-t HOST, -- host HOST-p PORT, -- port PORT -- threaded -- processes PROCESSES -- passthrough-errors-d, -- no-debug-r, -- no-reload


The -- host parameter is a very useful option because it can tell the web server which network interface is listened to for client connection. By default, the web server developed by Flask listens to localhost connections, so only servers running on internal computers can receive the requests. The following command enables the web server to listen to public network interfaces. computers on other networks can connect to the server:


(venv) $ python hello.py runserver --host 0.0.0.0 * Running on http://0.0.0.0:5000/ * Restarting with reload


Now the web server should be able to access the http://a. B .c.d from any computer in the network: 5000, "a. B. c. d" is the external IP address of the computer that runs the service.

For more information about how to use the Python Flask framework to build the first Web application, see The PHP Chinese Web!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.