semi working flask version

This commit is contained in:
Anika 2024-02-12 12:56:15 +01:00
parent 2ba8ae8772
commit 08a85501ce
12 changed files with 11436 additions and 114 deletions

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
### VirtualEnv ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json

Binary file not shown.

22
alarms.json Normal file
View File

@ -0,0 +1,22 @@
[
{
"datetime": "12.03.2025 11:00",
"message": "lj\u00f6sd"
},
{
"datetime": "12.03.2025 11:00",
"message": "lj\u00f6sd"
},
{
"datetime": "11.02.2024 23:33",
"message": ""
},
{
"datetime": "12.03.2022 11:00",
"message": "lj\u00f6sd"
},
{
"datetime": "11.02.2024 23:23",
"message": "lj\u00f6sd"
}
]

View File

@ -1,7 +0,0 @@
02/08/24 15:10:56 ~ ters
02/08/24 14:53:07 ~ test
02/08/24 15:53:07 ~ test
02/08/24 15:21:32 ~ asdfjklö sdfjkl
02/08/24 15:27:44 ~ juhu
02/08/24 15:39:49 ~ lds
02/08/24 15:43:17 ~ asfhk ksadf

104
fete.py
View File

@ -1,104 +0,0 @@
import cmd
import os
import sys
import time
import subprocess
from datetime import datetime, timedelta
alarms_queue = list()
class Fete(cmd.Cmd):
intro = "Willkommen zum Logging und Alarm Skript Ihres Vertrauens. \nBei Fragen help oder ? benutzen."
use_rawinput = False
def do_log(self, toLog):
"Log message with current timestamp"
log = open("log.txt", "a")
datetime_obj = datetime.now()
log_message = datetime_obj.strftime("%x") +", " + datetime_obj.strftime("%X") +" Uhr: "+ toLog
print( log_message )
# log als was besseres als txt, aber meh
log.write(log_message + "\n")
def do_alarm(self, args):
"set an alarm in x minutes for y, example: alarm 30 Cocktail wants stuff"
alarms = open("alarms.txt", "a")
args_arr = args.split()
print("\a")
if len(args_arr) < 2:
print("Heeer! Dir fehlt ein Argument. ")
return
try:
delta = int(args_arr[0])
except ValueError:
print("Das erste Argument muss ne Ganzzahl sein!")
return
args_arr.pop(0)
text = ' '.join(args_arr)
alarm_time = datetime.now() + timedelta(minutes = delta)
print("Alarm set for " + alarm_time.strftime("%X") + " " + text)
alarms.write(alarm_time.strftime("%x") + " " +alarm_time.strftime("%X") + " ~ " + text + "\n")
global alarms_queue
alarms_queue.append((alarm_time,text))
def do_readAlarms(self, minutes):
"read alarms from file into alarm queue that haven't happened or should have happened in the last x minutes (default=5)"
try:
if minutes:
delta = int(minutes)
else:
delta = 5
except ValueError:
print("Zeit bitte in ganzen Minuten!")
return
earliest_alarm_time = datetime.now() - timedelta(minutes = delta)
alarms = open("alarms.txt", "r").readlines()
for line in alarms:
line_sep = line.split(" ~ ")
alarm_time = datetime.strptime(line_sep[0], "%m/%d/%y %H:%M:%S")
if alarm_time > earliest_alarm_time:
global alarms_queue
alarms_queue.append((alarm_time,line_sep[1]))
class NonblockingStdin:
def __init__(self, stdin, idle_callback):
self._stdin = stdin
self._idle_callback = idle_callback
os.set_blocking(self._stdin.fileno(), False)
def readline(self):
buffer = ""
char = self._stdin.read(1)
while char != "\n":
buffer += char
char = self._stdin.read(1)
if char == "":
time.sleep(0.1)
self._idle_callback()
return buffer
def alarm():
alarms_copy = alarms_queue
for alarm_read in alarms_copy:
if datetime.now() >= alarm_read[0]:
subprocess.call(['mpv', './alarm.mp3'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("\n\n")
print(alarm_read[1])
print("")
alarms_queue.remove(alarm_read)
def main():
wrapped = NonblockingStdin(sys.stdin, alarm)
fete = Fete(stdin=wrapped)
fete.cmdloop()
if __name__ == '__main__':
main()

View File

@ -1,3 +0,0 @@
02/07/24, 19:18:19Uhr: 02/08/24, 15:18:54Uhr: hilfe, ich habe mein Pasenbrot vergessen
02/08/24, 15:26:12 Uhr: Es ist dumm nen Alarm zusetzen bevor man die alten eingelesen hat
02/08/24, 15:26:52 Uhr: außerdem, doppelte leerzeichen als trennsymbol, das kann nur schief gehen

6
logs.json Normal file
View File

@ -0,0 +1,6 @@
[
{
"datetime": "11.02.2024 22:58",
"message": "Nice"
}
]

11173
static/css/style.css Normal file

File diff suppressed because it is too large Load Diff

40
templates/base.html Normal file
View File

@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-light">
<a class="navbar-brand" href="{{ url_for('index')}}">FlaskBlog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{url_for('create')}}">New Post</a>
</li>
</ul>
</div>
</nav>
<div class="container">
{% block content %} {% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

23
templates/create.html Normal file
View File

@ -0,0 +1,23 @@
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %} Create a New Post {% endblock %}</h1>
<form method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title"
placeholder="Post title" class="form-control"
value="{{ request.form['title'] }}"></input>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="content" placeholder="Post content"
class="form-control">{{ request.form['content'] }}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
{% endblock %}

81
templates/index.html Normal file
View File

@ -0,0 +1,81 @@
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %} Partey! {% endblock %}</h1>
<div class="grid-container">
<div class="savedLogs">
<h3>Logs</h3>
{% for log in logs %}
<div>
{{ log.datetime }}: {{ log.message }}
</div>
{% endfor %}
</div>
<div class="savedAlarms">
<h3>Upcoming Alarms</h3>
{% for alarm in alarms %}
<div>
{{ alarm.datetime }}: {{ alarm.message }}
</div>
{% endfor %}
</div>
<div class="log">
<form method="post" action="/sendLog">
<div class="form-group">
<label for="logMessage">logMessage</label>
<input type="text" name="logMessage"
class="form-control"
value="{{ request.form['logMessage'] }}"></input>
<input type="submit" id="saveLog" value="Speichern"/>
</div>
</form>
</div>
<div class="alarms">
<form method="post" action="/setAlarm">
<div class="form-group">
<label for="time">Time</label>
<input type="datetime-local" name="datetime"
class="form-control"
value="{{ request.form['datetime'] }}"></input>
<label for="alarmMessage">alarmMessage</label>
<input type="text" name="alarmMessage"
class="form-control"
value="{{ request.form['alarmMessage'] }}"></input>
<input type="submit" id="saveAlarm" value="Speichern"/>
</div>
</form>
</div>
<div>
<h3>Previous Alarm</h3>
Script runs once for whatever reason????
<script>
async function getAlarms(){
const response = await fetch("http://127.0.0.1:5000/alarms");
const alarms = await response.json();
return alarms
}
alarms = getAlarms();
function checkAlarms(){
console.log("hello")
for(alarm in alarms){
if(Date(alarm.datetime) <=new Date()){
console.log("ALARM!");
alert(alarm.message);
// post alerting alarm
}
}
setTimeout(checkAlarms, 15000);
}
checkAlarms();
</script>
{% for alarm in previousAlarms %}
<div>
{{ alarm.datetime }}: {{ alarm.message }}
</div>
{% endfor %}
</div>
</div>
{% endblock %}

78
test.py Normal file
View File

@ -0,0 +1,78 @@
import json
from flask import request, Flask, render_template
from datetime import datetime, timedelta
app = Flask(__name__)
activeAlarms = list()
previousAlarms = list()
logs = list()
def preprocess():
logsFile = json.load(open("./logs.json"))
alarmsFile = json.load(open("./alarms.json"))
for alarm in alarmsFile:
if datetime.strptime(alarm['datetime'],"%d.%m.%Y %H:%M") <= datetime.now()-timedelta(minutes=2):
previousAlarms.append(alarm)
else:
activeAlarms.append(alarm)
for log in logsFile:
logs.append(log)
@app.route("/", methods=('GET', 'POST'))
def index():
# preprocesing in andere Methode, alarm sortieren nach Zeitpunkt
# alarm.txt alle alarme, alarm.json alle, die noch nicht behandelt wurden
# alle alarme in alarme.json -> preprocessing wie in die Listen
#alarms = open("alarms.txt").readlines()
#logs = open("alarms.txt").readlines()
preprocess()
return render_template('index.html', logs = logs, alarms = activeAlarms, previousAlarms=previousAlarms)
@app.route('/setAlarm', methods=('GET', 'POST'))
def setAlarm():
if request.method == 'POST':
time = datetime.fromisoformat(request.form['datetime']).strftime("%d.%m.%Y %H:%M")
print(time)
content = request.form['alarmMessage']
activeAlarms.append({'datetime':time,'message':content})
allAlarms = activeAlarms+previousAlarms
with open('alarms.json', 'w') as f:
json.dump(allAlarms, f, indent=2)
# Closing file
f.close()
return render_template('index.html', logs = logs, alarms = activeAlarms, previousAlarms=previousAlarms)
@app.route('/sendLog', methods=('GET', 'POST'))
def sendLog():
if request.method == 'POST':
content = request.form['logMessage']
log = {'datetime':datetime.now().strftime("%d.%m.%Y %H:%M"),'message':content}
logs.append(log)
with open('logs.json', 'w') as f:
json.dump(logs, f, indent=2)
# Closing file
f.close()
return render_template('index.html', logs = logs, alarms = activeAlarms, previousAlarms=previousAlarms)
@app.route('/alarms', methods=('GET','POST'))
def alarm():
if request.method == 'GET':
return json.dumps(activeAlarms)
if request.method == 'POST':
print('ALARM')
# gets alerting alarm, move to previous alarms and remove from active
@app.route('/about')
def create():
return 'The about page'