sqlalchemy get table with a string

274 views
Skip to first unread message

FURKAN bilgin

unread,
Mar 16, 2021, 3:14:03 PM3/16/21
to sqlalchemy

table_name = "table_name"

#get table as table

new = table(**tablo)
db.session.add(table)
db.session.commit()

Simon King

unread,
Mar 17, 2021, 7:27:31 AM3/17/21
to sqlal...@googlegroups.com
There are lots of ways of doing this. One option is to provide a
dictionary when creating your declarative_base:

classes = {}
Base = declarative_base(class_registry=classes)

Now you can look up classes by name in that classes dictionary:

def get_table_by_name(name):
return classes[name]

Another option could be to iterate over Base.__subclasses__:

def get_table_by_name(name):
for cls in Base.__subclasses__():
if cls.__name__ == name:
return cls

Hope that helps,

Simon
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
> ---
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/c3c7c369-7d7f-41b0-b6f3-273b6c76314dn%40googlegroups.com.

FURKAN bilgin

unread,
Mar 17, 2021, 10:07:03 AM3/17/21
to sqlalchemy
I think we keep it in RAM in the first method, so it may be a problem if the program is restarted. and I guess I don't understand what you mean by Base class.
17 Mart 2021 Çarşamba tarihinde saat 14:27:31 UTC+3 itibarıyla Simon King şunları yazdı:

Simon King

unread,
Mar 17, 2021, 10:17:56 AM3/17/21
to sqlal...@googlegroups.com
I assumed you were defining classes corresponding to your database
tables, as shown here:

https://docs.sqlalchemy.org/en/14/orm/tutorial.html#declare-a-mapping

If that's not how you're using SQLAlchemy, you'll have to show your code.

Simon
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1f98d725-f15f-4fde-9fe2-4205f71eb1d8n%40googlegroups.com.

FURKAN bilgin

unread,
Mar 17, 2021, 12:19:17 PM3/17/21
to sqlalchemy
I updated sqlalchemy and now I get an error when accessing the database. And their codes need to be coded:
What I really wanted to do was add data to a table with json data in the / main / write path. but now I get an error when I send / main / new-app post request (I updated sqlalchemy and it happened) related codes are below
Sorry for taking your time, there may not be a solution. I am thinking of rewriting the codes.


from sqlalchemy import MetaData, Table, Column, Integer, String, create_engine, DateTime,VARCHAR
from flask import Flask, abort, render_template, request,session,jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy import text
import json

meta = MetaData()
engine = create_engine('sqlite:////Users/dell/Desktop/2.2/db.db')
conn = engine.connect()

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:////Users/dell/Desktop/2.2/db.db'
db = SQLAlchemy(app)

app.secret_key = "Lbgsa,pdsa_ıda)6Kyw%61"

@app.route("/main/new-app",methods = ["GET","POST"])
def new_app():
    if request.method == "GET":
        return render_template("gg.html")
    if application.query.filter_by(name = request.form.get("username")).first():
       return "UserName..." 
    isim = request.form.get("username")
    varsayilanlar   = request.form.get("varsayilanlar")
    d_varsayilanlar = json.loads(varsayilanlar).keys()
    lis = [Column('id', Integer, primary_key = True),Column('date', DateTime, nullable=False, default=datetime.now)]
    for i in d_varsayilanlar:
        lis.append(Column(i,VARCHAR(80)))
    Table(isim, meta, *lis)
    meta.create_all(engine)
    new_app = application(name = isim,
                                password     = request.form.get("password"),
                                anaSayfa     = request.form.get("anaSayfa"),
                                manuelSayfa  = request.form.get("manuelSayfa"),
                                dinamikSayfa = request.form.get("dinamikSayfa"),
                                varsayilanlar= request.form.get("varsayilanlar"),
                                dinamik      = bool(request.form.get("dinamik")),
                                kitap        = bool(request.form.get("kitap")),
                                kalem        = bool(request.form.get("kalem")))
    db.session.add(new_app)
    db.session.commit()
    return "200OK"

@app.route("/main/write",methods = ["GET","POST"])
def write():
    if request.method == "GET":
        return "POST!"
    app = application.query.filter_by(name = request.form.get("username")).first()
    if not (app):
       return "Uygulama Bulunamadı"
    elif not(app.kalem) and (app.password != request.form.get("password")):
        return "TABLE NOT FOUND"
    tablo = json.loads(request.form.get("varsayilanlar"))
#i want to get table here
    new_row = meta.tables[request.form.get("username")]
    employee = new_row(**tablo)
    db.session.add(employee)
    db.session.commit()
    return "200ok"
class application(db.Model):
    id           = db.Column(db.Integer,primary_key = True)
    name         = db.Column(db.String(80))
    password     = db.Column(db.String(80))
    anaSayfa     = db.Column(db.String(80))
    manuelSayfa  = db.Column(db.String(80))
    dinamik      = db.Column(db.String(80))
    dinamikSayfa = db.Column(db.String(80))
    varsayilanlar= db.Column(db.String(80))
    kitap        = db.Column(db.String(80))
    kalem        = db.Column(db.String(80))
    pub_date     = db.Column(db.DateTime, nullable=False,default=datetime.now)
17 Mart 2021 Çarşamba tarihinde saat 17:17:56 UTC+3 itibarıyla Simon King şunları yazdı:

Simon King

unread,
Mar 17, 2021, 1:46:11 PM3/17/21
to sqlal...@googlegroups.com
OK, I see. You're creating tables dynamically, and you want to be able
to insert data into those tables.

I think it'll be easier to use SQLAlchemy Core for this, rather than
the ORM. You can use reflection to load table definitions from the
database.

https://docs.sqlalchemy.org/en/14/core/reflection.html#reflecting-database-objects
https://docs.sqlalchemy.org/en/14/core/tutorial.html#coretutorial-insert-expressions

That would look something like this (completely untested):

# if there's a chance multiple people can call this
# at the same time, you'll need to add a lock around it
def get_table(table_name):
if table_name in meta.tables:
return meta.tables[table_name]
return Table(table_name, meta, autoload_with=db.session.connection())

table_name = request.form.get("varsayilanlar")
table = get_table(table_name)
insert = table.insert().values(**tablo)
db.session.execute(insert)

Simon
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/20c81613-0794-4909-b353-200446d0a8a1n%40googlegroups.com.

FURKAN bilgin

unread,
Mar 18, 2021, 12:28:34 PM3/18/21
to sqlalchemy
Thank you for your response and I am immediately interested in your articles.

17 Mart 2021 Çarşamba tarihinde saat 20:46:11 UTC+3 itibarıyla Simon King şunları yazdı:
Reply all
Reply to author
Forward
0 new messages