added some settings functionality that's stored in db as json

master
Kostanjevec 2022-06-23 15:59:55 +02:00
parent da0bba6a98
commit bb2b1c44d0
2 changed files with 76 additions and 0 deletions

59
settings.py 100644
View File

@ -0,0 +1,59 @@
from flask import flash, redirect, render_template, url_for, Blueprint, request, session
from create_db import User, get_session
import json
bp = Blueprint('settings', __name__, url_prefix='/settings')
dbsession = get_session()
def get_settings(user_id):
"""get settings from db, turns it into a dict and returns it"""
user = dbsession.query(User).get(user_id)
settings_db = user.settings
if settings_db == "":
#userji se zaenkrat generirajo brez settingsov aka empty string, zato dodamo te defaulte
settings_dict = {
"max_new" : 5,
"max_due" : 5,
"max_shared" : 5,
}
else:
settings_dict = json.loads(settings_db)
print("this is it: ", settings_dict)
return settings_dict
@bp.route("/save_settings", methods=["GET", "POST"])
def save_settings():
"""takes a dict of settings turns it into json and updates the database with it"""
user_id = session['user_id']
username = session['username']
if request.method == "GET":
settings_old = get_settings(user_id)
return render_template("settings.html", username=username, settings=settings_old)
if request.method == "POST":
print('this is the form ', request.form)
#request form stuff
settings_dict = {
"max_new" : request.form.get('max_new', False),
"max_due" : request.form.get('max_due', False),
"max_shared" : request.form.get('max_shared', False),
}
print('this is the dict: ', settings_dict)
settings_json = json.dumps(settings_dict)
print('this is the json: ', settings_json)
user = dbsession.query(User).get(user_id)
user.settings = settings_json
dbsession.commit()
dbsession.close()
flash("settings updated")
return render_template("settings.html", username=username, settings=settings_dict)

View File

@ -0,0 +1,17 @@
{% extends 'base.html' %}
quantity
{% block header %}
<head>Settings</head>
{% endblock %}
{% block content %}
<form method="post" action={{ url_for('settings.save_settings') }}>
<label for="quantity">Maximum new cards per session</label>
<input type="number" id="quantity" name="max_new" value= '{{ settings['max_new'] }}' min="0" required="required">
<label for="quantity">Maximum seen cards per session</label>
<input type="number" id="quantity" name="max_due" value='{{ settings['max_due'] }}' min="0" required="required">
<label for="quantity">Maximum shared cards per session</label>
<input type="number" id="quantity" name="max_shared" value='{{ settings['max_shared'] }}' min="0" required="required">
<input type="submit" value="Save">
</form>
{% endblock %}