Open PaulWasTaken opened 6 years ago
from flask import Flask, Response, stream_with_context, render_template
from flask_admin import Admin, BaseView, expose
from werkzeug.wsgi import FileWrapper
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
# Flask-Admin setup
admin = Admin(app, name='Flask-Admin Streaming Example', template_mode='bootstrap3')
# Custom streaming view
class StreamingView(BaseView):
@expose('/')
def index(self):
return self.render('streaming_index.html')
@expose('/stream')
def stream(self):
def generate():
# Simulated data streaming (replace with your actual data source)
for i in range(10):
yield f'Data point {i}\n'
# Simulate delay
import time
time.sleep(1)
return Response(stream_with_context(generate()), mimetype='text/plain')
def render(self, template, **kwargs):
# Override render method to pass context including admin_base_view
kwargs['admin_base_view'] = self.admin.base_template
kwargs['app'] = self.admin.name
return super(StreamingView, self).render(template, **kwargs)
# Add streaming view to Flask-Admin
admin.add_view(StreamingView(name='Streaming', endpoint='streaming'))
# Routes for static files (needed for Flask-Admin templates)
@app.route('/admin/static/<path:filename>')
def admin_static(filename):
from flask_admin import static
return static(filename)
# Example template: streaming_index.html
"""
<!DOCTYPE html>
<html>
<head>
<title>Streaming Example</title>
</head>
<body>
<h1>Streaming Example</h1>
<p>Click <a href="{{ url_for('streaming.stream') }}">here</a> to start streaming.</p>
</body>
</html>
"""
if __name__ == '__main__':
app.run(debug=True)
http://flask.pocoo.org/docs/1.0/patterns/streaming/ There is a possibility in flask but i can not reproduce it in flask admin. I use my own views and then add them
admin.add_view
. Using render it is okay, but when i try to implement code from tutorial above, i got exceptions. 1 - from jinja (admin_base_view
is undefiend), 2 - no app context when trying to use static (from your internal templates). Any recommends, please?