通过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   星河赵  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2020-09-28 如何让nginx 显示文件夹目录
2018-09-28 Django admin 继承user表后密码为明文,继承UserAdmin,重写其方法

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示