Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Gevents with Falcon?

I am trying to use Falcon web framework with async workers like gevents and asyncio. I have been looking around for tutorials, but I haven't been able to find any which combine implementation of gevent with falcon. Since I have never used gevents before, I am not sure how to go around testing this combination. Can someone guide me to an example or a tutorial?

Thank you! :)

like image 360
AnisH_GuptA Avatar asked May 09 '16 14:05

AnisH_GuptA


1 Answers

I was just looking to build a new website with Falcon and gevent, something I had done in the past. 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):

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!

like image 70
kvaruni Avatar answered Nov 16 '22 02:11

kvaruni