Flacon: How do I get the value returned 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:

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

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 (e.g. 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.