Flask: How do I get the returned value from a function that uses @app.route decorator?
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 (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.
not sure what the context is. You could just call the method.
from yourmodule import get_tokendef 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