2012-03-16 40 views
2

我正在写一个使用龙卷风,python的小型web应用程序,下面是我的代码。我有一个带有2个文本字段的Python表单,现在我想要输入文本字段并存储在redis中。
我的问题 -如何使用龙卷风python保存用户输入数据redis

  1. 我如何连接到从我的python脚本的Redis?
  2. 如何将传入的用户输入存储到redis中?

示例代码将不胜感激。

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

from tornado.options import define, options 

define("port", default=8888, help="run on the given port", type=int) 

class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
     self.write('<html><body><form action="/" method="post">' 
      '<p>Please enter the Key Value pair for redis.</p>' 
        '<input type="text" **name="key"** value="type key here">' 
      '<input type="text" **name="value"** value="type value here">' 
        '<input type="submit" value="Submit Key Value">' 
        '</form></body></html>') 


def main(): 
    tornado.options.parse_command_line() 
    application = tornado.web.Application([ 
     (r"/", MainHandler), 
    ]) 
    http_server = tornado.httpserver.HTTPServer(application) 
    http_server.listen(options.port) 
    tornado.ioloop.IOLoop.instance().start() 


if __name__ == "__main__": 
    main() 
+0

如何连接到redis的python redis模块,有关POST处理的方法和龙卷风文档的redis文档? – 2012-03-16 22:57:56

回答

2

对于第一个问题,使用python的redis模块。

首先,从sudo easy_install redis安装redis或获取source code从安装脚本安装

上有PY-的Redis的github page文档,但如果你想开始与一些简单的,只写这2行代码:

import redis 
# if your redis was implemented properly and defaultly (eg. on 6379 port), 
# `db` you get can work now. 
db = redis.StrictRedis() 

对于第二个问题,写上MainHandler HTTP POST处理方法:

class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
     ... 

    def post(self): 
     # use handler's get_argument method to get incoming data, 
     # if eithor of them is not get, a HTTP 400 will return 
     key = self.get_argument('key') 
     value = self.get_argument('value') 
     # just like `SET` command in redis client 
     db.set(key, value) 
     # return something you want 
     self.write('Set %s - %s pair OK' % (key, value)) 

PS。您可以将db设置为先前属于您的处理程序类的属性,以便可以从self.db轻松获取该属性。

+0

谢谢你的工作。 – sue123456 2012-03-21 15:32:58

+0

所以你应该接受这个答案,否则如果你总是不能及时接受,这对你的社区表现并不好。见[this](http://meta.stackexchange.com/questions/16721/how-does-accept-rate-work)。 – Reorx 2012-03-22 03:39:47