同时使用Flask炼金术和Flask炼金术,为什么

2024-04-27 03:51:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在一个烧瓶应用程序,是数据库密集型工作了约4个月。我对python、flask和sqlalchemy非常陌生,但对web和数据库编程非常熟悉。你知道吗

我主要使用核心SQL来处理硬数据库位,但也使用了ORM。我在核心SQL中使用的主要方法是text()和bindparam()函数,它们通过sqlalchemy方言提供了数据库独立性。你知道吗

我发现自己不得不混合我的模块导入来得到我想要的东西。这里有一个简单但典型的例子。你知道吗

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import bindparam
from sqlalchemy.sql import text

SQLAlchemy对象随后会在我的代码的ORM位中使用,我相信它也会按照this处理会话。它是这样初始化的。你知道吗

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = appdb
app.config['SQLALCHEMY_BINDS'] = {'meta': foodb, 'data': bardb}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

然后我使用db变量访问所有的flask\u sqlalchemy内容。你知道吗

直接sqlalchemy的东西被用在我的核心SQL中,看起来像这样。你知道吗

我现在发现的是,我正在混合代码,例如这样。你知道吗

eng = db.get_engine(bind='meta')
cxn = eng.connect()
sql = text('select * from foo') 
rows = cxn.execute(sql).fetchall()

在我看来,如果我决定使用flask\u sqlalchemy,我不应该单独导入sqlalchemy的东西,它应该在flask\u sqlalchemy的某个地方。混合使我对副作用感到紧张。你知道吗

所以我有两个问题。你知道吗

  1. 这样混合安全吗?你知道吗
  2. 我能得到text()和 bindparam()和其他来自flask的sqlalchemy的东西?如果 那怎么办?你知道吗

Tags: textfromimportconfig数据库appflask核心
1条回答
网友
1楼 · 发布于 2024-04-27 03:51:39

下面对我自己问题的回答概括了我在过去4个月里通过艰苦的努力学到的一些东西。你知道吗

我是一个数据库程序员,希望使用SQLAlchemy核心SQL与我的数据库对话,而不是ORM。下面的代码就是在这种情况下给出的。你知道吗

  1. 绑定并使用多个数据库。你知道吗
  2. 获取列名。你知道吗
  3. 条款处理。你知道吗
  4. 引擎v会话。你知道吗
  5. 交易记录。你知道吗

我希望它能帮助别人。你知道吗

'''
THE SETUP
'''
maindb = 'dialect+driver://username:password@host:port/main database'
foodb = 'dialect+driver://username:password@host:port/foo database'
bardb = 'dialect+driver://username:password@host:port/bar database'

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = maindb
app.config['SQLALCHEMY_BINDS'] = {'foodb': foodb, 'bardb': bardb}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


'''
THE CODE USING AN ENGINE
'''
# Using an engine (dbms = database management system).
dbms = db.get_engine(bind='foodb')
cxn = dbms.connect()
sql = db.text('SELECT * FROM foo WHERE foo_id = :id')
parms = {'id': 4}
rows = cxn.execute(sql, parms)

# Get column names, works for all the examples
print(rows.keys())

# Loop through rows and print the column value
for row in rows:
    print(row[1]) # Access by position
    print(row['foo_name']) # Access by column name
cxn.close

# Providing a list to an IN clause (bindparam with expanding=True)
sql = db.text('select * from foo where foo_id in :ids and foo_name like :nm')
parms = {'ids':[3,4,5], 'nm':'C%'}
for key in parms.keys(): # Apply bindparam to special cases like IN lists
    if type(parms[key]) == type([]): # Parameter value is a list
        sql = sql.bindparams(db.bindparam(key, expanding = True))
rows = cxn.execute(sql, parms)
print([row['foo_name'] for row in rows])

# Do a database transaction with an engine
txn = cxn.begin()
try:      
    sql = db.text('update foo set foo_name = :nm where foo_id = :id')
    parms = {'id': 4, 'nm':'mr foo bar'}
    cxn.execute(sql, parms)
    txn.commit()
except:
    txn.rollback()
    raise
finally:
    if cxn != None:
        cxn.close()

'''
THE CODE USING A SESSION
'''
# Using a session.
dbms = db.get_engine(bind='foodb')
ssn = db.session(bind=dbms)
sql = db.text('SELECT * FROM foo WHERE foo_id = :id')
parms = {'id': 4}
rows = ssn.execute(sql, parms)
print([row['foo_name'] for row in rows])

# Do a database transaction with a session
breakpoint()
try:      
    sql = db.text('update foo set foo_name = :nm where foo_id = :id')
    parms = {'id': 4, 'nm':'ms bar foo'}
    ssn.execute(sql, parms)
    ssn.commit()
except:
    ssn.rollback()
    raise
finally:
    if ssn != None:
        ssn.close()

相关问题 更多 >