Flask Learning (ii) routing

Source: Internet
Author: User

Flask Routing

Before explaining what a Flask route is, elaborate on the code for the smallest application of Flask "Hello World".

Flask "Hello World"
1  fromFlaskImportFlask2 3App = Flask (__name__)4 5@app. Route ('/')6 defHello ():7     return 'Hello World'8 9 if __name__='__main__':TenApp.run ()

Parse the above code:

1. First, we imported the class Flask. The instantiation of this class will be our WSGI application. The first parameter is the name of the application module. If you are using a single module (as in this example), the first parameter should use __NAME__. The name will be different (' __main__ ' corresponds to the name of the actual import), depending on if it is started as a standalone application or imported as a module.

2. Next, we create an instance of the class. The name of the module or package that we pass to it. So Flask will know where to look for templates, static files and so on.
3. We then use the adorner route () to tell Flask which URL will trigger our function. This is the route, which will be studied in detail after the blog post.
4. After that, define a function that is used to generate URLs for specific functions and return the information we want to display on the user's browser.
5. Finally, we use the function run () to start the local server to run our application. if __name__ = = ' __main__ ': Make sure that the server runs only when the script is executed directly by the Python interpreter, not when it is imported as a module.

Visible outside the server:

The server is currently only native localhost access because, by default, a user in the app can execute any Python code on your computer.

If you turn off Debug or trust a user on your network, you can make your server available externally, as long as the call to change the method run () is as follows:

app.run (host='0.0.0.0') This allows your operating system to listen for all public IPs.

  

Debug mode

There are two ways to turn on mode: Add statement, set flag on Application object: app.debug = True

or pass in as a parameter to run: app.run (debug=true) is passed in as a parameter to run .

The debugging mode has the security hidden danger, must not use in the production environment, the reference is as follows:

Attention

Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on pro Duction servers), it still allows the execution of arbitrary code. This makes it a major security risk and therefore it must never is used on production machines.

Open Debug mode, if the page error, the example shows such as:

Flask Routing

The so-called route, which is URL binding, is route() used to bind a function to a URL,

1  fromFlaskImportFlask2App = Flask (__name__)3 4@app. Route ('/')5 defindexpage ():6     return 'Index Page'7     8@app. Route ('/flask')9 defflaskpage ():Ten     return 'Flask Page' One  A if __name__=='__main__': -App.run ()

As in the example above, bind the "/" URL to the Indexpage () function and bind the "/flask" URL to the Flaskpage () function.

HTTP request emulation Tool: This way you need to use the HTTP request tool to view, Chrome available plugins Postman;firefox available HttpRequest. The specific use of this side is not introduced, very simple.

After running, request the URL and

    

The above is only the simplest URL construct, you can construct a specific part of the URL dynamically, or you can attach multiple rules on a function.

Variable Rules

Add a variable part to the URL and mark some specific fields as <variable_name>. These specific fields are passed in as parameters to your function.

Of course, you can also specify an optional converter to pass rule <converter:variable_name>.

Let's look at the following example (the example omits the context code):

@app. Route ("/query_user")def  Query_user ():    = Request.args.get ("ID")    return"query User: {0} ". Format (ID)

That is, a simple URL to add a variable, run after the requested URL takes parameters

The following converters exist: The sample code is as follows:

@app. Route ('/userid/<int:user_id>')def  Show_userid (user_ ID):    #  show the user_id, the ID is an  integer    return'  User ID: {0}'. Format (user_id)

The URL must pass an integer after "/userid/", after running as

HTTP Method

By default, the URL route created is the Get method, which can be changed by providing the methods parameter to the route () adorner, related to the HTTP protocol, and Google related documents.

@app. Route ("/postuser", methods=["POST"]def  Hello_user ():    return"Post user"

The above example is the route of a post method, the direct access after the run will be reported 405, because the request should be Post, this way using the FireFox plugin httprequester to simulate

      

Change to Post mode,

The most common way is Post and Get, the other is Delete, Put, etc., please read the relevant documents.

   

Request

The request from flask Import flask needs to be introduced for the value of the request parameter, as shown in the following example:

@app. Route ("/query_user")def  Query_user ():    = Request.args.get ("ID")    return"query User: {0} ". Format (ID)

Is there a familiar? Then look at the multi-parameter, the following example:

@app. Route ("/query_page")def  query_page ():    PageID    = Request.args.get ("pageid")    num       = request.args.get (  "num")    return"query page: {0} and {1} ". Format (pageid,num)

      

URL Build

The URL is generated backwards based on the function name. You can use the function url_for () to construct a URL for a specific function. It can accept the function name as the first parameter, as well as some keyword parameters, each of which corresponds to the variable portion of the URL rule. The unknown variable part is inserted into the URL as a query parameter.

Need to introduce url_for, from flask Import flask, request, url_for routing is built as a previous example (this uses the Test_request_cont Ext () method, which is explained below. This method tells Flask to behave as if it were processing a request. )

@app. Route ('/')defindexpage ():return 'Index Page'@app. Route ("/query_user")defQuery_user (): ID= Request.args.get ("ID")    return "Query User: {0}". Format (ID) with App.test_request_context ():PrintUrl_for ('Indexpage')    PrintUrl_for ('Query_user', id=100)

      


The construction of URLs is more commonly used in real projects, why would you like to build URLs instead of hard coding in templates? Here are three good reasons:

· Reverse builds are usually more descriptive than hard coding. More importantly, it allows you to modify URLs at once instead of looking for URL changes everywhere.
· Building URLs can handle special characters and Unicode escapes explicitly, so you don't have to deal with them.
· If your app is not in the URL root directory (for example, in/myapplication and not/), url_for () will handle it appropriately for you.

Flask Learning (ii) routing

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.