Combine mesop with natural abilities of flask

2024-12-23

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

import flask
import mesop as me

@me.page(
    path="/home",
    security_policy=me.SecurityPolicy(  
        dangerously_disable_trusted_types=True)  
)  
def page():  
    with me.box():  
        for k, v in flask.request.cookies.items():
            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:

import mesop as me

def get_flask_app():
    try:
        me._wsgi_app({}, lambda: None)  # make sure flask app is created
    except:
        pass  
    return me._wsgi_app.__closure__[0].cell_contents._flask_app

app = get_flask_app()  # flask app instance

# 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.

import mesop as me
from mesop.server.wsgi_app import create_app

me_app = create_app(prod_mode=True)
app = me_app._flask_app  # flask app instance

# run flask app server
app.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:

@app.route('/set_cookie', methods=['GET'])
def set_cookie():
    resp = flask.make_response()
    for k, v in flask.request.args.items():
        resp.set_cookie(k, v)  
    return resp

Note that, the mesop already declared the following routes:

/
/__ui__
/sandbox_iframe.html
/__web-components-module__/<path>
/__csp__
/<path>

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.