Dynamically create and save models in Flask - Sqlalchemy

I am writing a webapp jar. I need to create a model based on user input and create a table based on the model. In addition, I also want to be able to use this model later (after restarting the web server). What would be the best way to do this?

I am using flask with sqlalchemy for ORM.

+4
source share
1 answer

You will have many dynamic queries.

Have you ever seen how and look ? INFORMATION_SCHEMA.tablesINFORMATION_SCHEMA.columns

Basically you are going to use them or create a clone of these tables in your database.

, - :

 from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey

 def make_metadata(source):
     ...
     return MetaData(...)     

 def make_column(column_definition): 
     return Column(....)


 all_table_definitions = ... # array of records from your custom_tables
 all_column_definitions = ... # map of table name to array of column definition for your tables from custom_columns
 my_tables = {}

 for t in all_table_definition:
   columns = [make_column(c) for c in all_column_definitions[t.name]]
   new_table = Table(t.table_name, make_metadata(t.metadata), columns*)

all_table_definitions my_tables ORM

+1

Source: https://habr.com/ru/post/1542690/


All Articles