admin管理员组

文章数量:1313121

I have an object that needs to be stored in a Flask application running SQLAlchemy. I create the table when the application starts up. However the columns are based on an object that is created by a different service. It would be nice if that service could publish a JSON that has all the fields and then the flask app creates the table based on that. Is that possible?

I have an object that needs to be stored in a Flask application running SQLAlchemy. I create the table when the application starts up. However the columns are based on an object that is created by a different service. It would be nice if that service could publish a JSON that has all the fields and then the flask app creates the table based on that. Is that possible?

Share Improve this question asked Jan 30 at 17:15 user14530855user14530855 1251 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I will work only if create a custom parcer of a file. Sadly, I won't work out of the box.

You will need some kind of a mapping:

from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime 

type_mapping = {
    "Integer": Integer,
    "String": String,
    "Boolean": Boolean,
    "Float": Float,
    "DateTime": DateTime
}

And you will need to fill the data in the correct way to allow sqlalchemy to read it correctly. The format of the data should be something like this:

attrs = {
   "__tablename__": table_name, 
   "__table_args__": {"extend_existing": True}},
   # just an example
   some_column_name = Column(col_type, nullable=True, unique=False)
}

Later you would be able to init the model using:

DynamicModel = type(your_table_name), (Base,), attrs)

engine = create_engine("")
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

本文标签: flaskCan I create a table in SQLAlchemy using a schema from a filejson fileStack Overflow