RuntimeError:在请求上下文之外工作当在方法的第一行

时间:2016-04-16 15:34:18

标签: python flask request

所以我有一个用http.get调用调用的方法。

@app.route('/showSQL')
def get_sql():
    spid = request.args['spid']
    instance = request.args['instance']
    user = creds.creds['bh1']['user']
    pw = creds.creds['bh1']['pass']

    print 'calling show sql', spid, instance

    conn = pymssql.connect(instance, user, pw)
    cursor = conn.cursor(as_dict=True)

    cmd = 'EXEC master..getSpidSQL ' + str(spid)

    cursor.execute(cmd)
    sql_out = None
    for row in cursor:
        sql_out = row['EventInfo']

    return sql_out

我已经读过这个错误会出现多线程和类似错误,但这里没有什么复杂的。这个方法的第一行引发了错误:'spid = request.args ['spid']'

>>> longrunners.get_sql()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/tools/dba/longrunners/longrunners.py", line 48, in get_sql
    spid = request.args['spid']
File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/site-packages/werkzeug/local.py", line 302, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context

我有其他成功访问请求对象的方法,并且已经验证我实际上是从浏览器发送一个名为'spid'的参数。

有什么可能导致这种情况的想法?我查看了一堆其他问题并在网上查看,但没有发现任何与此特定情况相关的问题。

谢谢!

1 个答案:

答案 0 :(得分:2)

您的get_sql功能是Flask路线回调。它希望处于请求环境中。

使用HTTP请求调用此函数时,您的request将可访问。

如果要从其他上下文中调用它,请将请求与函数的其他部分分离。

@app.route('/showSQL')
def get_sql_callback():
    spid = request.args['spid']
    instance = request.args['instance']
    return get_sql(spid, instance)


def get_sql(spid, instance):
    user = creds.creds['bh1']['user']
    pw = creds.creds['bh1']['pass']

    print 'calling show sql', spid, instance

    conn = pymssql.connect(instance, user, pw)
    cursor = conn.cursor(as_dict=True)

    cmd = 'EXEC master..getSpidSQL ' + str(spid)

    cursor.execute(cmd)
    sql_out = None
    for row in cursor:
        sql_out = row['EventInfo']

    return sql_out

现在,您可以从shell调用它或将其作为HTTP请求进行访问。