-
Notifications
You must be signed in to change notification settings - Fork 1
/
budget.py
205 lines (179 loc) · 6.41 KB
/
budget.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#erl67
FDEBUG = True
import os, re, json, pickle
from sys import stderr
from collections import OrderedDict
from functools import wraps
from flask import Flask, g, send_from_directory, flash, render_template, abort, request, redirect, url_for, Response, session
from flask_restful import Resource, Api
from flask_debugtoolbar import DebugToolbarExtension
from random import getrandbits
transactions = OrderedDict()
categories = dict()
apiKeys = ['erl67api', 'test', 'random', 'key4']
auth = False
def create_app():
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY='erl67',
TEMPLATES_AUTO_RELOAD=True,
USE_THREADED = True,
))
print(app.__str__(), end=" ")
return app
app = create_app()
api = Api(app)
def require_apikey(view_function): #coderwall.com/p/4qickw/require-an-api-key-for-a-route-in-flask-using-only-a-decorator
@wraps(view_function)
def decorated_function(*args, **kwargs):
if (request.args.get('key') and request.args.get('key') in apiKeys) or (session.get('apiKey') in apiKeys):
return view_function(*args, **kwargs)
else:
abort(401)
return decorated_function
class cats(Resource):
@require_apikey
def get(self, cat=None):
if not cat:
return categories, 200
else:
try:
return categories[str(cat)], 200
except:
abort(404)
@require_apikey
def post(self):
cat = request.json['category']
amt = request.json['amount']
if cat not in categories.keys():
categories[cat] = amt
flash("category added : " + str(cat))
else:
flash("category already exists")
return {}, 201
@require_apikey
def delete(self):
category = request.json['category']
del categories[category]
flash("category " + str(category) + " removed")
return {}, 204
class trans(Resource):
@require_apikey
def get(self, transaction=None, val=None):
if not transaction:
return transactions, 200
elif not val:
try:
result = transactions[str(transaction)]
return result, 200
except:
abort(404)
else:
try:
result = transactions[str(transaction)][str(val)]
return result, 200
except:
abort(404)
@require_apikey
def put(self):
transact = dict()
transact['name'] = remove_tags(request.json['name'])
transact['date'] = request.json['date']
transact['total'] = request.json['total']
transact['category'] = request.json['category']
x = len(transactions)
if x > 1:
y = int(list(transactions.keys())[-1]) + 1
transactions[str(y)] = transact
else:
transactions[str(x)] = transact
flash("transaction added")
return {}, 201
@require_apikey
def delete(self):
transaction = request.json['transaction']
#eprint(str(transaction))
if transaction in transactions:
#del transactions[transaction]
transactions.pop(transaction)
flash("transaction removed")
else:
flash("nothing to remove")
return {}, 204
api.add_resource(cats, '/c', '/api/cats', '/api/cats/<int:cat>')
api.add_resource(trans, '/t', '/api/transactions', '/api/transactions/<int:transaction>', '/api/transactions/<int:transaction>&value=<val>')
@app.before_request
def before_request():
session['requests'] = int(session.get('requests') or 0) + 1
g.session = session
g.transactions = transactions
g.categories = categories
eprint("g.cats: " + str(g.categories), end="\t")
eprint("g.trans: " + str(g.transactions), end="\n\n")
@app.before_first_request
def before_first_request():
global auth
session['starts'] = int(session.get('starts') or 0) + 1
if session.get('apiKey') in apiKeys:
auth = True
eprint("\t🥇 \t\t" + str(auth))
@app.route("/save")
@require_apikey
def save_data():
with open('data/categories.p', 'wb') as fh:
pickle.dump(g.categories, fh)
with open('data/transactions.p', 'wb') as fh:
pickle.dump(g.transactions, fh)
flash("Data saved to file")
return redirect(url_for("index"))
@app.route("/open")
@require_apikey
def read_data():
global categories, transactions
with open('data/categories.p', 'rb') as fh:
categories = pickle.load(fh)
with open('data/transactions.p', 'rb') as fh:
transactions = pickle.load(fh)
flash("Data loaded from file")
return redirect(url_for("index"))
@app.route("/setkey")
def setkey(k=getrandbits(2)):
for i in range(0,10):
eprint(str(getrandbits(2)), end=" ")
session['apiKey'] = apiKeys[k]
return redirect(url_for("index"))
@app.route('/')
def index():
return Response(render_template('index.html'), status=200, mimetype='text/html')
@app.route('/review')
def review():
return Response(render_template('analysis.html'), status=200, mimetype='text/html')
@app.route('/404/')
@app.errorhandler(403)
@app.errorhandler(404)
def page_not_found(error=None):
return Response(render_template('404.html', errno=error), status=404, mimetype='text/html')
@app.route('/favicon.ico')
def favicon():
if bool(getrandbits(1))==True:
return send_from_directory(os.path.join(app.root_path, 'static'), 'faviconF.ico', mimetype='image/vnd.microsoft.icon')
else:
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
def eprint(*args, **kwargs):
print(*args, file=stderr, **kwargs)
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
if __name__ == "__main__":
print('Starting......')
if FDEBUG==True:
app.config.update(dict(
DEBUG=True,
DEBUG_TB_INTERCEPT_REDIRECTS=False,
TEMPLATES_AUTO_RELOAD=True,
))
app.jinja_env.auto_reload = True
# toolbar = DebugToolbarExtension(app)
app.run(use_reloader=True, host='0.0.0.0', port=8080)
else:
app.run()