Skip to content

Instantly share code, notes, and snippets.

@auryn31
Last active Jul 10, 2020
Embed
What would you like to do?
import requests
import json
import http.server
import socketserver
from http import HTTPStatus
import redis
from datetime import datetime
from urllib.parse import urlparse
import urllib.parse as urlparse
from urllib.parse import parse_qs
from datetime import date, timedelta
def load_json(r, studio, yesterday):
dateTimeObj = datetime.now()
timestampStr = dateTimeObj.strftime("%d-%b-%Y-%H")
if yesterday == True:
yesterday = date.today() - timedelta(days=1)
timestampStr = yesterday.strftime("%d-%b-%Y-")
redis_key = studio + '-' + timestampStr + '*'
keys = []
for key in r.scan_iter(redis_key):
keys.append(key)
keys.sort()
return r.get(keys[len(keys)-1])
else:
redis_key = studio + '-' + timestampStr
print("["+timestampStr+"] Call for key: " + redis_key + " yesterday: " + str(yesterday))
a = r.get(redis_key)
if a:
return a
if yesterday:
return 'null'
x = requests.get('STUDIO_ENDPOINT?studioId='+studio)
r.set(redis_key, x.content)
return x.content
PORT = 8080
r = redis.from_url('redis://redis:6379/0', decode_components=True)
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
parsed = urlparse.urlparse(self.path)
url_parameter = parse_qs(parsed.query)
if "studio" in url_parameter:
studio = url_parameter["studio"][0]
else:
self.send_response(HTTPStatus.BAD_REQUEST)
self.end_headers()
return
yesterday = False
if "yesterday" in url_parameter:
yesterday = url_parameter["yesterday"][0] == 'True' or url_parameter["yesterday"][0] == 'true'
content = load_json(r, studio, yesterday)
if content != 'null':
self.send_response(HTTPStatus.OK)
self.end_headers()
self.wfile.write(content)
else:
self.send_response(HTTPStatus.BAD_REQUEST)
self.end_headers()
with socketserver.TCPServer(("0.0.0.0", PORT), Handler) as httpd:
print("serving at port", PORT)
print("Example call: curl localhost:8080/\?studio=1414810010")
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment