WolfgangFahl / pyFlaskBootstrap4

Flask + Bootstrap 4 static components and templates for webprojects
Apache License 2.0
5 stars 2 forks source link

Assigning baseUrl as base prefix for all path #32

Open tholzheim opened 2 years ago

tholzheim commented 2 years ago

The Solution proposed at https://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes to set a Middleware seems to working fine since it allows to get the prefixed url with the default url_for() function.

class PrefixMiddleware(object):
    """
    see https://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes
    """

    def __init__(self, app, prefix=''):
        self.app = app
        self.prefix = prefix

    def __call__(self, environ, start_response):

        if environ['PATH_INFO'].startswith(self.prefix):
            environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
            environ['SCRIPT_NAME'] = self.prefix
            return self.app(environ, start_response)
        else:
            start_response('404', [('Content-Type', 'text/plain')])
            return ["This url does not belong to the app.".encode()]

And adding this to the appWrap init function

self.app.wsgi_app = PrefixMiddleware(self.app.wsgi_app, prefix=baseUrl)

But this change requires to adjust the current modules that use the basedUrl function. such as SSE_Blueprint

Tested this solution on orapi.