非正则WSGI分发器
我发现了这个基于正则表达式的调度器,但我其实更想用那种只用字面前缀字符串的东西。有没有这样的东西呢?
我知道写一个这样的东西并不难,但我不想重复造轮子。
3 个回答
1
我知道这已经过去几年了,但这是我简单粗暴、超级简单的解决方案。
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)
注意事项
- 我们利用了内置的'dict'类,这样可以获得很多功能。
- 你需要提供send_error这个例程。
2
虽然这不是你所描述的完全一样,但你可以试试 bottle,它可能能满足你的需求。这里的 route
装饰器用起来更有条理。不过,Bottle 本身并不直接托管 WSGI 应用,但它可以作为一个 WSGI 应用被托管。
举个例子:
from bottle import route, run
@route('/:name')
def index(name='World'):
return '<b>Hello %s!</b>' % name
run(host='localhost', port=8080)
3
Flask 和 Werkzeug 有一个非常棒的 WSGI URL 分发器,它不是基于正则表达式的。举个例子,在 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)
这样做会得到你所期望的结果,也就是 http://example.com/products/gucci/handbag;这个 API 真的很不错。如果你只想要字面上的内容,那就简单得多:
@myapp.route('/blog/searchtool')
def search_interface():
return some_prestored_string
更新:根据 Muhammad 的问题,这里有一个使用 Werkzeug 中两个非正则工具的最小 WSGI 兼容应用——这个应用只处理一个 URL,如果整个路径是 '/',你会收到一个欢迎信息,否则你会得到反向的 URL:
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
你可以用 Tornado、mod_wsgi 等来部署这个应用。当然,Flask 和 Bottle 的简洁用法,以及 Werkzeug 在 Map
和 Rule
之外的全面性和质量,都是很难超越的。