Commit 1f43be0a authored by Vladislav Rykov's avatar Vladislav Rykov
Browse files

new app, app, index views working

parent 928b04dd
from binascii import hexlify
import os
def rand_str(length):
if length % 2 == 0:
return hexlify(os.urandom(length//2))
else:
return hexlify(os.urandom(length//2 + 1))
File added
from flask import Flask, render_template, request, redirect, url_for, session from flask import Flask, render_template, request, redirect, url_for, session
import psycopg2 import psycopg2
import bcrypt import bcrypt
import misc
APP_KEY_LEN = 8
server = Flask(__name__, template_folder='templates/')
app = Flask(__name__, template_folder='templates/')
def new_user(name, password): def new_user(name, password):
suc = (True, 'User added') suc = (True, 'User added')
...@@ -29,6 +35,8 @@ def new_user(name, password): ...@@ -29,6 +35,8 @@ def new_user(name, password):
return suc return suc
def chk_user(name, password): def chk_user(name, password):
suc = (True, 'Success') suc = (True, 'Success')
try: try:
...@@ -59,11 +67,149 @@ def chk_user(name, password): ...@@ -59,11 +67,149 @@ def chk_user(name, password):
return suc return suc
@app.route('/')
def get_apps(username):
res = []
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
SELECT * FROM
applications
WHERE
username = %s
"""
cur.execute(query, (username,))
res = cur.fetchall()
except (Exception, psycopg2.DatabaseError) as error:
print('Error querying applications: ', error)
finally:
if (conn):
cur.close()
conn.close()
return res
def get_app(appkey):
res = []
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
SELECT * FROM
applications
WHERE
app_key = %s
"""
cur.execute(query, (appkey,))
res = cur.fetchall()
except (Exception, psycopg2.DatabaseError) as error:
print('Error querying applications: ', error)
finally:
if (conn):
cur.close()
conn.close()
return res
def new_app(name, desc):
suc = (True, 'App created')
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
INSERT INTO
applications
VALUES
(%s, %s, %s, %s)
"""
cur.execute(query, (name, misc.rand_str(APP_KEY_LEN), session['name'], desc))
conn.commit()
print('App created')
except (Exception, psycopg2.DatabaseError) as error:
print('Error creating app: ', error)
suc = (False, error)
finally:
if (conn):
cur.close()
conn.close()
return suc
def new_app_devs(appkey):
suc = (True, 'app_devs created')
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
CREATE TABLE dev_%s (
name VARCHAR(30) NOT NULL,
dev_id NUMERIC(3) PRIMARY KEY,
app_key VARCHAR(80),
description VARCHAR(200)
FOREIGN KEY (app_key) REFERENCES applications(app_key)
);
"""
cur.execute(query, (appkey,))
conn.commit()
print('Dev table created')
except (Exception, psycopg2.DatabaseError) as error:
print('Error creating app: ', error)
suc = (False, error)
finally:
if (conn):
cur.close()
conn.close()
return suc
def get_devs(appkey):
res = []
try:
conn = psycopg2.connect('dbname=gateway')
cur = conn.cursor()
query = """
SELECT * FROM
devs-%s
"""
cur.execute(query, (appkey,))
res = cur.fetchall()
except (Exception, psycopg2.DatabaseError) as error:
print('Error querying applications: ', error)
finally:
if (conn):
cur.close()
conn.close()
return res
@server.route('/')
def index(): def index():
if len(session['name']) > 0:
apps = get_apps(session['name'].encode('utf-8'))
print(apps)
return render_template('index.html', apps=apps)
return render_template('index.html') return render_template('index.html')
@app.route('/signup', methods=['GET', 'POST'])
@server.route('/signup', methods=['GET', 'POST'])
def signup(): def signup():
if request.method == 'GET': if request.method == 'GET':
return render_template('signup.html') return render_template('signup.html')
...@@ -83,7 +229,9 @@ def signup(): ...@@ -83,7 +229,9 @@ def signup():
return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
@server.route('/login', methods=['GET', 'POST'])
def login(): def login():
if request.method == 'GET': if request.method == 'GET':
return render_template('login.html') return render_template('login.html')
...@@ -104,16 +252,42 @@ def login(): ...@@ -104,16 +252,42 @@ def login():
return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/logout')
@server.route('/logout')
def logout(): def logout():
session.clear() session.clear()
return redirect(url_for('index')) return redirect(url_for('index'))
@app.route('/apps')
def apps(): @server.route('/new-app')
return '<h1>Manage your apps, ' + app.conf['username'] + '</h1>' def new_application():
return render_template('new-app.html')
@server.route('/app', methods=['GET', 'POST'])
def app():
if request.method == 'GET':
app = get_app(request.form['appkey'])
devs = get_devs(app[1])
return render_template('app.html', app=app, devs=devs)
else:
if request.form['appname'] == '':
error = 'Application name cannot be empty.'
return render_template('new-app.html', feedback=error)
else:
res = new_app(request.form['appname'], request.form['appdesc'])
rer = new_app_devs(request.form['appname'])
if not res[0] or not rer[0]:
return render_template('new-app.html', feedback=res[1]+'|'+rer[1])
else:
return redirect(url_for('index'))
if __name__ == '__main__': if __name__ == '__main__':
app.secret_key = 'sdjfklsjf^$654sd^#sPH' server.secret_key = 'sdjfklsjf^$654sd^#sPH'
app.run(debug = True, host='0.0.0.0') server.run(debug = True, host='0.0.0.0')
{% extends 'layout.html' %}
{% block title %} Application: {% endblock %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<p>Name: {{ app[0] }} </p>
<p>Description : {{ app[3] }} </p>
<p>app-key: {{ app[1] }} </p>
<p>Devices:</p>
{% if devs %}
<ol>
{% for dev in devs %}
<li><a href="/device?app_key={{ app[1] }}&dev={{ dev[1] }}"> {{ dev[0] }} </a></li>
{% endfor %}
</ol>
{% else %}
<p> No registed devices </p>
{% endif %}
<a href="/add-device"><button type="submit" class="btn btn-primary">Add Device</button></a>
<a href="/delete-app"><button type="submit" class="btn btn-danger" onclick="return conf();">Delete Application</button></a>
</div>
</div>
<script type="text/javascrypt">
function conf() {
return confirm("Are you sure? It will remove all devices and data.")
}
</script>
{% endblock %}
...@@ -6,13 +6,15 @@ ...@@ -6,13 +6,15 @@
<div class="row"> <div class="row">
<div class="col-md-6 col-md-offset-3"> <div class="col-md-6 col-md-offset-3">
<h2> Welcome! </h2> <h2> Welcome, {{session['name']}}! </h2>
{% if session['name'] %} {% if session['name'] %}
<h4> {{session['name']}}, explore your applications or create a new one. </h4> <h4> Explore your applications or create a new one. </h4>
<ol> <ol>
<li> App1 </li> {% for app in apps %}
<li> App2 </li> <li><a href="/apps?appkey={{ app[1] }}"> {{ app[0] }} </a></li>
{% endfor %}
</ol> </ol>
<a href="/new-app"><button class="btn btn-primary" type="submit">New Application</button></a>
{% else %} {% else %}
<p>Log in, please</p> <p>Log in, please</p>
{% endif %} {% endif %}
......
{% extends 'layout.html' %}
{% block title %} Create application: {% endblock %}
{% block content %}
<div class="row">
<div class="col-md-6 col-md-offset3">
<form action="app" method="post">
<div class="form-group">
<label>Name:</label><br>
<input type="text" id="appname" name="appname"><br>
</div>
<div class="form-group">
<label>Description:</label><br>
<textarea id="appdesc" name="appdesc" cols="40" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Create</button>
</div>
{% if feedback %}
<p class="text-danger float-right">{{ feedback }}</p>
{% endif %}
</form>
</div>
</div>
{% endblock %}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment