两者的区别(个人理解,简单写一下)
1 SQLALchemy,他连接数据库比较方便,就建立创建基类和对应的ORM, 连接数据库,创建引擎,创建会话,创建实例,创建实例,就可以对数据库对应的数据表进行对应的操作
2 Flask-SQLAlchemy ,这话比较麻烦一点,必须要在上下文推动才能连接到数据,也就是路由请求。但是它可以一次性绑定两个数据库。
SQLALchemy连接数据库
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
Base=declarative_base()
class Student(Base):
__tablename__='student'
id=Column(Integer,primary_key=True)
name=Column(String(5),nullable=False)
age=Column(Integer,nullable=False)
addr=Column(String(32),nullable=False)
MYSQL_CONFIG_BASE = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': '123456',
'charset': 'utf8mb4',
'database': 'db'
}
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}'
SQLALCHEMY_BINDS = SQLALCHEMY_DATABASE_URI.format(**MYSQL_CONFIG_BASE)
engine_data = create_engine(SQLALCHEMY_BINDS)
Sesssion = sessionmaker(bind=engine_data)
session = Sesssion_data()
?
session.add(Student(name="xiamei",age=12,addr='天津'))
session.add_all([Student(name="tom",age=22,addr='北京'),Student(name="tony",age=23,addr='北京')])
session.commit()
session.close()
Flask-SQLAlchemy连接数据库,连接两个数据库
from flask import Flask
from config import FLASK_CONFIGS
from app.extensions import db, cors
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
db = SQLAlchemy()
cors = CORS()
class ProdConfig(Config):
ENV = 'production'
DEBUG = False
MYSQL_CONFIG = MYSQL_CONFIG_BASE
MYSQL_CONFIG['host'] = '192.168.1.147'
SQLALCHEMY_BINDS = {
'device_param': SQLALCHEMY_URI_FORMAT.format(**MYSQL_CONFIG, database='device_param'),
'device_data': SQLALCHEMY_URI_FORMAT.format(**MYSQL_CONFIG, database='device_data')
}
app = Flask(__name__)
app.config.from_object(ProdConfig)
db.init_app(app)
cors.init_app(app)
@app.route('/')
def app_route():
return "Ok"
return app
|