from functools import wraps from flask import Flask from flask import render_template, send_from_directory, request, Response import json, time app = Flask(__name__) def check_auth(username, password): return username == 'davide' and password == 'pwd' def authenticate(): return Response('Could not verify access level. Please retry', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'}) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated @app.route('/') def index(): return '{"onFire": false}' @app.route('/status') @requires_auth def somehtml(): #history = [] #with open('history.json', 'r') as json_data: # history = json.load(json_data) #history = history[-15:] #for event in history: # event['time'] = epochFormat(event['time']) return render_template('status.html') @app.route('/users') @requires_auth def users(): return 'You have reached Users' @app.route('/history') @requires_auth def history(): return render_template('history.html') @app.route('/gethistory') @requires_auth def getHistory(): return send_from_directory('.', 'history.json') @app.route('/getcardinfo/') @requires_auth def getCardInfo(cardID): return send_from_directory('cards', cardID + '.json') @app.route('/addcard///') @requires_auth def addCard(cardID, name, authCode): authCode = int(authCode) data = {} data["name"] = name if authCode == 0: data["fridge"] = False data["secretTools"] = False elif authCode == 1: data["fridge"] = True data["secretTools"] = False elif authCode == 2: data["fridge"] = False data["secretTools"] = True elif authCode == 3: data["fridge"] = True data["secretTools"] = True else: return '{"status" : "error_unknownAuthCode"}' with open('cards/' + cardID + '.json', 'w') as outfile: json.dump(data, outfile) history = [] with open('history.json', 'r') as history_in: history = json.load(history_in) for event in history: if event["cardID"] == cardID: event["name"] = name with open('history.json', 'w') as history_out: json.dump(history, history_out) return '{"status": "ok"}' def epochFormat(timestamp): timeObject = time.localtime(timestamp) timeString = str(timeObject.tm_year) + '/' + str(timeObject.tm_mon) + '/' + str(timeObject.tm_mday) + ' - ' if timeObject.tm_hour < 10: timeString = timeString + '0' timeString = timeString + str(timeObject.tm_hour) + ":" if timeObject.tm_min < 10: timeString = timeString + '0' timeString = timeString + str(timeObject.tm_min) + ":" if timeObject.tm_sec < 10: timeString = timeString + '0' timeString = timeString + str(timeObject.tm_sec) return timeString