官方文檔:http://flask-sqlalchemy.pocoo.org/2.3/python
1.安裝(進入虛擬環境)--利用鏡像安裝PyMySQLmysql
#python36 -m pip install PyMySQL -i http://pypi.mirrors.ustc.edu.cn/simple --trusted-host pypi.mirrors.ustc.edu.cnsql
(pymysql是驅動庫,請確保安裝)數據庫
2.安裝flask-sqlalchemy:json
#python36 -m pip install flask-sqlalchemy -i http://pypi.mirrors.ustc.edu.cn/simple --trusted-host pypi.mirrors.ustc.edu.cnflask
3.安裝自動生成工具sqlacodegenapp
python36 -m pip install sqlacodegen -i http://pypi.mirrors.ustc.edu.cn/simple --trusted-host pypi.mirrors.ustc.edu.cnide
4.利用sqlacodegen生成model:工具
sqlacodegen --tables users --outfile D:\video\flask\pro\Models.py mysql+pymysql://root:123123@localhost/test?charset=utf8mb4ui
備註:上面分別是項目路徑,數據庫用戶名密碼,數據庫名稱
5.使用flask-sqlalchemy基本配置:
官方文檔:http://flask-sqlalchemy.pocoo.org/2.3/quickstart/#a-minimal-application
(1).在啓動文件中(index.py中)配置:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123123@localhost/test?charset=utf8' app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False #SQLAlchemy 將會追蹤對象的修改而且發送信號
db = SQLAlchemy(app)
(2).在Model中配置:
官方文檔:http://flask-sqlalchemy.pocoo.org/2.3/queries/#querying-records
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
user_id = Column(INTEGER, primary_key=True)
user_name = Column(String(50), nullable=False)
user_qq = Column(String(50), nullable=False)
def as_dict(self): #自定義的方法,把咱們的類轉爲dict
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
6.查詢:
官方文檔:http://flask-sqlalchemy.pocoo.org/2.3/queries/#querying-records
例如:user=User.query.filter_by(user_id=userid).first() return user
7.自定義響應類的修改:
def force_type(cls, response, environ=None):
if isinstance(response,dict): #當返回類型是dict時,咱們作相應的處理
response=jsonify(response)
if isinstance(response, MyModel): # 當返回類型是對象時,咱們作相應的處理
response = jsonify(response.as_dict())
return super(Response,cls).force_type(response,environ)