The flask of Pythonweb frame

Source: Internet
Author: User

Simple example:
 from Import  = Flask (__name__) @app. Route ('/')def Hello_world ():     return ' Hello world! ' if __name__ ' __main__ ' :    app.run ()

1. Configuration

To configure settings for a configuration item via app. Config:

-Direct Assignment

app.config['secret_key'"sdf234jkwjk3423kldjl"

-Configuration item Management through configuration files

# settings.py definition class, variable name to capitalize, in the flask of the use of the source code to make a isupper judgment class baseconfig ():     " 3d086a6d-a140-41d8-817b-61f66de49fc0 "    "3C43K6ZL5LAS1D2KK3D8Y7TW" # using      App.config.from_object ("settings. Baseconfig")

2. Routing system

-Way One

def index ():     Pass app.add_url_rule ('/''index', index) # '/': URL, ' Index ': endpoint,index: function corresponding to execution

-Way Two

@app. Route ('/', endpoint= ' index ')def  index ():     Pass

-Dynamic parameter transfer

@app. Route ('/index/<int:nid>')def  Index (NID):     return " Index "

Endpoint specifies how URLs are reversed, by default, function names

Url_for (Endpoint) # reverse parsing
Url_for (endpoint, nid= parameter) # Reverse parse argument

Specify the request method methods

@app. Route ('/', methods=['GET','POST '])  # The default is only get

3.CBV

Example

#CBV View fromFlaskImportflask,url_for,views#-----------------------------------------------------App=flask (__name__)#Decorative DevicedefAuth (func):Print('I'm on top .')    defInner (*args,**Kwargs):returnFunc (*args,**Kwargs)returnInner#--------------------------------------------------------classIndexview (views. Methodview):#CBV Viewmethods=['GET']#allowed HTTP request method (change CBV only get method is allowed)decorators = [Auth,]#every request comes with a auth decorator.    defGet (self):return 'Index.get'    defpost (self):return 'Index.post'App.add_url_rule ('/index/', View_func=indexview.as_view (name='name1'))#(name= ' name1 ' reverse generates URL aliasesif __name__=='__main__': App.run () CBV View

4. Request the relevant

Data that the request can obtain:

Request.methodrequest.argsrequest.formrequest.valuesrequest.cookiesrequest.headersrequest.pathrequest.full_ Pathrequest.script_rootrequest.urlrequest.base_urlrequest.url_rootrequest.host_urlrequest.hostrequest.files

For more information, refer to the blog https://www.cnblogs.com/wangjikun/p/6935592.html

5. Response

-Return "Hello World" string

-Return jsonify ({' Data ': Data}) returns JSON

-Return render_template (' index.html ') returns HTML

-Return redirect ('/login ') jump

Custom Response Headers:

 from Import  = Make_response ("HelloWorld") response.headers["xxx  "value"#  Sets the cookieResponse.set_cookie ( " Key " " value ")
return response

6. Template rendering

The usage is similar to the Django template rendering: {{}} and {%}.

The basic method is not quite the same, the function needs to be executed in parentheses, similar to the Python syntax:

-{{Dict.get ()}} or {{dict["key"}}}

-{{list[0]}}

-{% for loop%} {% endfor%}

-{% if determined%} {% ENDIF%}

You can also customize global functions to use in templates:

@app. Template_global () def SUM (a1, A2):     return A1 + A2#  template use {{sum (2, 3)}}#  similar @app. Template_ Filter ()def  sum (A1, A2, A3):    return A1 + A2 + a3# called differently {{1|sum (2,3)}}    

Template inheritance:

" mater.html "%} {% block content%}    custom content {% endblock%} {" component. html"  %}    

Define Macros:

{% macro input (name, type='text', value=' ') %}<input type="{{type}}"Name="{{name}}"Value="{{value}}">{% ENDMACRO%}#Use<form>{{input ('username')}}{{input ('Password', type="Password")}}{{input (' ', type="Submit", value="Submit") }}</form>

Safety:

# Front End {{data| Safe}} # back end  from Import  = Markup (data)

7.session

The session in the flask is normally stored in a cookie, and when requested, the session value is read from the cookie, decrypted and deserialized in the local object, and can be manipulated in the view through the imported session. At the end of the request, the value is read from the local object, serialized and encrypted, and saved to the cookie.

8.flash

A way to temporarily store data in flask

 from Import Flash, Get_flashed_messages # Store Data Flash (" temp data ""name")#  get data, get and remove msg = get_flashed_messages (category_filter=["name" via Pop) ])

9. Middleware

The app.__call__ method is executed when the request arrives in flask, and __call__ executes the App.wsgi_app method. And we can rewrite Wsgi_app to complete a middleware, rewrite App.wsgi_app as an object, execute App.wsgi_app () will trigger the __call__ method of the class, in the __call__ method to complete the operation of the middleware.

classmiddleware ():def __init__(self, wsgi_app) Self.wsgi_app=Wsgi_appdef __call__(self, Environ, start_response):#actions before processing a requestRET =Self.wsgi_app (environ, start_response)#actions after the request is completed        returnretif __name__=='__main__': App.wsgi_app=Middleware (App.wsgi_app) App.run ()

10. Special Decorative Device

1.before_request: A function that performs its adornment before executing a request for the corresponding view function, which can be used as login validation.

2.after_request: The function that performs its adornment after the request is completed

3.before_first_request: The function that performs its adornment on the first request

4.template_global

5.template_filter

6.errorhandler: The function that captures the specified error and then performs its adornment

The flask of Pythonweb frame

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.