I am still learning flask and I have created an restful API with SQLAlchemy. The app is getting to be big and I would like to split it up into multiple files. When I separate the routes section from the main file, the app starts complaining about the SQL modules not being found. I have added all the imports to the routes file and it doesn't seem to help either. The error I am getting is:
module> Session.configure(bind=engine) NameError: name 'engine' is not defined
How can I get the Alchemy module to talk to 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()
CodePudding user response:
I suppose your error is traceable to admin.py
, because in there you want to initialize the session again using engine
which is not known in admin.py
.
A possible solution would be to import engine
from app.py
.
CodePudding user response:
Found a workaround. I created a module for this and it is now working.