Joseph
Joseph

Reputation: 141

(Still) Getting RuntimeError: Working outside of request context. when trying app.app_context()

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]

This is a program that accepts two bits of information in a browser url (postId and uid) and should allow me to reference them in the program. For my simple python program I can't figure out why I'm still getting RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.

I'm using the with app.app_context() but it won't let me snag the content of the variables in request. I've read the docs and looked at others solution but still stuck. Please help?

Upvotes: 5

Views: 5733

Answers (1)

Joseph
Joseph

Reputation: 141

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]

Upvotes: 7

Related Questions