(仍然)获取RuntimeError:在请求上下文之外工作。尝试app.app_context()时

Jos*_*eph 3 python request flask

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]
Run Code Online (Sandbox Code Playgroud)

这是一个程序,它接受浏览器URL中的两位信息(postId和uid),并且应该允许我在程序中引用它们。对于我简单的python程序,我无法弄清楚为什么仍然出现RuntimeError:在请求上下文之外工作。

这通常意味着您尝试使用需要活动HTTP请求的功能。请查阅有关测试的文档,以获取有关如何避免此问题的信息。

我与app.app_context()一起使用,但它不允许我在请求中获取变量的内容。我已经阅读了文档,并查看了其他解决方案,但仍然遇到问题。请帮忙?

Jos*_*eph 5

So if I define a function it has global scope in python and so I can call it within the app.route() / request context limited function to get the 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]
Run Code Online (Sandbox Code Playgroud)