sqlalchemy-Data Catalog Collection Consolidation

Source: Internet
Author: User

First, Sqlalchemy-utils

Because the choice method is not available in SQLAlchemy, the choice method provided by the Sqlalchemy-utils component

Importdatetime fromSQLAlchemyImportCreate_engine fromSqlalchemy.ext.declarativeImportDeclarative_base fromSQLAlchemyImportColumn, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index fromSqlalchemy.ormImportRelationship fromSqlalchemy_utilsImportChoicetypebase=declarative_base ()classXuan (Base):__tablename__='Xuan'types_choices= ((1,'Europe'),(2,'Japan and South Korea'),(3,'old boy'),) ID= Column (integer,primary_key=true,autoincrement=True) name= Column (String (64)) Types=Column (Choicetype (Types_choices,integer ()))__table_args__= {'Mysql_engine':'Innodb','Mysql_charset':'UTF8',}engine=Create_engine ("Mysql+pymysql://root:[email Protected]:3306/ttt2?charset=utf8", Max_overflow=0,#most connections created outside the connection pool sizePool_size=5,#Connection Pool SizePool_timeout=30,#There are no threads in the pool waiting for the most time, otherwise the errorPool_recycle=-1#how long after a connection to a thread in a thread pool is recycled (reset)) Base.metadata.create_all (engine)


Inquire:

Result_list = Session.query (Xuan). All ()
For item in Result_list:
Print (Item.types.code,item.types.value)

Second, scoped_session

 fromSqlalchemy.ormImportSessionmaker fromSQLAlchemyImportCreate_engine fromSqlalchemy.ormImportScoped_sessionengine=Create_engine ("Mysql+pymysql://root:[email Protected]:3306/ttt?charset=utf8", Max_overflow=0,#most connections created outside the connection pool sizePool_size=5,#Connection Pool SizePool_timeout=30,#There are no threads in the pool waiting for the most time, otherwise the errorPool_recycle=-1#how long after a connection to a thread in a thread pool is recycled (reset)) Sessionfactory= Sessionmaker (bind=engine)#mode one: Because the thread sharing feature cannot be provided, all of them should be noted at development time by creating a session on each thread. #From sqlalchemy.orm.session Import session#own operation database: ' Close ', ' commit ', ' connection ', ' delete ', ' execute ', ' expire ',.....Session =sessionfactory ()#print (' native Session ', session)#Operationsession.close ()#mode two: Support thread safety, create a session for each thread#-Threading. Local#-Unique identification#Scopedsession Object#self.registry (), add parentheses to create session#self.registry (), add parentheses to create session#self.registry (), add parentheses to create session fromGreenletImportGetCurrent as Get_identsession=scoped_session (sessionfactory,get_ident)#Session.add#OperationSession.remove ()

Three, Flask-sqlalchemy and flask-migrate components

4, flask-SQLAlchemy: Flask and SQLAlchemy together, the binder is in the __init__.py file1 Introduction of flask-SQLAlchemy in SQLAlchemy, instantiating a SQLAlchemy object2 Register flask-SQLAlchemy:-There are two ways to do one: inside the function, SQLAlchemy (APP)#If you want to use it somewhere else, it's not going to make it.mode two: In the global: DB=SQLAlchemy (), Inside the function Db.init_app (APP)#call the Init_app method and put it in the app.3, importing the models class4, the imported class inherits the Db.model, but essentially inherits the base class.5. manage.py CREATE database tables, which can be created by commands. With flask-Migrate components to complete5, flask-Migrate:-The old 5 was killed: Import db inside manage.py, execute Db.create_all () to create the table later, execute drop_all () Delete table later so bad, we can and flask-Migrate combined with-New 5:flask-Migrate-Installation components: Pip Install flask-Migrate-5.1Import fromFlask_migrateImportMigrate, Migratecommand fromAppImportdb, App-5.2 Migrate = migrate (APP,DB)#Create an instance-5.3create command Manager.add_command ("DB", Migratecommand)-5.4execute command Python manage.py DB init#executes only the first timepython manage.py db migratepython manage.py DB upgrade before executing the command, you have to connect to the database before he knows the table is there.

Two ways to register SQLAlchemy

Way One

 from Import SQLAlchemy  from Import  = Flask (__name__) app.config['sqlalchemy_database_uri'] =  "mysql://root:[email protected]/test"= SQLAlchemy (APP)

Way two:

 from Import SQLAlchemy  from Import  = SQLAlchemy ()def= Flask (__name__) Db.init_app (APP)  Return App

Iv. Operational Database

Through the above registered SQLAlchemy, you can directly from the Db.session

# Way One # will automatically create a session Db.session.add () Db.session.query (models. User.id,models. User.Name). All () Db.session.commit () db.session.remove ()# mode two import modelsmodels. User.query

V. All used components in the flask

all used components flask Two operations that connect to a database either Dbutils: Used to execute native SQL with SqlHelper in its own util or SQLAlchemy: follow his own syntax to link one: SQLAlchemy ( APP) This approach has limitations, what if I have to use it somewhere else? It writes to the global way two: advantages, instantiation: DB=SQLAlchemy () Registration: Configure the database link in Settings Sqlalchemy_database_uri="Mysql+pymysql://root:[email Protected]:3306/s6?charset=utf8"sqlalchemy_pool_size= 2Sqlalchemy_pool_timeout= 30sqlalchemy_pool_recycle=-1Flask-SQLAlchemy:db.init_app (APP) Flask-session#for the bar session save somewhere elseFlask-script#Generate CommandsFlask-migrate#Database MigrationFlask-sqlalchemy#to combine flask and sqlalchemy well together.#Nature: Each operation of the database will automatically create a session connection, finished automatic shutdownBlinker#SignalWtforms#Form Componentscomponents and versions used PIP3 freeze#get all installed modules in the environmentPIP3 Freeze >A.TXTPIP3 Freeze>Requirements.txt#pip3 Install Pipreqs #帮你找到当前程序的所有模块, and automatically generate requirements.txt files, write contentPipreqs./#root directoryafter someone gives you a program to tell you a folder to install components: Requirements.txt into the program directory: Pip install-R Requirements.txt#all the components of the design will be loaded.structure: Appstatictemplatesviews__init__. pymodels.py

sqlalchemy-Data Catalog Collection Consolidation

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.