如何在Flask中获取自定义SELECT查询?

时间:2013-12-19 14:15:34

标签: python mysql flask peewee flask-peewee

我想在Flask-Peewee

上获取此自定义查询
SELECT A.* , haversine('34.0160',' -118.4925', A.lat, A.long, 'MILES') AS dist FROM merchant_details A HAVING haversine('34.0160', '-118.4925', A.lat, A.long, 'MILES') <6000

我尝试了下面这段代码,但是没有用,我得到'long'对象没有属性'fetchall':

@app.route('/api/results/')
def results():
    db = connect_db()
    cur = db.execute("SELECT A.* , haversine('34.0160',' -118.4925', A.lat, A.long, 'MILES') AS dist FROM merchant_details A HAVING haversine('34.0160', '-118.4925', A.lat, A.long, 'MILES') <6000 LIMIT 1")
    entries = [dict(id=row[0], merchant_id=row[1], merchant_name=row[2], first_name=row[3]) for row in cur.fetchall()]
    return repr(entries)

非常感谢任何帮助。

EDITED&GT;

这是connect_db函数:

from torndb import Connection

LOCALHOST = "localhost"
DBNAME = "XXXX"
DBUSER = "XXXX"
DBPASSWORD = "XXXX"


    #connect with DB
    def connect_db():
        db = Connection(LOCALHOST,DBNAME, user=DBUSER, password=DBPASSWORD)
        return  db

    #close the connection from DB
    def close_db(db):
        db.close()

2 个答案:

答案 0 :(得分:2)

如果您想运行SQL查询,可以使用flask-peewee:

db = Database(app)
db.database.execute_sql("some query", [param1, param2])

如果MerchantDetails是模型,您可以尝试:

dist = fn.haversine(
    34.0160, 
    -118.4925, 
    MerchantDetails.lat, 
    MerchantDetails.long, 
    'MILES')
MerchantDetails.select(MerchantDetails, dist.alias('dist')).having(dist < 6000)

获得:

SELECT A.* , haversine('34.0160',' -118.4925', A.lat, A.long, 'MILES') AS dist 
FROM merchant_details A 
HAVING haversine('34.0160', '-118.4925', A.lat, A.long, 'MILES') <6000

答案 1 :(得分:1)

我的猜测是connect_db()实际上返回游标而不是数据库连接。因此,db.execute的返回值实际上是 long (从查询返回的行数)。您应该尝试的第一步是更改为以下内容:

curr = connect_db()
curr.execute("QUERY")
entries = [... for row in curr.fetchall()]

也很可能(我没有查看源代码)connect_db正在返回一个新对象,它包装了连接对象和游标对象的功能,以便您可以与它进行交互。我自己过去做过这个。唯一奇怪的是处理close方法,因为游标和连接都定义close。在我的情况下,close关闭了。

根据您的评论

编辑 再一次,没有阅读connect_db()的源代码,我只能猜测。但你可能想尝试:

conn = connect_db()
curr = conn.cursor()

和以前一样继续。如果仍然给您一个错误,请通过在该列表中添加print dir(conn) after the call to connect_db(). My guess now is that it will show a游标`函数来查看其属性和方法。