0

我有处理发布请求并向客户端返回一些 JSON 的处理程序,在我返回之前我需要验证输入数据,如果数据没有通过验证我需要放入标头(我不知道如何修改标头并添加额外的键),它没有通过键 VALIDATION 或其他任何东西下的验证标志。如何更改龙卷风帖子标题并将此数据添加到标题中?

def post(self):
    data = tornado.escape.json_decode(self.request.body)
    key = data.get('key', None)

    # here if key is not in db and did not pass validation I should add VALIDATION key value False to header and send back to client 

    result = fetch_data_for(key)        
    self.write(json.dumps(result))
    self.flush()
4

1 回答 1

6

RequestHandler has set_header and add_header methods: http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.set_header

#!/usr/bin/python
# -*- coding: utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def post(self):
        data = tornado.escape.json_decode(self.request.body)
        key = data.get('key', None)

        # result = fetch_data_for(key)        
        result = "ok\n"

        self.add_header('validation', 'value')
        self.write(result)      

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

Output:

$ curl -v "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"key":"..."}'  http://localhost:8000
* getaddrinfo(3) failed for Accept:80
* Couldn't resolve host 'Accept'
* Closing connection #0
curl: (6) Couldn't resolve host 'Accept'
* About to connect() to localhost port 8000 (#0)
*   Trying 127.0.0.1... connected
> POST / HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:8000
> Accept: */*
> Content-type: application/json
> Content-Length: 13
> 
* upload completely sent off: 13out of 13 bytes
< HTTP/1.1 200 OK
< Date: Sun, 09 Jun 2013 16:49:40 GMT
< Content-Length: 3
< Validation: value
< Content-Type: text/html; charset=UTF-8
< Server: TornadoServer/3.0.1
< 
ok
* Connection #0 to host localhost left intact
* Closing connection #0
于 2013-06-09T16:50:28.457 回答