Search code examples
pythonflaskmiddlewarewsgi

How can I use a dispatcher middleware on flask?


I am trying to use the wsgi DispatcherMiddleware in order to prefix a url on my application. I've written one module for the dispatcher and one for the app, which has just one view called home and this is where the homepage is served from.

here is my app1.py

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/home', methods=['GET'])
def home():
    return "<h1>Home</h1>"

and dispatcher.py

from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound

from app1 import app


app = Flask(__name__)

app.wsgi_app = DispatcherMiddleware(NotFound(), {
    "/prefix": app
})

if __name__ == "__main__":
    app.run()

what I wanna do is be able to navigate to http://127.0.0.1:5000/prefix/home when I run on console py dispatcher.py, but however when I navigate on that url I get a 404 response. What works in only the navigation to the pagehttp://127.0.0.1:5000/home. Could someone help me understand why this happens? I appreciate any help you can provide


Solution

  • SOLUTION:

    I was using wrong tha same name for the dispacher and the app1.

    dispacher.py should be edited as follows:

    from flask import Flask
    from werkzeug.wsgi import DispatcherMiddleware
    from werkzeug.exceptions import NotFound
    
    from app1 import app as app1
    
    
    app = Flask(__name__)
    
    app.wsgi_app = DispatcherMiddleware(NotFound(), {
        "/prefix": app1
    })
    
    if __name__ == "__main__":
        app.run()