Created
May 15, 2020 11:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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