One installation Flask-sqlalchemy
Pip Install Flask-sqlalchemy
Two import related modules and objects
from Import SQLAlchemy
Three configurations
# here is the configuration Sqlalchemy_database_ URI, the preceding mysql+pymysql refers to the type of the database and the driver type
# after Username,pwd,addr,port, dbname represents user name, password, address, port, and library name
app.config[ sqlalchemy_database_uri ' ] = " mysql+pymysql://root:[email protected]:3306/ Firewall " # Here the login is the root user, to fill in their own password, mysql default port is 3306 app.config[ sqlalchemy_track_modifications " ] = False #??? True causes an error
# Create 1 Sqlalichemy instances
db = SQLAlchemy (APP)
Four Definition data Table mapping classes
classstaticroute (db. Model):__tablename__='Static_route_config'ID= db. Column (db. Integer, Autoincrement=true, primary_key=True) D_ip_mask= db. Column (db. String (+), Unique=false, nullable=False) Next_gateway= db. Column (db. String (+), Unique=false, nullable=False)__mapper_args__= { "order_by": Id.desc ()}def __init__(self, D_ip_mask, Next_gateway): Self.d_ip_mask=D_ip_mask Self.next_gateway=Next_gateway @staticmethoddefadd_db (D_ip_mask, Next_gateway): Db.session.add (Staticroute (D_ip_mask, Next_gateway)) Db.session.commit () #overloading of functions using default values in Python@staticmethoddefget_db (id=-1): ifID >=0:returnStaticRoute.query.get (ID)Else: returnStaticRoute.query.order_by ('ID') @staticmethoddefdel_db (ID): Db.session.delete (StaticRoute.query.get (ID)) db.session.commit () @staticmethoddefupdate_db (ID, D_ip_mask, next_gateway): SR=StaticRoute.query.get (ID) sr.d_ip_mask=D_ip_mask Sr.next_gateway=Next_gateway Db.session.add (SR) db.session.commit ()
Five creating databases and data tables
The Flask-sqlalchemy of Flask (I.)