Datenbank hinzugefügt, Preisen werden eingetragen, Statusmeldungen werden gezeigt

This commit is contained in:
Tim Gröger 2019-01-14 00:25:25 +01:00
parent efd047fc48
commit 073676799f
7 changed files with 120 additions and 54 deletions

View File

@ -1,4 +1,4 @@
from flask import Flask from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
@ -7,4 +7,5 @@ app.config['SECRET_KEY'] = '0a657b97ef546da90b2db91862ad4e29'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app) db = SQLAlchemy(app)
from geruecht import routes from geruecht import routes

View File

@ -1,5 +1,5 @@
from geruecht import db from geruecht import db
from threading import Timer
class User(db.Model): class User(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
@ -8,6 +8,38 @@ class User(db.Model):
def add(self, value): def add(self, value):
self.sum += value self.sum += value
def storner(self, value):
self.sum = self.sum - value
def __repr__(self): def __repr__(self):
return f"User('{self.username}', '{self.sum}')" return f"User('{self.username}', '{self.sum}')"
class History:
history = []
user = None
def __init__(self, history, user, value):
self.history=history
self.history.append(self)
self.user = user
self.value = value
self.timer = Timer(60, self.kill)
self.timer.start()
def exec(self):
self.timer.cancel()
User.query.filter_by(username=self.user.username).first().storner(self.value)
self.kill()
def kill(self):
print("{} deledet from history".format(self.user))
self.history.remove(self)
print(self.history)
'''
def __repr__(self):
print(f'self:{self}, history:{self.history}, user:{self.user}, value:{self.value}')
def __str__(self):
print(f'self:{self}, history:{self.history}, user:{self.user}, value:{self.value}')
'''

View File

@ -1,27 +1,66 @@
from flask import render_template, url_for, redirect, flash, jsonify from flask import render_template, url_for, redirect, flash, jsonify, g
from geruecht import app, db from geruecht import app, db
from geruecht.forms import RegistrationForm from geruecht.forms import RegistrationForm
from geruecht.model import User from geruecht.model import User, History
import flask_sijax
import os, sys
users = [ path = os.path.join('.', os.path.dirname(__file__), '../')
{ sys.path.append(path)
'name': 'Corey Schafer',
'sum': '20€' # The path where you want the extension to create the needed javascript files
}, # DON'T put any of your files in this directory, because they'll be deleted!
{ app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
'name': 'Tim Gröger',
'sum': '10€' # You need to point Sijax to the json2.js library if you want to support
}, # browsers that don't support JSON natively (like IE <= 7)
{ app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'name': 'Franziska Bobbe',
'sum': '5,80€' flask_sijax.Sijax(app)
}
] history = []
@app.route("/", methods=['GET', 'POST']) @flask_sijax.route(app, "/", methods=['GET', 'POST'])
@app.route("/home", methods=['GET', 'POST']) @flask_sijax.route(app, "/home", methods=['GET', 'POST'])
def home(): def home():
def add(obj_response, username, value):
user_2 = User.query.filter_by(username=username).first()
print(user_2)
print(user_2.id)
user_2.add(value)
print(user_2)
db.session.commit()
print(obj_response, username, value)
History(history=history, user=user_2, value=value)
print(history)
obj_response.html('div#flash', f'{user_2.username} wurde {"%.2f"%value} € hinzugefügt')
obj_response.attr('div#flash', "class", "alert alert-success")
obj_response.html(f'#{user_2.id}-sum', str("%.2f" % user_2.sum + ""))
def storner(obj_response):
try:
obj = history[len(history)-1]
user_2 = User.query.filter_by(username=obj.user.username).first()
print("{} {}".format(obj.user, obj.value))
obj.exec()
print(history)
print(user_2)
db.session.commit()
obj_response.html('div#flash', f'{"%.2f"%obj.value} wurden von {user_2.username} storniert')
obj_response.attr('div#flash', "class", "alert alert-success")
obj_response.html(f'#{user_2.id}-sum', str("%.2f" % user_2.sum + ""))
except IndexError:
print("history: {} is empty".format(history))
obj_response.html('div#flash', "Der Timer ist abgelaufen!! Die Stornierliste ist leer!! Falls es was wichtiges ist, melde dich beim Finanzer oder Administrator!!")
obj_response.attr('div#flash', "class", "alert alert-error")
if g.sijax.is_sijax_request:
g.sijax.register_callback('add', add)
g.sijax.register_callback('storner', storner)
return g.sijax.process_request()
form = RegistrationForm() form = RegistrationForm()
if form.validate_on_submit(): if form.validate_on_submit():
user = User(username=form.username.data) user = User(username=form.username.data)
@ -31,16 +70,6 @@ def home():
return redirect(url_for('home')) return redirect(url_for('home'))
return render_template('home.html', users=User.query.all(), form=form) return render_template('home.html', users=User.query.all(), form=form)
@flask_sijax.route(app, "/about")
@app.route("/<string:username>/add-<int:value>", methods=['POST'])
def add(username, value):
user = User.query.filter_by(username=username).first()
user.add(value)
db.session.commit()
flash(f'{username} wurde {value}€ hinzugefügt', 'success')
return jsonify({'data': user.sum})
@app.route("/about")
def about(): def about():
return render_template('about.html', title='about') return render_template('about.html', title='about')

View File

@ -36,6 +36,10 @@ body {
color: black; color: black;
} }
.blue-button:active {
transform: translateY(4px);
}
.first { .first {
float: left;; float: left;;
margin-left: 10%; margin-left: 10%;
@ -81,6 +85,10 @@ body {
color: white; color: white;
} }
.button:active {
transform: translateY(4px);
}
.bottombar { .bottombar {
background-color: #077BCB; background-color: #077BCB;
overflow: hidden; overflow: hidden;

View File

@ -5,40 +5,28 @@
<div class="g-item"> <div class="g-item">
<p>{{ user.username }}</p> <p>{{ user.username }}</p>
</div> </div>
<button class="g-item button" id="{{ user.id }}-2"> <div class="g-item button" id="{{ user.id }}-2" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 2]);">
<p>+2 &euro;</p> <p>+2 &euro;</p>
</button> </div>
<div class="g-item button" id="{{ user.username }}-1"> <div class="g-item button" id="{{ user.it }}-1" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 1]);">
<p>+1 &euro;</p> <p>+1 &euro;</p>
</div> </div>
<div class="g-item button" id="{{ user.username }}-050"> <div class="g-item button" id="{{ user.id }}-050" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 0.5]);">
<p>+0,5 &euro;</p> <p>+0,5 &euro;</p>
</div> </div>
<div class="g-item button" id="{{ user.username }}-040"> <div class="g-item button" id="{{ user.id }}-040" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 0.4]);">
<p>+0,4 &euro;</p> <p>+0,4 &euro;</p>
</div> </div>
<div class="g-item button" id="{{ user.username }}-020"> <div class="g-item button" id="{{ user.id }}-020" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 0.2]);">
<p>+0,2 &euro;</p> <p>+0,2 &euro;</p>
</div> </div>
<div class="g-item button" id="{{ user.username }}-010"> <div class="g-item button" id="{{ user.id }}-010" href="javascript://" onclick="Sijax.request('add', ['{{ user.username }}', 0.1]);">
<p>+0,1 &euro;</p> <p>+0,1 &euro;</p>
</div> </div>
<div class="g-item"> <div class="g-item">
<p id="{{ user.id }}-sum">{{ user.sum }}</p> <p id="{{ user.id }}-sum">{{ "%.2f"%user.sum }}</p>
</div> </div>
</div> </div>
<script type="text/javascript">
$(document).ready(function(){
$("#{{ user.id }}-2").click(function(){
$("#{{ user.id }}-sum").text("Hello world!");
});
});
</script>
<!-- url: "{{ url_for('add', username=user.username, value=2) }}",
type: "POST",
success: function(resp){
$('div#{{ user.id }}-sum').text(resp.data);
} -->
{% endfor %} {% endfor %}
{% endblock %} {% endblock %}

View File

@ -13,6 +13,13 @@
<link href="{{ url_for('static', filename='master.css') }}", type="text/css", rel="stylesheet"> <link href="{{ url_for('static', filename='master.css') }}", type="text/css", rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}
</script>
</head> </head>
<body> <body>
<div class="topnav"> <div class="topnav">
@ -42,7 +49,9 @@
{% endfor %} {% endfor %}
{% endif %} {% endif %}
{% endwith %} {% endwith %}
<div id="flash"></div>
<div class="bottombar-element"> <div class="bottombar-element">
{% if form %}
<form method="POST" action=""> <form method="POST" action="">
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
<fieldset class="form-group"> <fieldset class="form-group">
@ -56,14 +65,13 @@
{{ form.submit(class="blue-button no-mg") }} {{ form.submit(class="blue-button no-mg") }}
</div> </div>
</form> </form>
{% endif %}
</div> </div>
<div class="right blue-button buttombar-element no-mg no-pd"> <div class="right blue-button buttombar-element no-mg no-pd" href="javascript://" onclick="Sijax.request('storner');">
<p>Stornieren</p> <p>Stornieren</p>
</div> </div>
</div> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<!-- Optional JavaScript --> <!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS <!-- jQuery first, then Popper.js, then Bootstrap JS