通过torndao 起一个web服务

需要安装包

tornado==6.4.1
redis==4.3.3

示例代码

import tornado.ioloop
import tornado.web
from redis.asyncio import Redis


class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        key = self.get_argument("key", "default_key")
        value = await self.application.redis.get(key)
        if value:
            self.write(f"Value for {key}: {value.decode('utf-8')}")
        else:
            self.write(f"No value found for {key}")

    async def post(self):
        key = self.get_argument("key")
        value = self.get_argument("value")
        await self.application.redis.set(key, value)
        self.write(f"Stored {key}: {value}")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
        ]
        settings = {
            "debug": True
        }
        super().__init__(handlers, **settings)
        self.redis = Redis(host='localhost', port=6379, db=0)


def main():
    app = Application()
    app.listen(8888)
    print("Server started on http://localhost:8888")
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()

 

4. 使用 curl 发送 POST 请求来存储数据,例如:

curl -X POST "http://localhost:8888" -d "key=mykey&value=myvalue"

然后,您可以通过 GET 请求来检索这个值:

curl "http://localhost:8888?key=mykey"

 

posted on 2024-09-28 10:53  星河赵  阅读(4)  评论(0编辑  收藏  举报

导航