flask_postgresql
1.0.0
Blask PostgreSQL库提供了一个方便的接口,用于将PostgreSQL数据库集成到烧瓶应用程序中。该库通过提供类似于Blask-Sqlalchemy的易于使用的API来简化数据库交互。
演示:我使用烧瓶-Sqlalchemy和Blask_postgresql制作了Mediumclone,并更改了两条三行代码。在此演示中,我使用blask_login库,该库也由我的blask_postgresql库支持。
您可以使用PIP安装烧瓶PostgreSQL库:
pip install flask-pgsql --user
添加支持Blask_login库✅
from flask_login import UserMixin , LoginManager , ...
class USERS ( UserMixin , db . Model ): ...使用Metaclass,因为在Python 3.11中弃用了类属性,并且在Python中不支持3.13
class BaseModel :
...
@ classmethod
@ property # Class properties are deprecated in Python 3.11 and will not be supported in Python 3.13
def query ( cls ): ...这样做。
class MetaModel ( type ): ...
class BaseModel ( metaclass = MetaModel ): ... from flask_sqlalchemy import SQLAlchemy
app . config [ 'SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///' + os . path . join ( basedir , 'database \ database.db' )
app . config [ 'SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
db = SQLAlchemy ( app ) # Creating an SQLAlchemy instance
...
if __name__ == "__main__" :
if RESET :
with app . app_context (): db . create_all ()替换为
from flask_postgresql import PostgreSQL
db = PostgreSQL ( hostname = hostname , port = port , database = database , username = username , password = password )
...
if __name__ == "__main__" :
if RESET :
db . create_all () # with app.app_context(): db.create_all() will also work class Test ( db . Model ):
id = db . Column ( db . Integer , primary_key = True )
data = db . Column ( db . Integer , array = True )
def __repr__ ( self ):
return f"Test( { self . id } , { self . data } )"
db . create_all ()
p = Test ( data = [ 21 , 24 ])
db . session . add ( p )
db . session . commit ()
Test . query . get ( id = 1 ). data #-> [21, 24] 要初始化PostgreSQL连接,请从flask_postgresql导入PostgreSQL类,并提供必要的连接参数:
import os
from flask_postgresql import PostgreSQL
# Retrieve database connection parameters from environment variables
hostname = os . getenv ( "db_hostname" )
port = int ( os . getenv ( "db_port" ))
database = os . getenv ( "db_database" )
username = os . getenv ( "db_username" )
password = os . getenv ( "db_password" )
# Initialize the PostgreSQL connection
db = PostgreSQL ( hostname = hostname , port = port , database = database , username = username , password = password )通过子分类db.Model来定义数据库模型。这是定义BLOGS和USERS模型的一个示例:
class BLOGS ( db . Model ):
id = db . Column ( db . Integer , primary_key = True )
user_id = db . Column ( db . Integer , nullable = False )
title = db . Column ( db . String ( 100 ), nullable = False )
description = db . Column ( db . String ( 200 ), nullable = True )
data = db . Column ( db . Text , nullable = False )
def __repr__ ( self ):
return f" { self . id } ). Name : { self . user_id } , title: { self . title } , description: { self . description } , data: { self . data } "
class USERS ( db . Model ):
id = db . Column ( db . Integer , primary_key = True )
username = db . Column ( db . String ( 80 ), unique = True , nullable = False )
email = db . Column ( db . String ( 120 ), unique = True , nullable = False )
age = db . Column ( db . Integer )
is_active = db . Column ( db . Boolean , default = True )
bio = db . Column ( db . Text )
details = db . Column ( db . JSON , nullable = True )
profile_image = db . Column ( db . LargeBinary )
created_at = db . Column ( db . DateTime , default = db . func . now ())
def __repr__ ( self ):
return f"Test( { self . id } , { self . username } , { self . email } , { self . age } , { self . is_active } , { self . bio } , { self . profile_image } , { self . created_at } )"使用create_all()方法创建数据库表:
db . create_all ()
# or you can recreate any special table
# USERS.create()
# BLOGS.create()您可以使用模型的query属性查询数据:
users = USERS . query . all ()
user = USERS . query . get ( id = 12 )您可以使用add()方法将数据添加到数据库中:
new_user = USERS ( username = "example_user" )
db . session . add ( new_user )
db . session . commit ()您可以使用delete()方法从数据库中删除数据:
user_to_delete = USERS . query . get ( id )
user_to_delete . delete ()
db . session . commit ()虽然烧瓶PostgreSQL库是为烧瓶应用设计的,但它也可以用于其他框架或需要PostgreSQL数据库集成的独立python脚本中。
欢迎捐款!如果您发现任何问题或提出改进的建议,请随时打开问题或提交拉动请求。