Changeset - f60824dd1290
[Not reviewed]
default
0 0 4
Dennis Fink - 10 years ago 2015-06-15 20:24:13
dennis.fink@c3l.lu
Added inital version
4 files changed with 120 insertions and 0 deletions:
0 comments (0 inline, 0 general)
spaceapi/__init__.py
Show inline comments
 
new file 100644
 
import json
 
import os
 
import os.path
 
import calendar
 
import base64
 
import copy
 

	
 
from datetime import datetime
 

	
 
from flask import Flask, jsonify, request, render_template
 
from flask.ext.httpauth import HTTPDigestAuth
 

	
 
config_file = os.path.abspath('config.json')
 
default_json_file = os.path.abspath('default.json')
 
last_state_file = os.path.abspath('laststate.json')
 

	
 
default_json = json.load(open(default_json_file, encoding='utf-8'))
 

	
 
if os.path.exists(last_state_file):
 
    with open(last_state_file, encoding='utf-8') as f:
 
        active_json = json.load(f)
 

	
 
    if os.path.getmtime(last_state_file) < os.path.getmtime(default_json_file):
 
        backup = copy.deepcopy(active_json)
 
        active_json.update(default_json)
 
        active_json['state']['open'] = backup['state']['open']
 
        active_json['state']['lastchange'] = backup['state']['lastchange']
 
else:
 
    active_json = copy.deepcopy(default_json)
 

	
 
app = Flask(__name__)
 
auth = HTTPDigestAuth()
 

	
 
_default_secret_key = base64.b64encode(os.urandom(32)).decode('utf-8')
 
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', _default_secret_key)
 

	
 
if not hasattr(app.config, 'from_json'):
 
    def from_json(file, silent=True):
 
        try:
 
            with open(file, encoding='utf-8') as json_file:
 
                obj = json.load(json_file)
 
        except IOError:
 
            if silent:
 
                return False
 
            raise
 

	
 
        for key in obj:
 
            if key.isupper():
 
                app.config[key] = obj[key]
 

	
 
        return True
 

	
 
    app.config.from_json = from_json
 

	
 
app.config.from_json(config_file, silent=True)
 

	
 

	
 
@auth.get_password
 
def get_pw(username):
 
    if username == app.config.get('HTTP_DIGEST_AUTH_USER'):
 
        return app.config.get('HTTP_DIGEST_AUTH_PASSWORD')
 
    return None
 

	
 

	
 
def request_wants_json():
 
    best = request.accept_mimetypes.best_match(
 
        ['application/json', 'text/html']
 
    )
 
    return best == 'application/json' and \
 
        request.accept_mimetypes[best] > \
 
        request.accept_mimetypes['text/html']
 

	
 

	
 
def save_last_state():
 

	
 
    with open(last_state_file, mode='w', encoding='utf-8') as f:
 
        json.dump(active_json, f, sort_keys=True)
 

	
 

	
 
@app.route('/')
 
def index():
 
    if request_wants_json():
 
        return jsonify(active_json)
 
    return render_template('index.html', status=active_json)
 

	
 

	
 
@app.route('/status.json')
 
def status_json():
 
    return jsonify(active_json)
 

	
 

	
 
@app.route('/set_state/<state>', methods=('PUT',))
 
@auth.login_required
 
def set_state(state):
 

	
 
    if state == 'open':
 
        active_json['state']['open'] = True
 
    elif state == 'close':
 
        active_json['state']['open'] = False
 
    else:
 
        return 400
 

	
 
    active_json['state']['lastchange'] = calendar.timegm(
 
        datetime.now().timetuple()
 
    )
 

	
 
    save_last_state()
 

	
 
    return jsonify(active_json)
spaceapi/static/closed.png
Show inline comments
 
new file 100644
 
binary diff not shown
Show images
spaceapi/static/open.png
Show inline comments
 
new file 100644
 
binary diff not shown
Show images
spaceapi/templates/index.html
Show inline comments
 
new file 100644
 
<html>
 
  <body>
 
    {% if status['state']['open'] %}
 
      <img src="{{ url_for('static', filename='open.png') }}"></img>
 
      <p>Yes, we're open!</p>
 
    {% else %}
 
      <img src="{{ url_for('static', filename='closed.png') }}"></img>
 
      <p>Sorry, we're closed!</p>
 
    {% endif %}
 
  </body>
 
</html>
0 comments (0 inline, 0 general)