Use the Python flask framework to build your first web App

Source: Internet
Author: User
Tags error status code passthrough virtual environment
1. Initialize

In this chapter, you will learn the 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 instance of the application. Use the Web Server Gateway Interface protocol to pass all requests received from the client to this object processing. This application instance is an object of the Flask class and is typically created in the following way:


From flask Import Flaskapp = Flask (__name__)


The only parameter required by the Flask class constructor is the application's main module or package. For most applications, Python's __name__ variable is the correct value that you need to pass.

Note: For flask developers, the name parameter passed to the Flask application constructor is relatively easy to confuse. Flask uses this parameter to determine the root of the application so that the resource file can be found relative to the path later.
You can see more complex application instance initialization later, but that's enough for a simple application.

2. Routing and view functions
Clients, such as Web browsers, send requests to Web services and send them to the Flask application instance. The application instance needs to know what code to run for each URL request, so it creates a map of the URLs for the Python function. These operations that establish a link between a URL and a function are called routes.

The most convenient way to define a route in a flask program is to register the decorated function as a route by displaying the App.route adorner defined on the application instance. The following example shows how to use adorners to declare a route:


@app. Route ('/') def index (): Return ' 


Note: adorners are a standard feature of the Python language, and they can change the behavior of functions in different ways. A common pattern is to use adorners to register functions as an event handler.
In the previous example, register the index () function as the handler for the event to the root URL of the application. If the application is deployed on the server and binds the www.example.com domain name, then entering http://www.php.cn/in your browser's 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 that is 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 a more complex form of the city, as you will see.

Note: The response string embedded in the Python code causes the code to be difficult to control, and this is just the concept of a response. You'll learn the right way to generate responses in chapter three.
If you notice how some of the website URLs you use every day are formed, you will find that many have variables. For example, the URL of your Facebook profile page is http://www.php.cn/;username>, so your username is part of it. Flask uses special syntax to support these types of URLs in the route adorner. The following example defines a route that has a dynamic name component:


@app. Route ('/user/<name> ') def user (name): Return ' 


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

In routing, a dynamic component defaults to a string, but can be defined as a different type. For example, Route/user/<int:id> only matches URLs that have an integer in the ID dynamic segment. Flask routes support int, float, and path. Path is also a string type, but does not consider a slash to be a delimiter, but rather as part of a dynamic component.

3. Service Start-up
The application instance has a run method 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 when the script is executed immediately. When the script is imported by another script, it is considered that the parent script will start a different service, so the App.run () call will be skipped.

Once the service is started, it goes into the loop waiting for the request and serves it. This loop lasts until the application stops, for example by pressing CTRL-C.

There are several option parameters to configure the operating mode of the Web service for App.run (). During development, it is convenient to turn on debug mode and activate Debugger and Reloader. This is accomplished by passing debug to True.

Note: Web services provided by flask are not used in production environments. You will learn the Web services of the production environment in chapter 17.

4. A complete application
In the previous section, you learned the different parts of the Flask Web application, and now it's time to write one. The entire hello.py application script simply combines the three sections described earlier in one file. The application example 2-1 shows.

Example hello.py: A complete flask application


From flask Import Flaskapp = Flask (__name__) @app. Route ('/') def index (): Return ' 


Recommendation: If you have cloned apps on GitHub, you can now run git checkout 2a to switch to this version of the app.
Before running the application, make sure that the virtual environment you created earlier is already active and has flask installed. Now open your Web browser and enter http://www.php.cn/:5000/in the Address bar. Displays the Web browser after connecting to the application.

Then enter the following command to start 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 manipulate it and will return an error code 404 to the browser-when you access a nonexistent Web page you will get the error.

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

Example hello.py: Flask application with Dynamic routing


From flask Import Flaskapp = Flask (__name__) @app. Route ('/') def index (): Return ' 


Recommendation: If you have cloned apps on GitHub, you can now run git checkout 2b to switch to this version of the app.
Test dynamic routing to ensure that the service is running and then access Http://localhost:5000/user/Dave. The generated application responds to a custom greeting with a dynamic parameter name. Try a different name and see if the view function always generates a response based on the given name.


5.1. Application context and request context

When Flask receives a request from the client, it needs to provide several available objects for the view function to handle. The request object is a good example that encapsulates the HTTP request sent by the client.

The best way for the Flask view function to access the request object is to send it as a parameter, but this requires that each single view function has an additional parameter in the application. Consider that if the request object is not the only one where the view function needs to access the object that completes the requests, things will become more complicated.

To avoid confusing the view functions with parameters that might or may not be required, flask uses the context to temporarily determine the accessible global objects. Also thanks to the context, view functions can be written as follows:


From flask import request@app.route ('/') def index (): User_agent = Request.headers.get (' user-agent ') return ' <p> Your browser is%s</p> '% user_agent


Notice how the request is used as a global variable in this view function. In reality, request is not a global variable, and if it is a multithreaded server, the same time thread acts on different requests from different clients, so each thread needs to see the different objects in the request. Contexts enables flask to determine which global variables are accessible without interfering with other threads.

Note: threads are the smallest sequence of instructions that can be managed independently. It is very common to have multiple active threads in a process, sometimes to share memory or file handle resources. A multithreaded Web server initiates a thread pool and selects one of the threads from the pool to handle 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.


Flask activates (or presses stacks) application-level context and request-level context before dispatching the request, and then deletes them when the request is processed. When the application context is pressed into the stack, the Current_app and g variables in the thread become available; Similarly, when the request-level context is pushed into the stack, the requests and session variables become available as well. If any of these variables are not accessed by an activated application-level or request-level context, an error is generated. The four context variables are discussed in more detail in the following chapters, so don't worry that you don't understand their usefulness.

The following Python shell session demonstrates how application-level context works:


>>> 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 as a valid context is pressed into the stack, current_app.name error. Note how an application-level context in an application instance is obtained by calling App.app_context ().

5.2. Request Dispatch

When an application receives a request from the client, it needs to find the response to the view function for the service. For this task, flask looks for the requested URL in the application's URL map, which contains the URLs and the view functions that manipulate them. Flask This mapping by app.route adorner or non-adorner version app.add_url_rule ().

Take a look at what URL mappings are in the Flask application, and you can check the mappings created by hello.py in the Python shell. In the test, make sure your virtual environment is active:


(venv)% python>>> from Hello import app>>> app.url_mapmap ([<rule '/' (HEAD, OPTIONS, GET), Inde X>, <rule '/static/<filename> ' (head, OPTIONS, GET), Static>, <rule '/user/<name> ' (head, OP tions, GET), User>])


The head, OPTIONS, and get elements shown in the URL map are the request method, which is handled by the route. Flask connection methods to each route, so that different request methods are sent to the same URL can be handled by different view functions. The head and options methods are automatically managed by flask, so you can actually say that the three routes in the URL map in this application are connected to the Get method. In the fourth chapter you will learn to specify different request methods for routing.

5.3. Request Hooks

Sometimes it is useful to execute code before or after each request processing. For example, it might be necessary to create a database connection before starting each request, or to validate a user request. To avoid copying the code that handles these operations into each view function, Flask gives you the option to register the same function to invoke before or after the request is assigned to the view function.

The request hooks is implemented by the adorner. Here are the four flask supported hooks:

(1) Before_first_request: Registers a function to run before the first request is processed.
(2) Before_request: Registers a function to run before each request.
(3) After_request: If no unhandled exception occurs, register a function to run after each request.
(4) Teardown_request: Registers a function to run after each request, even if an unhandled exception occurs.
The usual way to share data between request hook functions and view functions is to use the G global context. For example, the Before_request handler can load a logged-in user from a database and save it in G.user. After that, when the view function is called, the user can be accessed from that.

Ask for Hooks's example to be shown in future chapters, so don't worry,

5.4. Response

When flask invokes a view function and expects its return value to respond to the request. Most responses are sent back to the client by sending an HTML page consisting of a simple string.

But the HTTP protocol requires more information than a string to respond as requested. A very important part of an HTTP response is the status code, flask The default setting 200来 indicates that the request has been successfully processed.

When a view function needs to respond with a different status code, you can add a numeric code to 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 ' 


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

In addition to returning a tuple of one, two, or three values, the Flask view function can optionally return a response object. The Make_response () function can carry one, two, or three parameters, the same as the value returned by the View function, and returns a response object. It is sometimes useful to perform this transformation in a view function, and then use the methods in the response object to further configure the response. The following example creates a response object and sets a cookie:


From flask import make_response@app.route ('/') def index (): Response = make_response (' 


There is a special kind of response called redirection. This type of response does not include a page document; it simply gives the browser a new URL to load the new page. Redirects are usually used in a single web table, and you will learn in chapter fourth.

Redirects are usually indicated by a 302 response status code and the redirected URL is given by the location of the header. The redirect response can be generated using a return of three values or by a response object, but given its frequent use, flask provides the redirect () function to create such a response:


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


Another special response with interrupt functionality is used for error handling. The following example returns a status code of 404 when the URL gives the ID of a dynamic parameter that is not a legitimate user:


From flask import abort@app.route ('/user/<id> ') def get_user (id): User = Load_user (ID) if not User:  abort (404) r Eturn ' 


Note that termination does not refer to returning control to the function that called it, but to returning control to the Web service by throwing an exception.

6. Flask Extension
The flask is extensible. It intentionally frees up important features, such as database and user authorization, to give you the freedom to choose the package that best suits your application, or to write a desired one.

The community has developed a very wide range of extensions for a variety of purposes, and if that's 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, adding the command-line arguments to the application.

6.1. Flask-script Command Line Options

Flask Development, its Web server supports a range of boot configuration options, but the only way to configure them is to pass parameters to App.run () and call them in the script. This is not very convenient, the ideal way is to pass configuration options through command-line arguments.

Flask-script is an extension that adds a command-line explanation to your Flask application. It packs a common set of options and also supports custom commands.

To install an extension using PIP:


(venv) $ pip Install Flask-script


The following shows the changes in adding command-line interpretations to the hello.py application.
Example. hello.py: Using Flask-script


From flask.ext.script Import Managermanager = Manager (APP) # ... if __name__ = = ' __main__ ': Manager.run ()


Extensions developed specifically for flask are exposed under the Flask.ext namespace. Flask-script export a class named manager from the Flask.ext.script.

The method of initializing this extension is the same as many other extensions: the initialization of the main class instance is accomplished by passing the application instance as a parameter to the constructor. The objects created are appropriate for each extension. In this example, the server starts routing through Manager.run (), and the command line is parsed here.

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


$ python hello.py



usage:hello.py [-h] {shell, runserver} ... positional arguments: {shell, runserver} Shell   Runs a python Shell inside the flask application context. Runserver  Run the Flask development Server, for example: App.run () Optional arguments:-H,--help  displays this help message and exits


Shell commands are used to start a Python shell session in the context of an application. You can use this session to run maintenance tasks, or test, or debug errors.

The Runserver command, just like its name, starts the Web service. Run Python hello.py runserver start the Web service in debug mode with 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 this help message 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 tells the Web server which network interface The client connection is listening to. By default, the Web server developed by flask listens for localhost connections, so only servers that are running from the internal computer can receive it. The following command causes the Web server to listen on the public interface, and the computer on the other network can connect:


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


The Web server should now be able to access http://a.b.c.d:5000 from any computer on the network, and "A.B.C.D" is the external IP address of the computer that is running the service.

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.