I am trying to rest server with python flask-restx module. My table has two columns id
and value
. id
column is a auto-increment primary key. so for post I don't need to pass id
but for get
I need show it in the response.
- Is there any way I can avoid creating two tables?
- Is there any way I can directly map sqlalchamy model to flask-restx model.
- how to handle sqlalchamy session object. for now, I am creating this object for each method. is is a good idea to have a global session object, how can I attach that to my flask session object?
Following is the way I am doing it.
app = Flask(__name__)
api = Api(app)
demo_api_intake_model = api.model(
'demo_intake',
{
"value": fields.String(required=True, description="value")
}
)
demo_api_output_model = api.model(
'demo_output',
{
"id": fields.Integer(required=True, description="unique identifier, primary key"),
"value": fields.String(required=True, description="value")
}
)
@api.route("/demo")
class Demo(Resource):
@api.marshal_list_with(demo_api_output_model, code=200)
def get(self):
return get_session().query(DemoModel).all()
@api.expect(demo_api_intake_model)
def post(self):
json_data = request.get_json()
demo_model = DemoModel(value=json_data.get("value"))
session = get_session()
session.add(demo_model)
session.commit()
return demo_model.id
database.py
def _create_database_connection(db_user, db_pass, db_name, instance_connection_name):
pool = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL.create(
drivername="mysql+pymysql",
username=db_user, # e.g. "my-database-user"
password=my_pass, # e.g. "my-database-password"
database=db_name, # e.g. "my-database-name"
host="10.10.10.21", # e.g. "127.0.0.1"
port=3306, # e.g. 3306
),
# **db_config
)
Session = sessionmaker(bind=pool)
session = Session()
return session
def get_session():
connection = _create_database_connection(db_user="admin", db_pass=os.getenv("db_pass"),db_name=os.getenv("db_name))
return connection