如何更改龙卷风帖子标题并添加到标题新数据?

时间:2013-06-09 15:47:31

标签: python python-2.7 tornado

我有处理post请求的处理程序并将一些JSON返回给客户端,在我返回之前我需要验证输入数据,如果数据没有通过验证我需要放入头文件(我不知道如何修改头文件)并且在密钥VALIDATION或其他任何内容下,它没有通过验证标志。 如何更改tornado post header并将此数据添加到标题中?

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

1 个答案:

答案 0 :(得分:5)

RequestHandlerset_headeradd_header种方法: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()

输出:

$ 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