Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non regex WSGI dispatcher

I've found this regex based dispatcher but I'd really rather use something that only uses literal prefix strings. Does such a things exist?

I know it wouldn't be hard to write but I'd rather not reinvent the wheel.

like image 359
BCS Avatar asked Dec 21 '25 14:12

BCS


2 Answers

Flask / Werkzeug has a phenomenal wsgi url dispatcher that is not regex based. For example in Flask:

@myapp.route('/products/<category>/<item>')
def product_page(category, item):
    pseudo_sql = select details from category where product_name = item;
    return render_template('product_page.html',\
                      product_details = formatted_db_output)

This gets you what you would expect, ie., http://example.com/products/gucci/handbag ; it is a really nice API. If you just want literals it's as simple as:

@myapp.route('/blog/searchtool')
def search_interface():
    return some_prestored_string

Update: Per Muhammad's question here is a minimal wsgi compliant app using 2 non-regex utilities from Werkzeug -- this just takes an url, if the whole path is just '/' you get a welcome message, otherwise you get the url backwards:

from werkzeug.routing import Map, Rule

url_map = Map([
    Rule('/', endpoint='index'),
    Rule('/<everything_else>/', endpoint='xedni'),
])

def application(environ, start_response):
    urls = url_map.bind_to_environ(environ)
    endpoint, args = urls.match()
    start_response('200 OK', [('Content-Type', 'text/plain')])
    if endpoint == 'index':
        return 'welcome to reverse-a-path'
    else:
        backwards = environ['PATH_INFO'][::-1]
        return backwards

You can deploy that with Tornado, mod_wsgi, etc. Of course it is hard to beat the nice idioms of Flask and Bottle, or the thoroughness and quality of Werkzeug beyond Map and Rule.

like image 162
unmounted Avatar answered Dec 23 '25 03:12

unmounted


Not exactly what you describe, but your needs may be served by using bottle. The route decorator is more structured. Bottle does not host WSGI apps, though it can be hosted as a WSGI app.

Example:

from bottle import route, run

@route('/:name')
def index(name='World'):
    return '<b>Hello %s!</b>' % name

run(host='localhost', port=8080)
like image 30
Muhammad Alkarouri Avatar answered Dec 23 '25 05:12

Muhammad Alkarouri