Flask framework,

Source: Internet
Author: User

Flask framework,
A Brief Introduction to the FLask framework

Flask is a micro-framework developed based on Python and dependent on the jinja2 template and the Werkzeug WSGI service. For Werkzeug, it is essentially a Socket server, which is used to receive http requests and pre-process requests, then, the Flask framework is triggered. The developer processes the request based on the functions provided by the Flask framework and returns the request to the user. If the complex content is to be returned to the user, you need to use the jinja2 template to process the template, that is, rendering the template and data and returning the rendered string to the user's browser.

"Micro" does not mean that you need to plug the entire Web application into a single Python file (although it does), it does not mean that Flask is lacking in functionality. The "micro" in the microframework means that Flask is designed to keep the core simple and easy to expand. Flask won't make too many decisions for you-such as what database to use. Those selected by Flask, such as the template engine used, are easily replaced. Everything else is beyond your control. In this way, Flask can work with you.

By default, Flask does not include the database abstraction layer, form verification, or any other functions that can be used by multiple existing databases. However, Flask supports using extensions to add these features to applications, just as it is implemented by Flask itself. Numerous extensions provide functions such as database integration, form verification, upload processing, and various open authentication technologies. Flask may be "tiny", but it is ready for use in a complicated production environment.

1 pip3 install flask
Routing System
@app.route('/login/',methods=["GET","POST"],endpoint="login",)

Methods: supported request method. endpoint: used to generate url (url_for) in reverse order)

From flask import Flask, url_forapp = Flask (_ name _) # define the conversion class from werkzeug. routing import BaseConverterclass RegexConverter (BaseConverter): "custom URL matching regular expression" def _ init _ (self, map, regex): super (RegexConverter, self ). _ init _ (map) self. regex = regex def to_python (self, value): "when the route match is successful, the value of the parameter passed to the view function: param value: return: "" return int (value) def to_url (self, value): "When url_for is used to reverse generate a URL, the passed parameters are processed by this method, the returned value is used to generate the parameter param value: return: "val = super (RegexConverter, self) in the URL ). to_url (value) return val # add it to the converts app. url_map.converters ['Re'] = RegexConverter # Use @ app. route ('/index/<re ("\ d +"): nid>') def index (nid): url_for ('XX', nid = 123) return "Index" if _ name _ = '_ main _': app. run ()
Extend the Flask routing system to support regular view functions.
# @ App. route ('/Index', endpoint = 'xx') def index (nid): url_for ('XX', nid = 123) return "Index" # def index (nid): url_for ('XX', nid = 123) return "Index" app. add_url_rule ('/Index', index)
FBV
Def auth (func): ''' decorator ''' def inner (* args, ** kwargs): result = func (* args, ** kwargs) return result return innerclass IndexView (views. methodView): # methods = ['post'] decorators = [auth,] # Add decorator def get (self): v = url_for ('index') print (v) return "GET" def post (self): return "GET" app. add_url_rule ('/Index', view_func = IndexView. as_view (name = 'index') if _ name _ = '_ main _': app. run ()
CBV request and response
From flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask (_ name _) @ app. route ('/login.html', methods = ['get', "POST"]) def login (): # request information # request. method # request. args # request. form # request. values # request. cookies # request. headers # request. path # request. full_path # request. script_root # request. url # request. base_url # request. url_root # request. host_url # request. host # request. files # obj = request. files ['the _ file_name '] # obj. save ('/var/www/uploads/' + secure_filename (f. filename) # response information # return "string" # return render_template ('html template path', ** {}) # return redirect ('/index.html ') # response = make_response(render_template('index.html ') # response is flask. wrappers. response type # response. delete_cookie ('key') # response. set_cookie ('key', 'value') # response. headers ['x-Something '] = 'a value' # return response return "content" if _ name _ =' _ main _ ': app. run ()
View Code template Language

Flask uses the Jinja2 template, so its syntax is basically the same as that of Django.

However, when you execute functions or methods in a django template, you do not need to add parentheses, and Flask must add parentheses to execute the functions or methods.

Markup in flask is equivalent to mark_safe in django.

# @ App. template_global () def tag (a1, a2): return a1 + a2 + 100 call method in the template {tag (1, 2) }# second @ app. template_filter () def db (a1, a2, a3): return a1 + a2 + a3 template call method {1 | db (2, 3 )}}
Usage flash of custom tags
from flask import Flask,flash,get_flashed_messages

Use flash and get_flashed_messages (the principle is to set and delete sessions)

Extension
@app.before_requestdef process_request1():    print('process_request1')@app.after_requestdef process_response1(response):    print('process_response1')    return response@app.before_requestdef process_request2():    print('process_request2')@app.after_requestdef process_response2(response):    print('process_response2')    return response
Pseudo-middleware configuration file
Class BaseConfig (object): ''' write common configuration ''' passclass TestConfig (BaseConfig): ''' write your own unique configuration ''' DB = '2017. 0.0.1 'class DevConfig (BaseConfig): ''' write your own unique configuration ''' DB = '2017. 168.1.1 'class ProConfig (BaseConfig): ''' write your own unique configuration ''' DB = '47. 18.1.1'
Settings
Configuration method
# Method 1:
# App. config ['session _ COOKIE_NAME '] = 'session _ lvning'
# Method 2:
# App. config. from_pyfile ('settings. py ')
# Method 3:
# Import OS
# OS. environ ['flaks-setting'] = 'settings. py'
# App. config. from_envvar ('flaks-settings ')
# Method 4:
# App. config. from_object ('settings. devconfig ')
Blueprint

The blueprint function is to place different functions in different py files.

For example:

Order. py

from flask import Blueprintorder = Blueprint('order',__name__)@order.route('/order')def order():    return 'Order'

 

Account. py

from flask import Blueprint,render_templateaccount = Blueprint('account',__name__)@account.route('/login')def login():    return render_template('login.html')

 

_ Init _. py

from flask import Flaskfrom .views import accountfrom .views import orderapp = Flask(__name__)app.register_blueprint(account.account)app.register_blueprint(order.order)

 

Database Connection Pool
"Creates a connection for each thread, which is implemented by thread. local. "From DBUtils. persistentDB import PersistentDBimport pymysqlPOOL = PersistentDB (creator = pymysql, # Use the maxusage module of the connected database = None, # the maximum number of times a link can be reused. None indicates unlimited setsession = [], # list of commands executed before starting a session. For example, ["set datestyle to...", "set time zone..."] ping = 0, # ping the MySQL server and check whether the service is available. # For example, 0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always closeable = False, # If it is False, conn. close () is actually ignored for the next time, and the link will be automatically closed only when the thread is closed. If it is True, conn. close () closes the link, so the pool is called again. an error will be reported during connection, because the connection is actually closed (pool. steady_connection () can get a new link) threadlocal = None, # This thread exclusive object, used to save the link object, if the link object is reset host = '100. 0.0.1 ', port = 3306, user = 'root', password = '000000', database = 'pooldb', charset = 'utf8') def func (): # conn = SteadyDBConnection () conn = POOL. connection () cursor = conn. cursor () cursor.exe cute ('select * from tb1 ') result = cursor. fetchall () curs Or. close () conn. close () # is false rather than true. Conn = pymysql. connect () conn. close () conn = POOL. connection () cursor = conn. cursor () cursor.exe cute ('select * from tb1 ') result = cursor. fetchall () cursor. close () conn. close () import threadingfor I in range (10): t = threading. thread (target = func) t. start ()
Mode 1
Import timeimport pymysqlimport threadingfrom DBUtils. pooledDB import PooledDB, SharedDBConnectionPOOL = PooledDB (creator = pymysql, # Use The Connection database module maxconnections = 6, # maximum number of connections allowed by the connection pool, 0 and None indicates no limit on connections mincached = 2, # At the time of initialization, there are at least idle links created in the connection pool. 0 indicates that maxcached = 5 is not created, # the maximum number of idle links in the connection pool is 0 and None. maxshared = 3 is not restricted, # The maximum number of links shared in the connection pool. 0 and None indicate that all links are shared. PS: useless, because the threadsafety of modules such as pymysql and MySQLdb are both 1, and all values, regardless of the value, _ maxcached is always 0, so all links are always shared. Blocking = True, # Whether to block and wait if no connection is available in the connection pool. True, wait; False, do not wait, and then report the error maxusage = None, # the maximum number of times a link can be reused, None indicates unlimited setsession = [], # list of commands executed before starting a session. For example, ["set datestyle to...", "set time zone..."] ping = 0, # ping the MySQL server and check whether the service is available. # For example, 0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host = '2017. 0.0.1 ', port = 3306, user = 'root', password = '000000', database = 'pooldb', charset = 'utf8') def func (): # Check whether the number of currently running connections is smaller than the maximum number of connections. If it is not smaller than the maximum number, wait for or report a raise TooManyConnections exception # Otherwise # obtain the SteadyDBConnection link from the link created during initialization. # Encapsulate the SteadyDBConnection object in PooledDedicatedDBConnection and return the result. # If there is no link to the initial link, create a SteadyDBConnection object, encapsulate it in PooledDedicatedDBConnection, and return the result. # Once the link is closed, the connection will be returned to the connection pool for subsequent threads to continue using it. # PooledDedicatedDBConnection conn = POOL. connection () # print (th, 'the link has been taken away', conn1. _ con) # print (th, 'current pool has ', pool. _ idle_cache, '\ r \ n') cursor = conn. cursor () cursor.exe cute ('select * from tb1 ') result = cursor. fetchall () conn. close () conn = POOL. connection () cursor = conn. cursor () cursor.exe cute ('select * from tb1 ') result = cursor. fetchall () conn. close () func ()
Mode 2

 

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.