Python WEB framework Flask

Source: Internet
Author: User
Flask introduction Flask is a lightweight Web framework for Django. Unlike Django, Flask is built on a series of open-source software packages, the most important of which is the introduction of WS Flask.

Flask is a lightweight Web framework relative to Django.

Unlike Django's big package, Flask is built on a series of open-source software packages, the most important of which is the WSGI application development library Werkzeug and the template engine Jinja:

Policy: The werkzeug and Jinja libraries are the same as Flask databases and are developed by the pocoo team. This may reflect a strategy about the ecosystem when pocoo and Django compete. the natural extension of this strategy is that the Flask framework does not contain database components, whether it is ORM or other.

Focus: Flask is a WSGI application framework. This means that we do not need to focus on network operations during Flask Development. the Flask application Portal is a encapsulated network request package, the egress is the network response. we only need to pay attention to the processing logic in this phase.

WSGI server: Although Flask has a built-in simple WSGI server, its performance is only applicable to debugging in the development phase. The Flask website recommends a variety of WSGI servers, from multi-process to multi-thread to coroutine, which will not be covered in this course.

REST adaptability: Although Flask is the same as Django, the initial starting point is the server's dynamic web page application. However, the design of Flask makes it quite suitable for the resource-oriented REST architecture. it is a great advantage of Flask over Django in more and more mobile WEB development fields and more important single-page applications.

Hello Flask

Writing a Flask-based hello world is quite easy:

1. import the Flask class
from flask import Flask

The Flask class is the core class of the Flask framework and implements WSGI application specifications.

2. create a Flask instance
app = Flask(name)

The first parameter of the Flask constructor specifies an import name/importname. The Flask framework uses this name to locate static resources, templates, and error messages. Unless you understand it clearly, we should always use the special variable _ name.

The Flask instance is callable (with the call method) and can be directly connected to the WSGI server.

3. Register a route

@route('/')def index():    return 'Hello,Flask!'

Registering a route is to establish an association between URL rules and processing functions. The Flask framework relies on routes to distribute HTTP requests.

A function in a route is called a View function. its return value is the body content of the HTTP response.

4. connect to and start the WSGI server

Flask encapsulates a simple WSGI server for development. we can start the server running by calling run:

app.run(host='0.0.0.0',port=80)

Overview

Routing is a very important concept in the Web framework of MVC architecture and also the focus of this course.

It means finding a path in confusion. In the Flask framework, the routing means to find the corresponding processing function for the URL requested by the user.

In this course, we will mainly explain the routes in the Flask framework from the following aspects:

How do I register a route for an application? How do I specify the supported HTTP methods for a route? How to match dynamic URLs? How do I filter variable types in URLs? How do I understand access points/endpoints? How do I set static routes for applications? How can I avoid hard coding URLs pointing to other views?

Register a route

In the Flask application, routing refers to the ing between the URL requested by the user and the View function. The Flask framework matches the predefined URL rules in the routing table based on the HTTP request URL, finds the corresponding View function, and returns the execution result of the View function to the WSGI server:

It can be seen that the route table is at the core of the Flask application. The content of the route table is filled by the application developer.

Route decorator: you can use the route decorator of the Flask application instance to bind a URL rule to a view function.

For example, the following example binds the URL rule/test to the View function test:

@app.route('/test')def test():    return 'this is response'

If the application is deployed in the root directory of the host ezhost.com:

Http://pythontab.com/teset

The Flask framework calls our test () function, and the returned results are passed to the WSGI server and sent to the visitor.

Add_url_rule (): Another equivalent method is to use the add_url_route () method of the Flask application instance. The following example registers a route entry with the same region:

def test():    return 'this is response'app.add_url_route('/test',view_func=test)

In fact, the route decorator also registers routes by calling the add_url_route () method. However, it is clear that the code looks more elegant with the decorator.

Specify the HTTP method for the route

By default, Flask routes only support http get requests. You can use the methods keyword parameter to explicitly declare the HTTP methods supported by The View method when registering a route.

For example, the following example binds the URL rule/auth to The View function v_auth (). This route only supports the POST method:

@app.route('/auth',methods=['POST'])def v_auth():pass
Support for multiple HTTP methods

The type of the keyword parameter methods is list, so you can specify multiple HTTP methods at the same time.

In the following example, make the URL rule/user support both the POST method and the GET method:

@ App. route ('/user', methods = ['post', 'Get']) def v_users (): if request. method = 'get': return... # return to the user list if request. method = 'post' return... # Creating a new user

This feature makes Flask very easy to develop background services in the REST architecture, rather than limited to traditional dynamic web pages.

Match dynamic URL

Sometimes we need to map the same type of URL to the same view function for processing. for example, we need to use the same view function to display the personal files of different users. We hope that the following URLs can be distributed to the same view function:

In Flask, you can declare the variable part of the URL with a pair of parentheses as variables and declare parameters with the same name for the View function:

@app.route('/user/')def v_user(uname):    return '%s\'s Profile' % uname

In the preceding example

URL variable type filtering

For the following example, we want to share files in/var/readonly through HTTP:

/Var

/Readonly

/A.txt

/B .txt

/Repo

/C.txt

/D.txt

Simply think about the answer. We can construct URL rules/file/

@app.route('/file/')def v_file(fname):    fullname = os.path.join('/var/readonly',fname)    f = open(fullname)    cnt =  f.read()    f.close()    return cnt

Test results show that neither/file/a.txt NOR/file/B .txt is correct, but/file/repo/c.txt and/file/repo/d.txt fail.

This is because, by default, the variables in the URL rule are considered as strings that do not contain. /File/repo/c.txt cannot match URL rules/file/

You can use the built-in path converter to tell the Flask framework to change this default behavior. The path converter allows the rule to match strings that contain:

@app.route('/file/')

In Flask, the converter/converter is used to pre-process the variables extracted from the URL before calling the View function. Flask has four preset converters:

String-match a string that does not contain/, which is the default converter

Path-match the contained/string

Int-the matching is performed only when the variable in the URL is an integer and the variable is converted to an integer.

Float-match only when the variable in the URL is a floating point value and convert the variable to a floating point type

Access Point/endpoint

We have always stressed that the role of routing is to find the corresponding View function based on the request URL. This is correct, but in the Flask framework, the distribution of request tasks is not directly located from the URL requested by the user to the View function. The two are separated by an access point/endpoint.

The following code is used as an example to describe how Flask distributes requests:

@app.route('/home')def home():pass

Use two tables in Flask to maintain the route:

Url_map: maintain the ing between URL rules and endpoints.

View_functions: maintain the ending between the endpoint and the View function.

Taking the user's access to URL/home as an example, Flask will first use url_map to find the endpoint corresponding to the requested URL, that is, the access point home, and then use the view_functions table to find the View function corresponding to the access point home, the final match to the function home ():

Default access point: when we use the route modifier to register a route, the function name (name) of the decorated function is used as the access point by default. Therefore, you can see the table above, the access point in the route is home.

Custom access point: you can use the endpoint keyword parameter to change the default behavior when using the route modifier or calling the add_url_rule () method to register a route:

@app.route('/home',endpoint='whocare')def home():pass

At this time, the two route tables will become like this:

Static directory routing

When an application instance is created, Flask automatically adds a static directory route. its access point is always set to static, and the URL rule is set to/static by default, by default, the local path is set to the static subfolders in the application folder:

+ Rule + | url rule | endpoint | view_function |/static | Flask. send_static_file | + -------------------------------------------------------- + if your application directory is as follows:

/App

/Web. py

/Static

/Main.css

/Jquery. min. js

After the application is started, you can use main.css under the URL/static/main.css1_staticfile folder.

Except that the access point is fixed to static, the URL rules of the static directory and the local directory can be adjusted according to the application.

Change the default local path: you can use the keyword static_folder to change the default static folder when creating an application object. For example, if all your static files are stored in the assets directory under the application, you can create an application object as follows:

App = Flask (name, static_folder = 'asset') can also use an absolute path:

App = Flask (name, static_folder = '/var/www/static') changing the default local path does not affect the route table.

Change the default URL rule: if you do not like the static Directory URL/static, you can also use the keyword static_url_path to change the name when creating an application object.

In the following example, register the assets folder under the application as a static directory/assets:

App = Flask (name, static_folder = 'assets', static_url_path = '/asset') after the application runs, you can access the main.css file in the assets folder through URL/assets/main.css.

The route table changes:

+ Metrics + | url | endpoint | view_function |/assets | static | Flask. send_static_file | + ------------------------------------------------------------ +

Construct a URL

In a practical view, links to other views are inevitable. In the previous example of the course, we hardcoded these URL URLs in the View function as follows:

@app.route('/')def v_index():    return 'tech'@app.route('/tech') def v_tech():pass

In most cases, this hard-coded URL can work. However, if the application is attached to a sub-path of the WSGI server, such as/app1, the user access URL/tech will not succeed, in this case,/app1/tech should be accessed before it can be correctly routed to the View function v_tech ().

We should use the access point to let the Flask framework help us calculate the link URL. Simply input an access point to the url_for () function, which returns a reliable URL address:

@app.route('/')def v_index():    print url_for('v_contacts')  # /contact    return 'see console output!'@app.route('/contact')def v_contacts():pass

Add query parameters: using the keyword parameter, you can generate a query string in the constructed URL. The following call will generate/contact?

format=json@app.route('/')def v_index():    print url_for('v_contacts',format='json')    return  ''@app.route('/contact')     def v_contacts():pass

Add URL variable: if you specify the View function receiving parameter corresponding to the access point, the keyword parameter will generate the corresponding parameter URL. The following example will generate/contact/Julia? Format = html:

@app.route('/')def v_index():    print url_for('v_contact',name='Julia',format='html')    return ''@app.route('/contact/')def v_contact(name):pass

Add anchor: you can use the _ anchor keyword to add an anchor for the generated URL. The following example generates URL/contact # part2

@app.route('/')def v_index():    print url_for('v_contacts',_anchor='part2')@app.route('/contact')def v_contacts():pass

External URL: by default, url_for () generates a site URL. you can set the keyword parameter _ external to True to generate an external URL containing the site address. The following example generates URLhttp ://

@app.route('/')def v_index():    print url_for('v_contacts',_external=True)@app.route('/contact')def v_contacts():pass

The above is a detailed description of the Python development WEB framework Flask. For more information, see other related articles in the first PHP community!

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.