我一直在玩龙卷风,并且我写了一些看起来不太好的代码。
我正在写一个应用来存储食谱。这些是我的处理程序:
handlers = [
(r"/recipes/", RecipeHandler),
(r"/recipes", RecipeSearchHandler), #so query params can be used to search
]
这导致我写了这个:
class RecipeHandler(RequestHandler):
def get(self):
self.render('recipes/index.html')
class RecipeSearchHandler(RequestHandler):
def get(self):
try:
name = self.get_argument('name', True)
self.write(name)
# will do some searching
except AssertionError:
self.write("no params")
# will probably redirect to /recipes/
有没有更好的方法来尝试不使用try / except的这些URL?我希望/ recipes和/ recipes /显示相同的内容,而/ recipes?name = something可以进行搜索,并且理想情况下是不同的处理程序。
有一种更好的GET请求方法。有一个在github上龙卷风源的演示在这里
# url handler
handlers = [(r"/entry/([^/]+)", EntryHandler),]
class EntryHandler(BaseHandler):
def get(self, slug):
entry = self.db.get("SELECT * FROM entries WHERE slug = %s", slug)
if not entry: raise tornado.web.HTTPError(404)
self.render("entry.html", entry=entry)
任何与正则表达式匹配的“文本”都将作为slug参数传递给EntryHandler的get方法。如果网址与任何处理程序都不匹配,则用户将收到404错误。
如果您想提供另一个备用广告,则可以将参数设为可选
(r"/entry/([^/]*)", EntryHandler),
class EntryHandler(BaseHandler):
def get(self, slug=None):
pass
更新:
+1的链接。但是,如果我想像这样进行搜索,此网址格式是否扩展为包括更多参数... / recipes?ingredient = chicken&style = indian – colinjameswebb
是的,它确实。
handlers = [
(r'/(\d{4})/(\d{2})/(\d{2})/([a-zA-Z\-0-9\.:,_]+)/?', DetailHandler)
]
class DetailHandler(BaseHandler):
def get(self, year, month, day, slug):
pass
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句