Skip to content

Instantly share code, notes, and snippets.

@gurayops
Created May 15, 2020 11:51
Show Gist options
  • Save gurayops/ff2d8e12a3d0faaa29ba802393e23806 to your computer and use it in GitHub Desktop.
Save gurayops/ff2d8e12a3d0faaa29ba802393e23806 to your computer and use it in GitHub Desktop.
A pseudo-random number API with Python and Falcon, serving by Gunicorn inside the code.
from gunicorn.app.base import BaseApplication
import falcon
import random
import os
import time
waitTime = int(os.environ.get('WAIT_TIME', '2'))
class RandomGenerator(object):
def on_get(self, request, response):
time.sleep(waitTime)
number = random.randint(0, 100)
result = {'lowerLimit': 0, 'higherLimit': 100, 'number': number}
response.media = result
api = falcon.API()
api.add_route('/number', RandomGenerator())
class StandaloneRandomNumberAPI(BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == "__main__":
options = {
'bind': '%s:%s' % ('0.0.0.0', '80'),
'workers': 4,
}
StandaloneRandomNumberAPI(api, options).run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment