Combine mesop with natural abilities of flask
mesop is popular with AI apps, since is can be used to build web apps with Python without frontend works.
mesop is developed upon the popular frontend framework flask. How about combine the natural abilities of flask while developing with mesop? Let do a little research.
Access flask request instance(including headers, cookies)
In any mesop page, you may simply access flask.request, flask.request.cookies, flask.request.headers by importing flask. For example
1import flask
2import mesop as me
3
4@me.page(
5 path="/home",
6 security_policy=me.SecurityPolicy(
7 dangerously_disable_trusted_types=True)
8)
9def page():
10 with me.box():
11 for k, v in flask.request.cookies.items():
12 me.text(f'{k}: {v}')
The above code will display the cookies inside a box component.
Get the flask app instance
The mesop wraps the flask app instance inside a function, it would be a little tricky to get the flask app instance from a mesop app.
If you would serve mesop app via a wsgi app instance, after calling the create_wsgi_app, you my get a flask app instance by:
1import mesop as me
2
3def get_flask_app():
4 try:
5 me._wsgi_app({}, lambda: None) # make sure flask app is created
6 except:
7 pass
8 return me._wsgi_app.__closure__[0].cell_contents._flask_app
9
10app = get_flask_app() # flask app instance
11
12# serve me._wsgi_app with a server
Note that the flask app instance is not created when me._wsgi_app is created, calling me._wsgi_app({}, lambda: None) make sure it is being created.
The other way is to get a mesop app instance via mesop.server.wsgi_app.create_app function, and access by mesop_app._flask_app.
1import mesop as me
2from mesop.server.wsgi_app import create_app
3
4me_app = create_app(prod_mode=True)
5app = me_app._flask_app # flask app instance
6
7# run flask app server
8app.run(debug=True, host='0.0.0.0', port=5000)
Note, you can not start the server with mesop command, since it has different importing mechanism of the main module.
Write flask views
With flask app instance we got from above, we can write flask views just as it is:
1@app.route('/set_cookie', methods=['GET'])
2def set_cookie():
3 resp = flask.make_response()
4 for k, v in flask.request.args.items():
5 resp.set_cookie(k, v)
6 return resp
Note that, the mesop already declared the following routes:
The /path is for serving static files of mesop, it will not conflict with routes defined more specific(ses https://flask.palletsprojects.com/en/stable/design/#the-routing-system).
Conclusion
mesop is powerful for building web UI, with the natural ability of flask, it can be much easier to integrate with existing flask code and third party libraries.