Python Road _flask Framework _flask Framework Foundation (2)

Source: Internet
Author: User
Tags connection pooling set time

One, configuration file

Unlike Django, Django will provide us with a configured setting file, and the configuration we need can be automatically added to the setting file, but flask is not, it's an interface that provides us with a variety of configuration files internally. We configure the relevant configuration according to the interface. Here are a few simple examples:

Way One:

As below, is our introduction to tell you how to configure, you can see that config is essentially a dictionary (internal inheritance Dict or __setitem__ method), by adding a key value pair to the dictionary can be configured, but like this way to write large configuration code in the main program code, Obviously does not conform to the programming specification, so does not recommend such use, of course flask also for our other methods.

Way two:

As below, the configuration content is written in the Py file, by reading the form of the file, the application starts automatically load the configuration file configuration, note that the configuration file is required by default要放在程序root_path目录,如果instance_relative_config为True,则就是instance_path目录。

Way three:

Configure the environment variable as follows, configure the configuration file as an environment variable, and then read the configuration file in the environment variable through app.config.from_envvar (' environment variable name ') , it also calls the From_pyfile method internally, essentially the same , the same configuration file is placed in the directory in the same way two.

Mode four:

By configuring the configuration information in the class, follow theapp.config.from_object(“python类或类的路径”)方式加载配置,这样的方式不但可以将配置信息和逻辑代码分离,还可以做到将不同级别的配置进行分离,局部配置和全局配置分离,不同应用的配置也写成不同的配置类,局部配置继承全局配置,很灵活。为推荐的配置方式。

Examples of setting files:

classBaseconfig (object):" "placing the global configuration" "DB='127.0.0.1'    Print("Test Baseconfig")classTestconfig (baseconfig):" "Place Local Configuration" "    Print("Test Testconfig")classDevConfig (baseconfig):" "Place Local Configuration" "    Print("Test DevConfig")classProconfig (baseconfig):" "Place Local Configuration" "    Print("Test Proconfig")

Second, blueprint

In the previous tutorial we all write all the applications in the same PY file, obviously this is not very reasonable. We should separate different applications from Django, and then use just one launcher file. In flask, you can use Blueprints (Blueprint) to introduce small and medium-sized projects, which provide directory partitioning for your applications.

mange.py File code example:

import Fcrm                                     # refers to the project module, which executes the __init__.py file in the module if__name__' __main__ ' :    fcrm.app.run (Port=8001)                     # app __init__.py file instantiation in FCRM module

__init__.py File Code:

 from Import Flask  from Import account                     # Introduction View folder Views under Account application from import= Flask (__name__)print(app.root_path) App.register_blueprint ( Account.account)        # Blueprint Registration App App.register_blueprint (Order.order)

Account Application code:

 from Import  = Blueprint ('account',__name__) @account. Route (' /login ' )def  login ():    #  return ' login '    return Render_template ('login.html')

Third, database connection pool

Unlike the Django framework, the Flask framework does not provide our own database, so we can only introduce modules such as pymysql, so that we can operate the database, but how do we do it? Maybe we can connect to the database directly where we use it, as follows:

Import== conn.cursor () cursor.execute ('select * from TB where ID >%s  ', [5= cursor.fetchall () cursor.close () conn.close ()print(Result)

But like the above situation, each request to create a database connection repeatedly, the number of connections too much, it is certainly not very reasonable, in production remember to connect the database. And do we think of the following solutions? Establish a connection in advance for each view to use without duplicating the database connection. Obviously this is possible in a single thread, but if it is multi-threading, we have to lock the database in order not to operate the database for multiple users. But this makes multithreading meaningless. The code is as follows:

ImportPymysqlImportThreading fromThreadingImportRlocklock=rlock () CONN= Pymysql.connect (host='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')defTask (ARG): With Lock:cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () cursor.close ( )Print(Result) forIinchRange (10): T= Threading. Thread (Target=task, args=(i,)) T.start ()

So what do we do? We're going to use a data connection pool thing. Dbutils is a Python module that implements database connection pooling. Installation mode pip install Dbutils, but before we talk about the database connection pool, we first introduce the concept of a local thread, where the local thread actually makes a unique identity for each thread that stores the data for this thread, such as the following example:

ImportThreadingImport Time#Local Thread ObjectLocal_values =threading.local ()deffunc (num):"""# The first thread comes in, and the local thread object creates a # for him a second thread comes in, and the local thread object creates a unique identity for him {thread 1: {name:1}, thread 2 's unique identity: {name:2},} :p Aram Num:: return:"""Local_values.name= num#4Time.sleep (2)    #Local_values.name, go to local_values to get the value of name in value based on your unique identity as key    Print(Local_values.name, Threading.current_thread (). Name) forIinchRange (5): Th= Threading. Thread (Target=func, args= (i,), name='Thread%s'%i) Th.start ()

Database connection pool Mode one:

With a local thread implementation, a connection is created for each thread, and the thread does not close even if the Close method is called, but simply puts the connection back into the connection pool for its own thread to use again. When the thread terminates, the connection is automatically closed. As follows:

 fromDbutils.persistentdbImportPersistentdbImportPymysqlpool=Persistentdb (creator=pymysql,#modules that use linked databasesMaxusage=none,#the maximum number of times a link is reused, none means unlimitedSetsession=[],#a list of commands to execute before starting the session. such as: ["Set Datestyle to ...", "Set time zone ..."]ping=0," "Ping the MySQL server to check if 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 False, Conn.close () is actually ignored for the next use, and the link is automatically closed when the thread is closed.
If True, Conn.close () closes the link and then calls pool.connection again with an error because it is
The connection has been really closed (pool.steady_connection () can get a new link)" "threadlocal=none,#This thread is exclusive to the object that holds the linked object, if the linked object is resethost='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')deffunc (): Conn=pool.connection () cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () cursor.close () Conn.close ( )#not really closed, but fake off. forIinchRange (10): T= Threading. Thread (target=func) T.start ()

Database connection pool Mode two:

Create a batch of connections to the connection pool for all threads to share with. PS: Because the threadsafety value of Pymysql, MYSQLDB, etc. is 1, the threads in this mode connection pool are shared by all threads. As follows:

Import TimeImportPymysqlImportThreading fromDbutils.pooleddbImportPooleddb, Shareddbconnectionpool=Pooleddb (creator=pymysql,#modules that use linked databasesMaxconnections=6,#the maximum number of connections allowed for a connection pool, 0 and none means no limit on the number of connectionsmincached=2,#at least 0 of the free links created in the link pool are not created when initializingMaxcached=5,#most idle links in the link pool, 0 and none are not limitedMaxshared=3,#The maximum number of links shared in a linked pool, 0 and none means sharing all. PS: Useless, because Pymysql and mysqldb modules such as threadsafety are 1, all values regardless of set to how much, _maxcached forever is 0, so forever is all links are shared. Blocking=true,#If there are no available connections in the connection pool, wait is blocked. True, wait, False, not wait and then errorMaxusage=none,#the maximum number of times a link is reused, none means unlimitedSetsession=[],#a list of commands to execute before starting the session. such as: ["Set Datestyle to ...", "Set time zone ..."]ping=0,#Ping the MySQL server to check if 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 = Alwayshost='127.0.0.1', Port=3306, the user='Root', Password='123', Database='Pooldb', CharSet='UTF8')deffunc ():#detects if the number of currently running connections is less than the maximum number of links, if not less than: Waits or reports raise Toomanyconnections exception    #otherwise    #gets the link steadydbconnection in the link created when the initialization is prioritized.     #The Steadydbconnection object is then encapsulated into the pooleddedicateddbconnection and returned.     #if the link you initially created is not linked, create a Steadydbconnection object and encapsulate it in pooleddedicateddbconnection and return.     #once the link is closed, the connection is returned to the connection pool for subsequent threads to continue to use. conn =pool.connection ()cursor=conn.cursor () cursor.execute ('SELECT * from TB1') Result=Cursor.fetchall () conn.close () func ()

Python Road _flask Framework _flask Framework Foundation (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.