简体   繁体   English

如何在 Falcon 中使用 Gevents?

[英]How to use Gevents with Falcon?

I am trying to use Falcon web framework with async workers like gevents and asyncio.我正在尝试将 Falcon Web 框架与像 gevents 和 asyncio 这样的异步工作者一起使用。 I have been looking around for tutorials, but I haven't been able to find any which combine implementation of gevent with falcon.我一直在寻找教程,但我一直找不到任何将 gevent 的实现与 falcon 结合起来的教程。 Since I have never used gevents before, I am not sure how to go around testing this combination.由于我以前从未使用过 gevents,因此我不确定如何测试这种组合。 Can someone guide me to an example or a tutorial?有人可以指导我查看示例或教程吗?

Thank you!谢谢! :) :)

I was just looking to build a new website with Falcon and gevent, something I had done in the past.我只是想用 Falcon 和 gevent 建立一个新网站,这是我过去做过的事情。 I knew that there was something odd about it, so I searched online and found your question.我知道它有些奇怪,所以我在网上搜索并找到了你的问题。 I'm somewhat surprised no one has responded yet.我有点惊讶还没有人回应。 So, I went back to have a look at my earlier code and the following is the basic skeleton to get up and running with Falcon and gevent (which makes for a very fast framework):所以,我回去查看我之前的代码,以下是使用 Falcon 和 gevent 启动和运行的基本框架(这构成了一个非常快速的框架):

from gevent import monkey, pywsgi  # import the monkey for some patching as well as the WSGI server
monkey.patch_all()  # make sure to do the monkey-patching before loading the falcon package!
import falcon  # once the patching is done, we can load the Falcon package


class Handler:  # create a basic handler class with methods to deal with HTTP GET, PUT, and DELETE methods
    def on_get(self, request, response):
        response.status = falcon.HTTP_200
        response.content_type = "application/json"
        response.body = '{"message": "HTTP GET method used"}'

    def on_post(self, request, response):
        response.status = falcon.HTTP_404
        response.content_type = "application/json"
        response.body = '{"message": "POST method is not supported"}'

    def on_put(self, request, response):
        response.status = falcon.HTTP_200
        response.content_type = "application/json"
        response.body = '{"message": "HTTP PUT method used"}'

    def on_delete(self, request, response):
        response.status = falcon.HTTP_200
        response.content_type = "application/json"
        response.body = '{"message": "HTTP DELETE method used"}'

api = falcon.API()
api.add_route("/", Handler())  # set the handler for dealing with HTTP methods; you may want add_sink for a catch-all
port = 8080
server = pywsgi.WSGIServer(("localhost", port), api)  # address and port to bind, and the Falcon handler API
server.serve_forever()  # once the server is created, let it serve forever

As you can see, the big trick is in the monkey-patching.如您所见,最大的技巧在于猴子补丁。 Other than that, it really is quite straightforward.除此之外,它真的很简单。 Hope this helps someone!希望这可以帮助某人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM