尝试使用 app.app_context() 时仍然出现 RuntimeError: Working outside of request context.

5
from flask import Flask, request
app = Flask(__name__)

@app.route('/post/', methods=['GET', 'POST'])
def update_post():
    # show the post with the given id, the id is an integer
    postId = request.args.get('postId')
    uid = request.args.get('uid')
    return postId, uid

def getpostidanduid():
    with app.app_context():
        credsfromUI = update_post()
        app.logger.message("The postId is %s and uid is %s" %(request.args.get('postId'), request.args.get('uid')))
        ## Prints 'The post id is red and uid is blue'\
    return credsfromUI

print(getpostidanduid())

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
# [END app]

这是一个在浏览器URL中接受两个信息(postId和uid)的程序,应该允许我在程序中引用它们。对于我的简单Python程序,我无法弄清楚为什么仍然出现“RuntimeError:Working outside of request context”的错误。
通常,这意味着您尝试使用需要活动HTTP请求的功能。请参阅有关如何避免此问题的测试文档。
我正在使用app.app_context(),但它不允许我获取请求变量的内容。我已经阅读了文档并查看了其他解决方案,但仍然卡住了。请帮帮我?
1个回答

7

如果我在Python中定义一个函数,它将具有全局作用域,因此我可以在app.route() / request上下文限制的函数中调用它,以获取request.args.get(var)。

import datetime
import logging
from flask import Flask, request
app = Flask(__name__)

def testuser(username):
    # show the user profile for that user
    user_string = username.lower()
    return 'Username you appended is %s' %user_string

@app.route('/user/', methods=['GET', 'POST'])
def show_user_profile():
    # show the user profile for that user : http://127.0.0.1:8080/user/?user=gerry
    uid = request.args.get('user')
    print(testuser(uid))
    return 'User %s' %uid

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
# [END app]

1
我试图使用一个通用的打印函数来显示所有有趣的请求属性,但遇到了请求上下文问题。这个答案解决了它。我所要做的就是传递请求对象。def print_request(request): args_string = '' for k, v in request.args.items(): args_string += f'<p>arg {k} = {v}</p>' request_string = f'<p>Request method = {request.method}</p> return request_string + args_string - Leon Chang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接