如何在Falcon中使用Gevents?

Ani*_*ptA 8 python asynchronous web-services falcon gevent

我正在尝试将Falcon Web框架与gevents和asyncio等异步工作者一起使用.我一直在寻找教程,但我找不到任何将gevent与falcon结合起来的方法.由于我以前从未使用gevents,我不确定如何测试这个组合.有人可以引导我参加示例或教程吗?

谢谢!:)

kva*_*uni 10

我只是想用Falcon和gevent构建一个新的网站,这是我过去所做的.我知道它有些奇怪,所以我在网上搜索并找到了你的问题.我有点惊讶没有人回应.所以,我回过头来看看我之前的代码,以下是使用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(("", port), api)  # address and port to bind to ("" is localhost), and the Falcon handler API
server.serve_forever()  # once the server is created, let it serve forever
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,最重要的诀窍在于修补猴子.除此之外,它真的非常简单.希望这有助于某人!

  • 这个设置对我来说很棒。值得注意的是,Falcon不仅可以与gevents一起使用,而且还可以在应用程序中利用诸如`spawn`,`sleep`和`Semaphore`之类的gevents构造。我用它们来创建后台工作程序,这些工作程序独立于请求驱动的代码而运行。 (2认同)