Reputation: 361
I am having a problem with returning a flask redirect from a function. I am probably missing something simple but would really appreciate some help.
Here is my views.py
from .tasks import get_stuff
from flask import render_template
@app.route('/get-stuff')
def get_stuff(stuff_name):
stuff = get_stuff(stuff_name)
return render_template('stuff.html', stuff=stuff)
Here is my function which is in tasks.py
import os
from flask import redirect, request, url_for
def get_stuff(stuff_name):
if os.environ.get('SOME_VARIABLE') is None:
return redirect(url_for('some_url', next=request.url))
stuff = "Some stuff here"
return stuff
And my stuff.html
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<h1 class="uppercase">{{ stuff }}</h1>
<hr>
</div>
</div>
</div>
{% endblock %}
So because SOME_VARIABLE is not set I want it to redirect to another page where I will get the user to set SOME_VARIABLE. But this is not happening I am getting <Response 241 bytes [302 FOUND]>
. Any help would be much appreciated.
Upvotes: 1
Views: 3077
Reputation: 2888
From what I see, You have twice defined get_stuff
function, once in tasks.py
and second time in views.py
.
Second thing I notice, You are rerouting to /some_url
, while I don't see You actually defined that route.
Upvotes: 0
Reputation: 600049
But you're still calling return render_template
in your handler, whatever the result of the call to the task. You need to return that result directly if it is a redirect.
Potentially you could return a flag as well from that task, to tell the calling function what to do:
if os.environ.get('SOME_VARIABLE') is None:
return True, redirect(url_for('some_url', next=request.url))
stuff = "Some stuff here"
return False, stuff
and in the handler:
redirect, stuff = get_stuff(stuff_name)
if redirect:
return stuff
return render_template('stuff.html', stuff=stuff)
But really this is all far too complex. You should either get the task to return the full response no matter what happens - ie render the template there, rather than in the handler - or move the whole logic into the handler function.
Upvotes: 2