Python Super Star Web frame flask

Source: Internet
Author: User
Flask Introduction

Flask is a lightweight web framework relative to Django.

Unlike Django embracing, flask is built on a series of open-source packages, the most important of which is the WSGI application Development Library Werkzeug and template engine Jinja:

Strategy: Werkzeug and Jinja The two libraries, like Flask, were developed by the Pocoo team. This may reflect a strategy for Pocoo to compete with Django, a natural extension of which is that the Flask framework contains no database-related artifacts, whether ORM or otherwise.

Focus: Flask is a WSGI application framework, which means that we do not need to pay attention to the operation of the network in flask development, the entrance of flask application is the encapsulated network request packet, the export is the network response, we only need to pay attention to the processing logic in this phase.

WSGI Server: Flask Although the built-in simple WSGI server, its performance is only suitable for the development period of debugging. Flask website recommended a variety of WSGI server, the implementation of the way from multi-process to multi-threaded to the association, this choice we will not be involved in this course.

Rest adaptability: Although flask and Django are the same, the initial starting point is the Dynamic Web application on the server side. But Flask's design makes it quite suitable for resource-oriented rest architectures, which is a considerable advantage of flask versus Django in the increasingly mobile and single-page application of the increasingly important web development landscape.

Hello Flask

Writing a flask-based Hello World is fairly easy:

1. Import Flask Class

From flask import Flask

The Flask class is the core class of the Flask framework, which implements the WSGI application specification.

2. Create Flask Instances

App = Flask (__name__)

The first parameter of the Flask constructor specifies an introduction named/importname. The FLASK framework uses this name to locate static resources, templates, and error messages. Unless you clearly understand its role, usually we should always use special variable _name.

The Flask instance is callable (with the Call method), which can be directly docked to the WSGI server.

3. Registered Routing

@route ('/') def index ():    return ' hello,flask! '

Registering a route is the association between a URL rule and a handler function. The Flask framework relies on routing to complete the distribution of HTTP requests.

A function in a route is called a view function whose return value will be the body content of the HTTP response.

4, docking and start Wsgi server

Flask encapsulates a simple development with a WSGI server that we can run by calling run () to start the server:

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

Overview

Routing is a fairly important concept in the web framework of the MVC architecture and is the focus of this lesson.

As implies means that routing is the meaning of finding a way in confusion. In the flask framework, the route represents the URL of the user request to find the corresponding handler function.

In this lesson, we will explain the routes in the flask framework mainly from the following aspects:

How do I register a route for an app? How do I specify the HTTP methods it supports for routing? How do i match a dynamic URL? How do I filter the type of variables in a URL? How to understand access point/endpoint? How do I set a static route for my app? How do I avoid hard-coded URLs that point to other views?

Registering routes

In flask applications, routing refers to the mapping between a user-requested URL and a view function. The Flask framework matches the predefined URL rules in the routing table based on the URL of the HTTP request, finds the corresponding view function, and returns the result of the view function to the WSGI server:

The Visible routing table is at a very central location in the flask application. The content of the routing table is populated by the app developer.

Route Adorner: You can bind a URL rule to a view function by using the route adorner of the Flask application instance.

For example, the following example binds a 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, then when the user accesses:

Http://pythontab.com/teset

The FLASK framework calls our test () function, and its return results are passed to the WSGI server for sending to the visitor.

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

def test ():    return ' This is response ' App.add_url_route ('/test ', view_func=test)

In fact, the route decorator interior is also implemented by calling the Add_url_route () method for routing registrations. But obviously, using adorners makes the code look more elegant.

To specify an HTTP method for a route

By default, flask routing only supports get requests for HTTP. You can use the Methods keyword parameter to explicitly declare the HTTP methods supported by the view method when you register the route.

For example, the following example binds the URL rule/auth to the View function V_auth (), which only supports the Post method:

@app. Route ('/auth ', methods=[' POST ') def v_auth ():p

Specifying multiple HTTP method support

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

In the following example, the URL rule/user supports both the Post method and the Get method:

@app. Route ('/user ', methods=[' POST ', ' get ') def v_users ():    if Request.method = = ' Get ':        return ... # Back to user list    if Request.method = = ' POST '        return ... #创建新用户

This feature makes flask very easy to develop back-end services for rest architectures, rather than just traditional dynamic web pages.

Match dynamic URL

Sometimes we need to map the same type of URLs to the same view function, for example, using the same view function to display the profiles of different users. We want the following URLs to be distributed to the same view function:

In flask, you can use a pair of parentheses <> declare the variable part of the URL as a variable and declare a parameter with the same name for the view function:

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

In the example above, the representation in the URL rule is mutable, and flask will fetch the contents of this part of the URL requested by the user and call it as the uname parameter of the View function V_user ().

URL variable type filtering

Consider the following example, where we want to share files in the/var/readonly folder via http:

/var

/readonly

/a.txt

/b.txt

/repo

/c.txt

/d.txt

Think about it for a second. We can construct the URL rule/file/and then directly read the file contents back to the user. Register the following routes:

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

The test results show that/file/a.txt and/file/b.txt are fine, but/file/repo/c.txt and/file/repo/d.txt fail.

This is because, by default, a variable in a URL rule is treated as a string that does not contain/. /file/repo/c.txt is no way to 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 the containing/string:

@app. Route ('/file/')

In Flask, the converter/converter is used to preprocess the variables extracted from the URL, which occurs before the view function is called. The flask has four types of converters preset:

String-matches the strings not contained in/, which is the default converter

Path-matches the contained/string

INT-matches only if the variable in the URL is an integer value and converts the variable to an integral type

Float-matches only if the variable in the URL is a floating-point value and converts the variable to float

Access Point/endpoint

We have always emphasized that the role of routing is to find the corresponding view function according to the requested URL. That's true, but in the flask framework, the dispatch of a request task is not directly from the URL of the user request to the view function, which is separated by an access point/endpoint.

Take the following code, for example, to see how flask implements the distribution of the request:

@app. Route ('/home ') def home ():p

Use two tables to maintain routing inside flask:

Url_map: Maintaining mappings for URL rules and endpoint

View_functions: Maintains mappings for endpoint and view functions.

As an example of user access to Url/home, flask will first use Url_map to find the corresponding endpoint of the requested URL, that is, the access point home, and then use the View_functions table to find the home access point corresponding to the view function, Final match to function home ():

Default access point: When we use the route adorner to register a route, the function name (name) of the decorated function is used as the access point by default, so you see that the access point in the route is home in the table above.

Custom Access points: You can use the Endpoint keyword parameter to change this default behavior when you use the route adorner or call the Add_url_rule () method to register a route:

1

2

@app. Route (' home ', endpoint= ' Whocare ')

def home ():p

The two routing tables at this point will become:

Static directory Routing

When you create an app instance, Flask automatically adds a static directory route whose access points are always set to Static,url rules are set to/static by default and the local path is set to the static subfolder under the App folder by default:

+------------------------------------------------------------+ | URL Rule | Endpoint | view_function | | /static | static | Flask.send_static_file | +------------------------------------------------------------+ If your app directory is as follows:

/app

/web.py

/static

/main.css

/jquery.min.js

After you launch the app, you can access the MAIN.CSS under the static folder via Url/static/main.css.

In addition to the access point being pinned to static, both the URL rules for the static directory and the local directory can be adjusted according to the application situation.

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

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

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

Change the default URL rule: If you don't like static directory Url/static, you can also use the keyword argument static_url_path to change the name when you create an App object.

In the following example, the Assets folder under the app is registered as a static directory/assets:

App = Flask (name,static_folder= ' assets ', static_url_path= '/assets ') when the app is running, you can access the Url/assets/main.css folder by assets Main.css file now.

At this point the routing table changes to:

+------------------------------------------------------------+ | URL | Endpoint | view_function | | /assets | static | Flask.send_static_file | +------------------------------------------------------------+

Construct URL

In a practical view, there are inevitably links to other views. In the previous lesson example, we hardcoded these link URLs in view functions:

@app. Route ('/') def v_index ():    return ' tech ' @app. Route ('/tech ') def V_tech ():p

In most cases, this hard-coded URL can work. However, if the application is hung in a sub-path of the WSGI server, such as:/app1, then the user access Url/tech will not be successful, then should access the/app1/tech can be correctly routed to the View function V_tech ().

We should use the access point to let the Flask framework calculate the link URL for us. Simply pass in an access point to the Url_for () function, and it 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 ():p

Add query parameters: Use the keyword parameter to 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 ():p

Add URL variable: If the View function that corresponds to the specified access point receives the parameter, the keyword parameter generates the corresponding parameter URL. The following example generates/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):p

Add anchor points: Use the _anchor keyword to add an anchor point to the generated URL. The following example generates a Url/contact#part2

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

External URL: By default, Url_for () generates an in-station URL, and you can set the keyword parameter _external to true to generate an external URL that contains the site address. The following example generates URLHTTP:///CONTACTS:

@app. Route ('/') def v_index ():    print url_for (' v_contacts ', _external=true) @app. Route ('/contact ') def v_contacts ( ):p
  • 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.