Python 如何定义和访问数据库postgresql示例代码
我是新使用python flask的,我想连接到postgresql,在中使用类似flask示例的代码,但在代码示例中使用sqlite3。我试图搜索代码样本,但让我感到困惑,因为每个样本都使用不同的方法。这是我的代码,但在使用CLI初始化数据库时出错Python 如何定义和访问数据库postgresql示例代码,python,python-3.x,postgresql,flask,Python,Python 3.x,Postgresql,Flask,我是新使用python flask的,我想连接到postgresql,在中使用类似flask示例的代码,但在代码示例中使用sqlite3。我试图搜索代码样本,但让我感到困惑,因为每个样本都使用不同的方法。这是我的代码,但在使用CLI初始化数据库时出错 Error: No such command "init-db". 我的结构文件 这是我的代码: run.py #run.py import os from smart_app import create_app app = create_a
Error: No such command "init-db".
我的结构文件
这是我的代码:
run.py
#run.py
import os
from smart_app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
init.py
db.py
db.py
导入点击
从烧瓶导入当前应用程序,g
从flask.cli导入,使用_appcontext
从flask_sqlalchemy导入sqlalchemy
# db = SQLAlchemy()
def get_db():
if 'db' not in g:
g.db = SQLAlchemy()
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
如果您熟悉SQL,请使用连接到postgresql数据库。
或者,如果您想使用ORM操作flask中的数据库,可以使用 谢谢你的快速回复…我尝试你的建议
# db = SQLAlchemy()
def get_db():
if 'db' not in g:
g.db = SQLAlchemy()
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)