简体   繁体   English

将SQL查询转换为flask-sqlalchemy语句

[英]translate SQL query to flask-sqlalchemy statements

I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence. 我正在将Web应用程序的旧SQL实现更改为flask-alchemy,并且在通信方面遇到一些困难。

The old code looks like this. 旧代码看起来像这样。 It does the name query about some properties and returns a csv style text. 它会查询一些属性的名称,并返回一个csv样式的文本。

header = 'id,display_name,city,state,latitude,longitude\n'
base_query = '''SELECT id, bbs_id, city, state, 
                     latitude, longitude FROM mytable'''
conn = sqlite3.connect(path.join(ROOT,'db.sqlite')) 
c = conn.execute(base_query+'WHERE name=?', (name,))
results = c.fetchall()
conn.close()
rows = [','.join(map(str, row)) for row in results]
return header + rows

The new code 新密码

header = 'id,display_name,city,state,latitude,longitude\n'
cols = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude'] 
users = User.query.filter_by(name=name).all()
rows = ''
for user in users:
    rows += ','.join([user.id, user.bbs_id, user.city, user.state, user.latitude, user.longitude]) + '\n'
return header + rows

I am not happy with the new code since it's so verbose. 我对新代码不满意,因为它太冗长了。

  • Is there a way to select only the ones in cols instead of query all columns and then pick the needed columns? 有没有办法只选择在那些cols ,而不是查询中的所有列,然后挑选需要的列?
  • If not, is it possible to write the ','.join() more succinctly? 如果没有,是否可以更简洁地编写','.join() It seems user['id'] does not work and I have to do user.id . 看来user['id']不起作用,我必须做user.id

If you just want a result set as before, you can do: 如果您只想要像以前一样的结果集,则可以执行以下操作:

results = db.session.query(*(getattr(User, col) for col in cols)).filter_by(...)

and then you can use results as you did before. 然后您可以像以前一样使用results

If, OTOH, you want to use the ORM, you can use load_only : 如果是OTOH,您想使用ORM,则可以使用load_only

users = User.query.options(*(load_only(col) for col in cols)).filter_by(...)
rows = "".join(",".join(*(getattr(u, col) for col in cols)) + "\n" for u in users)

As it seems that you want to output comma separated values, use the proper module for that. 似乎您要输出逗号分隔的值,因此请使用适当的模块 You can override the query's entities with with_entities : 您可以使用with_entities覆盖查询的实体:

import csv
import io

...

output = io.StringIO()
writer = csv.writer(output)

headers = ['id', 'bbs_id', 'city', 'state', 'latitude', 'longitude'] 
writer.writerow(headers)

# The other option is to db.session.query(...)
users = User.query.with_entities(
    *(getattr(User, hdr) for hdr in headers)
).filter_by(name=name)
writer.writerows(users)

return output.getvalue()

If you're still on python 2, replace io.StringIO with io.BytesIO . 如果您仍在使用python 2, io.StringIO io.BytesIO替换为io.BytesIO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM