Python 的輕鬆閲讀
Python 的輕鬆閲讀

寫寫 Python,還有關於 Python 延伸的項目

學習 python 記錄 - 套件 fastapi-sqlalchemy

fastapi-sqlalchemy 的使用

直接安裝

pip install fastapi-sqlalchemy

使用 add, update, delete

使用 ORM 的方式比較輕鬆

# add
save = User(username=username, password=password)
db.session.add(save)
db.session.commit()

# update
user = db.session.query(User).filter_by(id=123).first()
user.password = password_change
db.session.commit()

# delete
user = db.session.query(User).filter_by(id=123).delete()
db.session.commit()

# select, 使用 first(),這個返回 json 格式
user = db.session.query(User).filter_by(id=123).first()
username = user.username
password = user.password

使用 all(),使用 dict 轉 json.dumps()

# select, 使用 all(),返回 dict,要靠 json.dumps() 轉換 json
import json

users = db.session.query(User).all()
json_users = json.dumps(users)

記錄一下

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…
加载中…

发布评论