问题
I'm trying to learn Flask and making a small app. So at first, I tested without a css file by using: (delay() gets the result from generator)
return Response(stream_template('login.html', data=delay()))
It works fine for me then now i want to implement new css, let's called it style.css and i put it in the static folder. In the html file I have:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>
The code will probably won't work as there is a problem with context and response, but it will work fine as a static return:
return render_template('login.html')
My Question is it it anyway that I can both have the generator to work (the delay() function) with the CSS in the static folder? I just spent couple hours on this problem but couldn't find an answer yet.
My stream_template:
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
# uncomment if you don't need immediate reaction
##rv.enable_buffering(5)
return rv
Thanks a lot
回答1:
Quoting from the documentation:
Note that when you stream data, the request context is already gone the moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator: ...
In your case, your code probably should be:
return Response(stream_with_context(stream_template('login.html', data=delay())))
or
return Response(stream_template('login.html', data=stream_with_context(delay())))
来源:https://stackoverflow.com/questions/22741833/flask-how-to-use-css-when-im-using-responsestream-template-with-generator