Flask SQLAlchemy 和蓝图
Flask SQLAlchemy and Blueprints
我还在学习烧瓶,我用 SQLAlchemy 创建了一个 restful API。该应用程序越来越大,我想将其拆分为多个文件。当我将路由部分与主文件分开时,应用程序开始抱怨找不到 SQL 模块。我已将所有导入添加到路由文件中,但似乎也无济于事。我得到的错误是:
模块>
Session.configure(绑定=引擎)
NameError:名称 'engine' 未定义
如何让 Alchemy 模块与 admin.py 对话?
app
app.py
admin
__init__.py
admin.py
######################## admin.py ########################
from flask import Flask, request, jsonify, Blueprint, render_template
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
import json
import logging
admin = Blueprint("admin", __name__)
#initialize Session
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
session = Session()
employee_schema = EmployeeSchema()
#create Employee
@admin.route('/', methods=['POST'])
def add_employee():
..........
#Get Employee
@admin.route('/', defaults={'id': None}, methods=['GET'])
@admin.route('/<id>', methods=['GET'])
..........
#Delete Employee
@admin.route('/<id>', methods=['DELETE'])
def delete_employee(id):
..........
#update Employee
@admin.route('/<id>', methods=['PUT'])
def update_employee(id):
..........
######################## app.py ########################
from flask import Flask, request, jsonify
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
import json
import logging
from admin.admin import admin
#Init app
app = Flask(__name__)
#Allows URL's to be with a trailing / or not
app.url_map.strict_slashes = False
app.register_blueprint(admin, url_prefix="/")
#Gets password info from json file
..........
# Define the MariaDB engine using MariaDB Connector/Python
engine = sqlalchemy.create_engine(f"mariadb+pymysql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB}")
Base = declarative_base()
class Employee(Base):
__tablename__ = 'employees'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
firstname = sqlalchemy.Column(sqlalchemy.String(length=100))
lastname = sqlalchemy.Column(sqlalchemy.String(length=100))
active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
Base.metadata.create_all(engine)
#initialize Session
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
session = Session()
我想你的错误可以追溯到 admin.py
,因为你想在其中使用 engine
再次初始化会话,这在 admin.py
中是未知的。
一个可能的解决方案是从 app.py
.
导入 engine
找到解决方法。我在文件夹中创建了一个 init 文件,现在可以使用了。
我还在学习烧瓶,我用 SQLAlchemy 创建了一个 restful API。该应用程序越来越大,我想将其拆分为多个文件。当我将路由部分与主文件分开时,应用程序开始抱怨找不到 SQL 模块。我已将所有导入添加到路由文件中,但似乎也无济于事。我得到的错误是:
模块> Session.configure(绑定=引擎) NameError:名称 'engine' 未定义
如何让 Alchemy 模块与 admin.py 对话?
app
app.py
admin
__init__.py
admin.py
######################## admin.py ########################
from flask import Flask, request, jsonify, Blueprint, render_template
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
import json
import logging
admin = Blueprint("admin", __name__)
#initialize Session
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
session = Session()
employee_schema = EmployeeSchema()
#create Employee
@admin.route('/', methods=['POST'])
def add_employee():
..........
#Get Employee
@admin.route('/', defaults={'id': None}, methods=['GET'])
@admin.route('/<id>', methods=['GET'])
..........
#Delete Employee
@admin.route('/<id>', methods=['DELETE'])
def delete_employee(id):
..........
#update Employee
@admin.route('/<id>', methods=['PUT'])
def update_employee(id):
..........
######################## app.py ########################
from flask import Flask, request, jsonify
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
import json
import logging
from admin.admin import admin
#Init app
app = Flask(__name__)
#Allows URL's to be with a trailing / or not
app.url_map.strict_slashes = False
app.register_blueprint(admin, url_prefix="/")
#Gets password info from json file
..........
# Define the MariaDB engine using MariaDB Connector/Python
engine = sqlalchemy.create_engine(f"mariadb+pymysql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB}")
Base = declarative_base()
class Employee(Base):
__tablename__ = 'employees'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
firstname = sqlalchemy.Column(sqlalchemy.String(length=100))
lastname = sqlalchemy.Column(sqlalchemy.String(length=100))
active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)
Base.metadata.create_all(engine)
#initialize Session
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
session = Session()
我想你的错误可以追溯到 admin.py
,因为你想在其中使用 engine
再次初始化会话,这在 admin.py
中是未知的。
一个可能的解决方案是从 app.py
.
engine
找到解决方法。我在文件夹中创建了一个 init 文件,现在可以使用了。