-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
105 lines (90 loc) · 3 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# importing Flask and other modules
from flask import Flask, request, render_template, redirect, url_for
from print_helper import *
# Flask constructor
app = Flask(__name__)
RECENT_MESSAGES = []
HOURLY_LIMIT = 12
RECENT_LIMIT = 10
def increment_counts():
'''
increments both hourly and all time counts
'''
#first all time
with open("./all_time_count.txt", "r") as file:
new_count= str(int(file.readline())+1)
with open("./all_time_count.txt", "w") as file:
file.write(new_count)
#then hourly
with open("./hourly_count.txt", "r") as file:
new_count= str(int(file.readline())+1)
with open("./hourly_count.txt", "w") as file:
file.write(new_count)
def get_hourly_count():
#try to get hourly count. if file doesn't exist, make a new one
try:
with open("./hourly_count.txt", "r") as file:
count=int(file.readline())
except FileNotFoundError:
with open("./hourly_count.txt", "w") as file:
file.write("0")
count=0
return count
def get_all_time_count():
#try to get all time count. if file doesn't exist, make a new one
try:
with open("./all_time_count.txt", "r") as file:
count=int(file.readline())
except FileNotFoundError:
with open("./all_time_count.txt", "w") as file:
file.write("0")
count=0
return count
def log_message(name, message):
with open("./message_log.txt", "a+") as file:
file.write("FROM: "+name+"\n"+message+"\n\n")
def update_recent(name, message):
message_list=[name, message]
RECENT_MESSAGES.append(message_list)
if len(RECENT_MESSAGES) > RECENT_LIMIT:
RECENT_MESSAGES.pop(0)
@app.route('/', methods=["GET", "POST"])
def name():
messages_this_hour = get_hourly_count()
if messages_this_hour >= HOURLY_LIMIT:
return render_template("too_many.html")
elif request.method == "POST":
# getting message from HTML form
name = request.form.get("name")
message = request.form.get("message")
#trim message if needed
if len(message) > 280:
message=message[:280]
if len(name) > 28:
name=name[:28]
log_message(name, message)
print_message(name,message)
increment_counts()
update_recent(name,message)
return redirect(
url_for('success'))
else:
return render_template(
"index.html",
all_time_count = get_all_time_count(),
hourly_count=messages_this_hour,
recent_list=RECENT_MESSAGES,
len=len(RECENT_MESSAGES)
)
@app.route("/success")
def success():
# access the result in the tempalte, for example {{ result.name }}
return render_template(
'success.html',
all_time_count=get_all_time_count(),
hourly_count=get_hourly_count(),
recent_list=RECENT_MESSAGES,
length=len(RECENT_MESSAGES)
)
if __name__ == '__main__':
app.run()