Advertisement
trippyt

Webiface.py

Sep 30th, 2018
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.88 KB | None | 0 0
  1. import sys
  2. import os
  3. import AquariumLights
  4. from flask import Flask, flash, redirect, render_template, request, session, abort, jsonify, redirect, url_for
  5. from sqlalchemy.orm import sessionmaker
  6. from tabledef import *
  7. import logging
  8.  
  9. logger = logging.getLogger("AquariumLights")
  10.  
  11. lights_control = AquariumLights.LightControl()
  12.  
  13. engine = create_engine('sqlite:///tutorial.db', echo=True)
  14.  
  15. app = Flask('Flask')
  16. app.logger.setLevel(logging.DEBUG)
  17. app.logger.addHandler(logger)
  18.  
  19. class InvalidUsage(Exception):
  20.     status_code = 400
  21.  
  22.     def __init__(self, message, status_code=None, payload=None):
  23.         Exception.__init__(self)
  24.         self.message = message
  25.         if status_code is not None:
  26.             self.status_code = status_code
  27.         self.payload = payload
  28.  
  29.     def to_dict(self):
  30.         rv = dict(self.payload or ())
  31.         rv['message'] = self.message
  32.         return rv
  33.  
  34. @app.route('/login', methods=['POST'])
  35. def do_admin_login():
  36.  
  37.     POST_USERNAME = str(request.form['username'])
  38.     POST_PASSWORD = str(request.form['password'])
  39.  
  40.     Session = sessionmaker(bind=engine)
  41.     s = Session()
  42.     query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]) )
  43.     result = query.first()
  44.     if result:
  45.         session['logged_in'] = True
  46.     else:
  47.         flash('wrong password!')
  48.     return redirect(url_for('main'))
  49.  
  50. @app.route("/")
  51. def main():
  52.     if not session.get('logged_in'):
  53.         return render_template('login.html')
  54.  
  55.     app.logger.debug('hello')
  56.     templateData = {
  57.         'config_state': lights_control.get_config_state()
  58.     }
  59.     # Pass the template data into the template main.html and return it to the user
  60.     return render_template('main.html', **templateData)
  61.  
  62. # The function below is executed when someone requests a URL with the pin number and action in it:
  63. @app.route("/<key>", methods=["GET", "POST"])
  64. def handleattr(key):
  65.     if not session.get('logged_in'):
  66.         return render_template('login.html')
  67.  
  68.     value = ''
  69.  
  70.     if key == 'favicon.ico':
  71.         return 'None'
  72.  
  73.     if not hasattr(lights_control, key):
  74.         raise InvalidUsage( 'Invalid attribute name {}'.format(key) )
  75.  
  76.     if request.method == "GET":
  77.         value = lights_control.get_config_state().get(key,'Unknown')
  78.         return jsonify({'value': value})
  79.  
  80.     elif request.method == "POST":
  81.         if len(request.form.getlist('value[]')) > 0:
  82.             new_val = [i for i in request.form.getlist('value[]')]
  83.         else:
  84.             new_val = request.form.get('value',None)
  85.         setattr(lights_control, key, new_val)
  86.         return jsonify('success')
  87.  
  88. @app.route("/logout")
  89. def logout():
  90.     session['logged_in'] = False
  91.     return main()
  92.  
  93. if __name__ == "__main__":
  94.     app.debug = True
  95.     app.secret_key = os.urandom(12)
  96.     app.run(host='0.0.0.0', port=443, debug=True, ssl_context='adhoc')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement