【问题标题】:How to save user input data to redis using tornado python如何使用tornado python将用户输入数据保存到redis
【发布时间】:2012-04-02 10:56:33
【问题描述】:

我正在使用 tornado、python 编写一个小型 Web 应用程序,下面是我的代码。我在 python 中有一个带有 2 个文本字段的 html 表单,现在我想将输入表单作为文本字段并存储在 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()

【问题讨论】:

  • 连接redis的python redis模块、方法的redis文档和关于POST处理的tornado文档怎么样?

标签: python redis tornado


【解决方案1】:

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

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

py-redis 的github page 上有文档,但是如果你想从简单的开始,就写这两行代码:

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

附言。您可以将 db 设置为之前的处理程序类的属性,以便可以轻松地从 self.db 获取。

【讨论】:

  • 所以你应该接受这个答案,否则如果你总是不及时接受,对你的社区表现不利。见this
猜你喜欢
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 2017-05-21
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 2018-02-21
相关资源
最近更新 更多