2016-11-02 2 views
2
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)に2ビットの情報を受け入れ、プログラムでそれらを参照できるようにするプログラムです。私の単純なPythonプログラムでは、なぜ私はまだRuntimeErrorを取得しているのかわかりません:リクエストコンテキストの外で働いています。(まだ)RuntimeErrorを取得する:要求コンテキスト外で作業する。

これは通常、アクティブなHTTP要求である が必要な機能を使用しようとしたことを意味します。この問題を回避する方法については、 のテストに関するドキュメントを参照してください。

私はwith app.app_context()を使用していますが、要求に応じて変数の内容を邪魔することはありません。私はドキュメントを読んで、他のソリューションを見たが、まだまだ立ち往生している。助けてください?

答えて

1

私は関数を定義するとpythonでグローバルスコープを持つため、app.route()/ request context限定関数を呼び出して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] 
+0

ダン私は自分の投稿に投票できません。 – Joseph

関連する問題