Use the Python Flask framework to build the first Web application, pythonflask

Source: Internet
Author: User

Use the Python Flask framework to build the first Web application, pythonflask

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 '

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 this application is deployed on the server and bound to the www.example.com domain name, then entering the http://www.example.com 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 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 profile page is a http://www.facebook.com/<username>, so your username 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/<name>') def user(name): return '

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, the route/user/<int: id> matches only the URLs with 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 '

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 http: // 127.0.0.1: 5000/in the address bar /. Displays the web browser connected to the application.

Run 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 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 '

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.

5. Request-response Loop
Now you have played a basic Flask application, and you may want to know

Related Article

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.