I've found this regex based dispatcher but I'd r开发者_开发知识库eally 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.
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
.
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)
I know it's been a few years, but here is my quick and dirty, drop-dead simple, solution.
class dispatcher(dict):
def __call__(self, environ, start_response):
key = wsgiref.util.shift_path_info(environ)
try:
value = self[key]
except:
send_error(404)
try:
value(environ, start_response)
except:
send_error(500)
Notes
- We leverage the built-in 'dict' class to get a lot of functionality.
- You need to supply the send_error routine.
精彩评论