Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create and persist models in Flask - Sqlalchemy [closed]

I am writing a flask webapp. I need to be able to create a model based on user input and create a table based on the model. Further, I also want to be able to use that model later (after having restarted the web server). What would be the best way of doing this?

I am using flask with sqlalchemy for the ORM.

like image 612
Vineet Goel Avatar asked Oct 31 '22 22:10

Vineet Goel


1 Answers

You are going to have a lot of dynamic queries man.

Have you ever seen how INFORMATION_SCHEMA.tables and INFORMATION_SCHEMA.columns look like?

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

Then you are going to read information form those tables to dynamically do something like this:

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

After that you will have array all_table_definitions with descriptions of all your tables and my_tables with ORM table objects to query data

like image 177
vittore Avatar answered Nov 08 '22 10:11

vittore