flask sqlalchemy
3.1.1
Flask-SQLAlchemy 是 Flask 的擴展,可為您的應用程式新增對 SQLAlchemy 的支援。它旨在透過提供有用的預設值和額外的幫助程式來簡化 SQLAlchemy 與 Flask 的使用,從而更輕鬆地完成常見任務。
重要的
該項目是 Pallets 社區生態系統的一部分。 Pallets是維護Flask的開源組織; Pallets-Eco 支援 Flask 擴充的社群維護。如果您有興趣協助維護該項目,請聯絡 Pallets Discord 伺服器。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy . orm import DeclarativeBase , Mapped , mapped_column
app = Flask ( __name__ )
app . config [ "SQLALCHEMY_DATABASE_URI" ] = "sqlite:///example.sqlite"
class Base ( DeclarativeBase ):
pass
db = SQLAlchemy ( app , model_class = Base )
class User ( db . Model ):
id : Mapped [ int ] = mapped_column ( primary_key = True )
username : Mapped [ str ] = mapped_column ( unique = True )
with app . app_context ():
db . create_all ()
db . session . add ( User ( username = "example" ))
db . session . commit ()
users = db . session . scalars ( db . select ( User ))