我找到了这个基于正则表达式的调度程序,但我真的更愿意使用只使用文字前缀字符串的东西。这样的事情存在吗?
我知道写起来并不难,但我宁愿不重新发明轮子。
Flask / Werkzeug有一个非凡的 wsgi url 调度程序,它不是基于正则表达式的。例如在烧瓶中:
@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
更新:这里的 Per Muhammad 的问题是一个最小的 wsgi 兼容应用程序,它使用来自 Werkzeug 的 2 个非正则表达式实用程序——这只需要一个 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
.
不完全是您所描述的,但您的需求可以通过使用来满足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)
我知道这已经有几年了,但这是我快速而肮脏,非常简单的解决方案。
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)
笔记