user14530855
user14530855

Reputation: 125

Can I create a table in SQLAlchemy using a schema from a file/json file?

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?

Upvotes: 0

Views: 20

Answers (1)

ViAchKoN
ViAchKoN

Reputation: 724

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()

Upvotes: 1

Related Questions