Flask: How to get the return value from a function using @ app.route decorator?

So, I'm pretty new to Flask and I'm trying to figure out one thing. So, if I understand well, when you write a function in a Flask application and you use the @ app.route decorator in that function, it only fires when you click that path / url.

I have a small oauth application written in Flask that goes through the entire authorization flow and then returns a token.

My question is how do I get this token from the @decorated function? For example, let's 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 (/ token /) url-path, the function returns a token. But now I need to get this token and use it in another function to write and read from the API from which I only got the token. My initial thought was this:

token = getToken(code)

      

But if I do this, I get this error:

RuntimeError: working outside of request context

      

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

+3


source to share


2 answers


Extract the marker generation code into a separate function so you can call it from anywhere, including the view function. It is a good practice to keep the application logic out of the way and also helps with unit testing.

I am assuming your route contains a placeholder for the code you missed:

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

it shouldn't depend on the object request

. If you need request data (like an HTTP header), you must explicitly pass it in the arguments. Otherwise, you will get the "work outside of request context" exception that you mentioned.

It is possible to directly invoke requests that depend on the request, but you have to mock the request object, which is a bit tricky. Read the documentation on demand to find out more.

+2


source


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

from yourmodule import get_token

def yourmethod():
  token = get_token()

      

Otherwise you can use a library requests

to fetch data from a 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

      

0


source







All Articles