Cleaned up functions. Added extra middleware function to log endpoint being called. Added documentation to make easier to understand.
This commit is contained in:
parent
748ca28185
commit
ee79750a22
|
@ -17,8 +17,17 @@ app = Sanic(name=__name__)
|
||||||
logger = None
|
logger = None
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("request")
|
||||||
|
async def log_uri(request):
|
||||||
|
# Simple middleware to log the URI endpoint that was called
|
||||||
|
logger.info("URI called: {0}".format(request.url))
|
||||||
|
|
||||||
|
|
||||||
@app.middleware("request")
|
@app.middleware("request")
|
||||||
async def attach_db_connectors(request):
|
async def attach_db_connectors(request):
|
||||||
|
# We will check to see if our redis pool has been created
|
||||||
|
# If you have access to the app object, you can set app.config directly
|
||||||
|
# If you don't have access to the app object, you can use request.app
|
||||||
if not hasattr(request.app.config, "REDIS"):
|
if not hasattr(request.app.config, "REDIS"):
|
||||||
logger.info("Setting up connection to Redis Cache")
|
logger.info("Setting up connection to Redis Cache")
|
||||||
request.app.config.REDIS = await aioredis.create_pool((app.config.REDIS_HOST, int(app.config.REDIS_PORT)),
|
request.app.config.REDIS = await aioredis.create_pool((app.config.REDIS_HOST, int(app.config.REDIS_PORT)),
|
||||||
|
@ -26,6 +35,7 @@ async def attach_db_connectors(request):
|
||||||
maxsize=int(app.config.REDIS_MAXPOOL),
|
maxsize=int(app.config.REDIS_MAXPOOL),
|
||||||
password=app.config.REDIS_PASS)
|
password=app.config.REDIS_PASS)
|
||||||
# Just put the db objects in the request for easier access
|
# Just put the db objects in the request for easier access
|
||||||
|
logger.info("Passing pool to request object")
|
||||||
request["redis"] = request.app.config.REDIS
|
request["redis"] = request.app.config.REDIS
|
||||||
|
|
||||||
|
|
||||||
|
@ -40,7 +50,6 @@ async def access_state(request, user_id):
|
||||||
# Then state object is not in redis
|
# Then state object is not in redis
|
||||||
logger.critical("Unable to find user_data in cache.")
|
logger.critical("Unable to find user_data in cache.")
|
||||||
return sanic.response.HTTPResponse({"msg": "User state not found"}, status=404)
|
return sanic.response.HTTPResponse({"msg": "User state not found"}, status=404)
|
||||||
|
|
||||||
except aioredis.ProtocolError:
|
except aioredis.ProtocolError:
|
||||||
logger.critical("Unable to connect to state cache")
|
logger.critical("Unable to connect to state cache")
|
||||||
return sanic.response.HTTPResponse({"msg": "Internal Server Error"}, status=500)
|
return sanic.response.HTTPResponse({"msg": "Internal Server Error"}, status=500)
|
||||||
|
@ -49,13 +58,14 @@ async def access_state(request, user_id):
|
||||||
@app.route("/state/<user_id>/push", methods=["POST"])
|
@app.route("/state/<user_id>/push", methods=["POST"])
|
||||||
async def set_state(request, user_id):
|
async def set_state(request, user_id):
|
||||||
try:
|
try:
|
||||||
|
# Pull a connection from the pool
|
||||||
with await request["redis"] as redis_conn:
|
with await request["redis"] as redis_conn:
|
||||||
# Set the value in cache to your new value
|
# Set the value in cache to your new value
|
||||||
await redis_conn.set(user_id, json.dumps(request.json), expire=1800)
|
await redis_conn.set(user_id, json.dumps(request.json), expire=1800)
|
||||||
logger.info("Successfully retrieved from cache")
|
logger.info("Successfully retrieved from cache")
|
||||||
return sanic.response.HTTPResponse({"msg": "Successfully pushed state to cache"})
|
return sanic.response.HTTPResponse({"msg": "Successfully pushed state to cache"})
|
||||||
except aioredis.ProtocolError:
|
except aioredis.ProtocolError:
|
||||||
logger.critical("UNable to connect to state cache")
|
logger.critical("Unable to connect to state cache")
|
||||||
return sanic.response.HTTPResponse({"msg": "Interal Server Error"}, status=500)
|
return sanic.response.HTTPResponse({"msg": "Interal Server Error"}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
@ -64,33 +74,36 @@ def configure():
|
||||||
env_vars = [os.environ.get(v, None) for v in ENV_VARS]
|
env_vars = [os.environ.get(v, None) for v in ENV_VARS]
|
||||||
if not all(env_vars):
|
if not all(env_vars):
|
||||||
# Send back environment variables that were not set
|
# Send back environment variables that were not set
|
||||||
return False, [ENV_VARS[i] for i, flag in env_vars if not flag]
|
return False, ", ".join([ENV_VARS[i] for i, flag in env_vars if not flag])
|
||||||
else:
|
else:
|
||||||
|
# Add all the env vars to our app config
|
||||||
app.config.update({k: v for k, v in zip(ENV_VARS, env_vars)})
|
app.config.update({k: v for k, v in zip(ENV_VARS, env_vars)})
|
||||||
setup_logging()
|
setup_logging()
|
||||||
logging.info("Configuraiton complete")
|
return True, None
|
||||||
return True, []
|
|
||||||
|
|
||||||
def setup_logging():
|
def setup_logging():
|
||||||
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
|
logging_format = "[%(asctime)s] %(process)d-%(levelname)s "
|
||||||
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
|
logging_format += "%(module)s::%(funcName)s():l%(lineno)d: "
|
||||||
logging_format += "%(message)s"
|
logging_format += "%(message)s"
|
||||||
|
|
||||||
print(app.config.APP_LOGFILE)
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
filename=app.config.APP_LOGFILE,
|
filename=app.config.APP_LOGFILE,
|
||||||
format=logging_format,
|
format=logging_format,
|
||||||
level=logging.DEBUG
|
level=logging.DEBUG)
|
||||||
)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
result, missing = configure()
|
def main(result, missing):
|
||||||
logger = logging.getLogger()
|
|
||||||
if result:
|
if result:
|
||||||
try:
|
try:
|
||||||
app.run(host="0.0.0.0", port=8080, debug=True)
|
app.run(host="0.0.0.0", port=8080, debug=True)
|
||||||
except:
|
except:
|
||||||
logger.critical("User killed server. Closing")
|
logging.critical("User killed server. Closing")
|
||||||
else:
|
else:
|
||||||
need_string = ", ".join(missing)
|
logging.critical("Unable to start. Missing environment variables [{0}]".format(missing))
|
||||||
logger.critical("Unable to start. Missing environment variables [{0}]".format(need_string))
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
result, missing = configure()
|
||||||
|
logger = logging.getLogger()
|
||||||
|
main(result, missing)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user