snap2laz/server.py

67 lines
1.7 KiB
Python

#! /usr/bin/python3
from redis import Redis
from flask import Flask, redirect, url_for, request
import flask
import hashlib
import json
import os
import time
# Redis init
environ = os.environ
host = environ['DB_HOST'] if 'DB_HOST' in os.environ else "localhost"
port = environ['DB_PORT'] if 'DB_PORT' in os.environ else 6379
debug = environ['DEBUG'] if 'DEBUG' in os.environ else False
sep='**************************************'
print("\n{}\nConnecting to Redis server on {}:{}\n{}\n".format(sep,host,port,sep))
r = Redis(host="db", port=port)
# hashlib init
m = hashlib.sha256()
# Flask app init
app = Flask(__name__)
@app.before_first_request
def setup_logging():
if not app.debug:
# In production mode, add log handler to sys.stdout.
app.logger.addHandler(logging.StreamHandler(stream=sys.stdout))
app.logger.setLevel(logging.INFO)
# Routing requests
@app.route('/image',methods = ['POST', 'GET'])
def image():
try:
data = dict()
# Clean the request
if "text" in request.form:
data["text"] = request.form["text"][:256]
else :
data["text"] = ""
if "image_data" in request.form:
data["image_data"] = request.form["image_data"]
else:
raise Exception("image_data is mandatory")
m.update( bytes(time.asctime(), 'utf-8'))
hash_name = m.hexdigest()[:16]
data["hash_name"] = hash_name
# Save to queue
r.rpush("image-convert",json.dumps(data))
return( json.dumps({
"message":"ok",
"hash_name":hash_name
}) )
except Exception as e:
print("woah",e)
return( json.dumps( {"errors":[ str(e)]}))
# Run Flask
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug = True)