snap2laz/server.py

84 lines
2.2 KiB
Python
Raw Permalink Normal View History

2020-10-21 12:39:48 +00:00
#! /usr/bin/python3
from redis import Redis
from flask import Flask, redirect, url_for, request
import flask
2020-10-21 12:39:48 +00:00
import hashlib
import json
import os
2020-10-21 12:39:48 +00:00
import time
2020-11-05 08:49:18 +00:00
import sys
2020-10-21 12:39:48 +00:00
# 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))
2020-11-05 08:49:18 +00:00
r = Redis(host=host, port=port)
# hashlib init
2020-10-21 12:39:48 +00:00
m = hashlib.sha256()
# Flask app init
app = Flask(__name__)
2023-07-25 23:28:19 +00:00
#
# @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
2020-10-21 12:39:48 +00:00
@app.route('/image',methods = ['POST', 'GET'])
def image():
try:
data = dict()
2023-07-25 23:28:19 +00:00
print("Received request")
2020-10-21 12:39:48 +00:00
# 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)]}))
@app.route('/hash_name/<hash_name>',methods = ['GET'])
def hash_name(hash_name):
try:
item = json.loads(r.hget("images",hash_name))
if not item:
raise Exception("This image is not available now. You might need to wait a bit more?")
return( json.dumps({
"message":"ok",
"points_list":item["points_list"]
}) )
except Exception as e:
print("woah",e)
return( json.dumps( {"errors":[ str(e)]}))
# Run Flask
2020-10-21 12:39:48 +00:00
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug = True)