English 中文(简体)
龙卷风 URL 查询参数
原标题:Tornado URL query parameters

我一直在玩弄龙卷风, 我写了一些代码 似乎不怎么好。

我在写一个程序来存储食谱,作为一个例子。这些是我的处理者:

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/

是否有更好的方法可以不尝试/ 例外地处理这些 URL? 我喜欢/ recipes 和 / recipes/ 来显示同样的东西, 而 / recipes? name = something 会做搜索, 最好换个处理器 。

最佳回答

在龙卷风源中有一个演示,请访问 https://github.com/facebook/transado/blob/master/demos/blog/blog.py#L87。

# 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)

任何符合正则表达式的“ 文本” 将被传递到条目Handlers 获取方法作为弹簧参数。 如果 URL 与任何处理器不匹配, 用户将收到404 个错误 。

如果您想要提供另一个后退, 您可以让参数可选

(r"/entry/([^/]*)", EntryHandler),

class EntryHandler(BaseHandler):
    def get(self, slug=None):
        pass

<强> 更新:

+1 for the link. However does this URL pattern extend to include more parameters if I wanted to search like this... /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
问题回答

get_argument 允许您提供默认值 :

details=self.get_argument("details", None, True)

如果不提供理由,就不会出现例外,如果没有提供理由

Tornado also has a get_arguments function. It returns a list of arguments with the given name. If not present, it returns an empty list ( [] ). I found it cleaner this way to sanitize your web service inputs instead of try..catch blocks.

Sample:
Assume I have a following URL handler:

(r"/recipe",GetRecipe)

And the request handler:

class GetRecipe(RequestHandler):
    def get(self):
        recipe_id = self.get_arguments("rid")
        if recipe_id == []:
            # Handle me
            self.set_status(400)
            return self.finish("Invalid recipe id")
        self.write({"recipe_id":self.get_argument("rid")})


recipe_id list will also hold the value but I found self.get_argument usage convenient this way.

Now for the results:

curl "http://localhost:8890/recipe" -v

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8890 (#0)
> GET /recipe HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:8890
> Accept: */*
> 
< HTTP/1.1 400 Bad Request
< Content-Length: 17
< Content-Type: text/html; charset=UTF-8
* Server TornadoServer/1.1.1 is not blacklisted
< Server: TornadoServer/1.1.1
< 
* Connection #0 to host localhost left intact
Invalid recipe id

curl "http://localhost:8890/recipe?rid=230" -v
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8890 (#0)
> GET /recipe?rid=230 HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:8890
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Length: 20
< Etag: "d69ecb9086a20160178ade6b13eb0b3959aa13c6"
< Content-Type: text/javascript; charset=UTF-8
* Server TornadoServer/1.1.1 is not blacklisted
< Server: TornadoServer/1.1.1
< 
* Connection #0 to host localhost left intact
{"recipe_id": "230"}

如果您想要使用更动态的过滤方法( 而不是硬编码的 URL), 您可以在请求处理器中使用 < code> self. request. arguments 来获取所有已通过的 URL 参数/ 参数 。

class ApiHandler(RequestHandler):
    def get(self, path):
        filters = self.request.arguments
        for k,v in filters.items():
            # Do filtering etc...

http://www.tradesradoweb.org/en/stable/httputil.html#traterado.httputil.HTTPServer request.arguments' rel=“noreferrer'>http://www.tradesadoweb.org/en/stable/httpttil.html#traterado.attil.httputil.HTTPServer request.arguments





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签