简体   繁体   中英

Flask: How do I get the returned value from a function that uses @app.route decorator?

So I'm pretty new to Flask and I'm trying to make my mind around one thing. So, if I understand well when you write a function within a Flask app and you use the @app.route decorator in that function, it only runs when you hit that path/url.

I have a small oauth app written in Flask that goes through all the authorization flow and then it return the token.

My question is how do I get that token from the @decorated function? For example, lets say I have something like this:

@app.route(/token/)
def getToken(code): #code from the callback url.
    #/Stuff to get the Token/
    #/**********************/
    return token

If I hit the (/token/) url-path the function returns the token. But now I need to get that token and use it in another function to write and read from the API I just got the token from. My initial thought was doing this:

token = getToken(code)

But if I do that, I get this error:

RuntimeError: working outside of request context

So again, my question is, how do I get the token so I can pass it as a parameter to other functions.

Extract the token generation code into a separate function, so that you can call it from anywhere, including the view function. It's a good practice to keep the application logic away from the view, and it also helps with unit testing.

I assume your route includes a placeholder for code, which you skipped:

def generateToken(code):
    #/Stuff to get the Token/
    #/**********************/
    return token

@app.route('/token/<string:code>')
def getToken(code):
    return generateToken(code)

Just keep in mind that generateToken shouldn't depend on the request object. If you need any request data (eg HTTP header), you should pass it explicitly in arguments. Otherwise you will get the "working outside of request context" exception you mentioned.

It is possible to call request-dependent views directly, but you need to mock the request object, which is a bit tricky. Read the request context documentation to learn more.

not sure what the context is. You could just call the method.

from yourmodule import get_token

def yourmethod():
  token = get_token()

Otherwise, you could use the requests library in order to retrieve the data from the route

>>> import requests
>>> response = requests.get('www.yoursite.com/yourroute/')
>>> print response.text

If you're looking for unittests, Flask comes with a mock client

def test_get_token():
  resp = self.app.get('/yourroute')
  # do something with resp.data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM