Flask view of the routing system and the function (a)

 01- Introduction

 Flask is a Web development framework for micro Python implementation, but also has strong expansion capability.

02- The first flask procedure

# 初始化

from flask import Flask, url_for, views
app = Flask(__name__)

Flask class constructor must specify only one parameter, i.e. the application name of the primary module or package. In most applications, Python's __name__ variable is the value you want.

Copy the code
from flask import Flask 

create # flask object, passing parameters into __name__ 
App = the Flask (__ name__) 


# url and view mapping 
@ app.route ( '/') 
DEF hello_world (): 
    '! the Hello World' return 


IF __name__ == '__main__': 
    app.run () may change the port number # run (port = 5500)
Copy the code

03- Setting debug mode

Copy the code
Import the Flask Flask from 
Import config 
create a Flask # objects, __name__ parameters passed into the 
app = Flask (__ name__) 
# app.debug = True # second 
# app.config.update (DEBUG = True) # The third 
app .config.from_object (config) # fourth 

#url and view mapping 
@ app.route ( '/') 
DEF hello_world (): 
    Print ( 'helloworkl') 
    return '! the Hello World' 

IF __name__ == '__main__': 
    # app.run (debug = True) # The first 
    app.run ()
Copy the code

04- Profile

 New config.py

DEBUG =True

Two kinds of main program of reference:

Copy the code
# The first: Recommended Use 
Import config 
app.config.from_object (config)   

# second: 
app.config.from_pyfile ( 'config.py')
Copy the code

05-url parameter passing mode

Copy the code
Import the Flask flask from, Request 

# create flask object, passing parameters into __name__ 
App = the Flask (__ name__) 


# normal transmission parameters manner 127.0.0.1:5000/p/1 
@ app.route ( '/ P / <ID> / ') 
DEF article_detail (the above mentioned id): 
    return' you access the article published on% s'% the above mentioned id 


"" " 
specify the parameter type 
has the following types: 
    String: the default data type 
    int: accepting plastic 
    float: float 
    path : and a string of similar, but accepted slash 
    any: You can specify multiple paths 
    uuid: only accept uuid string 
"" " 


# any: 127.0.0.1:5000/blog/id 127.0.0.1:5000/user/id 
@app .route ( '/ <the any (blog, User): URL_path> / <ID>') 
DEF Detail (URL_path, ID): 
    IF URL_path == 'blog': 
        return 'blog Information% s'ID% 
    the else: 
        return 'User Information% s'% id


Path #: 127.0.0.1:5000/article/python/1/ 
@ app.route ( '/ Article This article was / <path: Test> /') 
DEF test_article (Test): 
    return 'test_article: {}'. The format (Test) 


# acquisition parameters 127.0.0.1:5000/tieba/?wd=python 
@ app.route ( '/ Tieba /') 
DEF Tieba (): 
    WD = request.args.get ( 'WD') 
    return 'parameter is acquired S% '% WD 


IF the __name__ ==' __main__ ': 
    app.run ()
Copy the code

06-url_for: implementation creates url, just generate a url

url If you want to generate a css-style static files requires the use of url_for ( 'static', filename = 'style.css') to create the corresponding url.

View url_for:

Copy the code
# 1. parsed view illustrating function url 

from the Flask Flask Import, the url_for 

@ app.route ( '/') 
DEF the hello_world (): 
    # Inside the url_for: is a view of a first function, the second parameter is the url required 
    return url_for ( 'my_list', Page = 2)    

@ app.route ( '/ List / <Page> /') 
DEF my_list (Page): 
    return 'my_list' 

access 127.0.0.1:5000/, results: / List / 2 / 

# 2. url_for many parameters which will be used as search characters 

@ app.route ( '/') 
DEF the hello_world (): 
    return the url_for ( 'my_list', Page = 2, COUNT = 2)    

@ app.route ( '/ List / < Page> / ') 
DEF my_list (Page): 
    return' my_list ' 

access 127.0.0.1:5000/, the results:? / list / 2 / count = 2
Copy the code

Template url_for:

Template url_forand view functions are url_forsimilar, but also passing the name of the view function, you can pass parameters. When used, it is necessary url_forto add a both sides{{ url_for('func_name'),ref='/',id='1'}}

07-Response

Copy the code
View of the function may return type: 
    1 can return a string, the string returned by this fact, the underlying string into a package 'Response' objects 
    2 can be returned tuples form (body response status code, the head information), and returns the tuple fact underlying the string into a package 'Response' objects 
    3. Response to return its subclasses 

implement a custom Response object: 
    1. inherits from, 'Response' class 
    2. implement the method of 'force_type is' 
    3. specify 'app.response_class' to 'Response' for your custom objects 
    4. If the view function returns the data, not a string, a tuple nor nor Response object, it will return the value pass 'force_type', then 'force_type' the return value to the distal end
Copy the code
Copy the code
from Flask Import the Flask, the url_for, the Response, jsonify 

App = the Flask (__ name__) 

class jsonResponse (the Response): 

    @classmethod 
    DEF force_type is (CLS, Response, Environ = None): 
        '' ' 
        This method only view function returns non-character, non-ancestral , non-Response object will be called 
        : the Response param: 
        : param Environ: 
        : return: 
        '' ' 
        # dictionary to convert json 
        IF isinstance (the Response, dict): 
            # jsonify the conversion dictionary into json objects, the object will be packaged into a Response object 
            Response = jsonify (Response) 
        return Super (jsonResponse, CLS) .force_type (Response, Environ) 

app.response_class = jsonResponse 


@ app.route ( '/') 
DEF the hello_world ():
    return 'the Hello world'

app.route @ ( '/ List1 /') 
DEF List1 (): 
    return the Response ( 'List1') # legal object, the direct return 

@ app.route ( '/ list3 /') 
DEF list3 (): 
    return { 'username' : 'derek', 'age' : 18} # non-return character, non-ancestral, non Response object, the method of performing force_type 

IF the __name__ == '__main__': 

    app.run (Debug = True)
Copy the code

08-add_url_rule:

Copy the code
Import the Flask Flask from, the render_template, the url_for 

App = the Flask (__ name__) 
app.config.update ({ 
    'the DEBUG': True, 
   # configured to automatically load a template file, the debug mode is automatically turned 'TEMPLATES_AUTO_RELOAD': True }) @app. route ( '/', endpoint = 'index') DEF the hello_world (): Print (the url_for ( "derek_list")) # found by the corresponding endpoint URL / List / return the render_template ( 'index.html') DEF my_list (): return "list page" # three parameter # 1.url # 2. to play url aliases, if there is no endpoint specified, the default name to use as the endpoint view function value # 3 view function app.add_url_rule ( '/ list / ', Endpoint =' derek_list ', view_func = my_list) with app.test_request_context (): print(url_for('index')) # / if __name__ == '__main__': app.run()
Copy the code

09-render_template: render template file

from flask import Flask, render_template, url_for

return render_template('index.html')

10-send_from_directory: mainly used for downloading files

Copy the code
from flask import Flask
from flask import g
from flask import send_from_directory
from flask import url_for
import os.path
 
app = Flask(__name__)
dirpath = os.path.join(app.root_path,'upload')
@app.route("/download/<path:filename>")
def downloader(filename):
    return send_from_directory(dirpath,filename,as_attachment=True)
Copy the code

 11-static_url_path和static_folder

 static_url_path used mainly to change the path url, static files on the following static, so normally url is static / filename, but can be changed by this url static_url_path.

 static_folder is mainly used to change the url of the directory, the default is static, static files directory can be changed by this variable.

Copy the code
from flask import Flask
from flask import g
from flask import send_from_directory
from flask import url_for
import os.path
 
app = Flask(__name__,static_url_path="/test")
 
@app.route("/")
def static_create():
    return url_for('static',filename='style.css')
Copy the code

12-Request Object

Copy the code
Flask Request indicating the request object is the current request, the request context generally called variable (global variable as will be appreciated, in any view can be accessed). Common attributes are: 

  args: the query string in the url. Essentially key-value pairs, followed, used between a plurality of key-value pairs "&" is connected; "?" 

  Form: data request form the url. Is a key-value pairs, submit data post method is generally used 

  cookies: cookie information in the request. Key-value pairs generated by the server, sending the value to the client and saved to highlight the later! 

  files: uploaded files
Copy the code

12- Class View

1. inherited views.VIew. 
2. The need to implement 'dispatch_request' method, over the subsequent requests will perform this method, as the return value of the function corresponding to the view, the object must return 'Response' or subclass, or a string, or tuples. 
3. Mapping must be done by the view url app.add_url_role (url_rule, view_func).
Copy the code
from flask import Flask, url_for, views 
create a Flask # object, passing parameters into __name__ 
App = Flask (__ name__) 

app.config.update ({ 
    'the DEBUG': True, 
    'TEMPLATES_AUTO_RELOAD': True, 
}) 


class the ListView ( views.View): 
    DEF dispatch_request (Self): 
        return "my list" 


# 1.ListView.as_view ( 'list') which must pass a parameter 'name', from the individual to view_func name, in fact dispatch_request function 
# 2.endpoint may not be specified, the default alias used view_func (value of the name parameter) 
app.add_url_rule ( '/ List /', Endpoint = 'List', view_func ListView.as_view = ( 'List')) 


# URL and view map 
@ app.route ( '/') 
DEF hello_world (): 
    return 'the Hello World!' 


IF __name__ == '__main__':
    app.run(port=5555)
Copy the code

13- through class inheritance to achieve a plurality of view data return json

Copy the code
from flask import Flask,url_for,views,jsonify

app = Flask(__name__)
app.config.update({
    'DEBUG':True,
    'TEMPLATES_AUTO_RELOAD':True
})

# 父类,把数据转换成json格式
class JsonView(views.View):
    def get_data(self):
        raise NotImplementedError

    def dispatch_request(self):
        return jsonify(self.get_data())

# 子类只需要写get_data方法
class ListView(JsonView):
    def get_data(self):
        return {"usernmae":'derek','age':18}

app.add_url_rule('/list/',endpoint='list',view_func=ListView.as_view('list'))


@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
Copy the code

14- View class based scheduling method

Copy the code
class LoginView(views.MethodView):
    def __render(self,error=None):
        return render_template('login.html', error=error)

    def get(self,error=None):
        return self.__render()

    def post(self):
        username = request.form.get('username')
        password = request.form.get('password')
        if username == 'derek' and password == '123':
            return '登录成功'
        else:
            return self.__render(error='用户名或密码错误')

app.add_url_rule('/login/',view_func=LoginView.as_view('login'))
Copy the code

 15-Routing

method one:

  The easiest way to define routes in the Flask applications, decorative applications using app.route examples provided.

# Url and view mapping 
@ app.route ( '/') 
DEF hello_world (): 
    return 'the Hello World!'

Second way:

  Use add_url_rule () method. 3 arguments: URL, name and endpoint view function.

Guess you like

Origin www.cnblogs.com/Moodsfeelings/p/11762756.html