-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·800 lines (537 loc) · 23.5 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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
import os
from cs50 import SQL
from multiprocessing.connection import Connection
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import apology, login_required, closer, dem_say, kilimanjaro, naomi, usd, get_db_connection
# import sqlite3
# Configure application
app = Flask(__name__)
#######¡¡¡¡¡ THANKS CS50 !!!!!#######
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# # Configure session to use filesystem (instead of signed cookies)
# app.config["SESSION_FILE_DIR"] = mkdtemp()
# app.config["SESSION_PERMANENT"] = False
# app.config["SESSION_TYPE"] = "filesystem"
# Session(app)
# create a db but using flask_sqlalchemy syntax
db = SQLAlchemy()
# db = get_db_connection()
app.config['SECRET_KEY'] = 'h1p3908jh0hji1nondjakjsoh8n1kju4i9y7yuui2hu0o8ujl'
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
# connection = sqlite3.connect('gallery.db')
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///gallery.db")
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
#read database for user share values and nfts
rows = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
#create list for database values to display
portfolio = []
total_cash = 0
#update cash
rows = db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=session["user_id"])
total_cash += rows[0]["cash"]
#return update portfolio
return render_template("index.html", purchases=portfolio, cash=usd(rows[0]["cash"]), total=usd(total_cash))
@app.route("/buy_closer", methods=["GET", "POST"])
@login_required
def buy_closer():
"""Buy edition of NFT"""
if request.method == "POST":
#verify nft field isn't null
if not request.form.get("NFT"):
return apology("must provide NFT", 400)
#verify nft
elif not closer(request.form.get("NFT")):
return apology("NFT does not exist", 400)
#get proper share values
elif not request.form.get("edition").isdigit():
return apology("must provide valid edition", 400)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper share values", 403)
NFT = request.form.get("NFT")
stock = closer(NFT)
# image = lookup(NFT)
rows = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])
cash = rows[0]["cash"]
balance = cash - edition * stock['price']
if balance < 0:
return apology("insufficient funds")
db.execute("UPDATE users SET cash=:balance WHERE id=:id",
balance=balance, id=session["user_id"])
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = edition)
flash("Closer Bought!")
return redirect("/")
# else:
# return render_template("buy.html")
@app.route("/buy_dem_say", methods=["GET", "POST"])
@login_required
def buy_dem_say():
"""Buy edition of NFT"""
if request.method == "POST":
#verify nft field isn't null
if not request.form.get("NFT"):
return apology("must provide NFT", 400)
#verify nft
elif not dem_say(request.form.get("NFT")):
return apology("NFT does not exist", 400)
#get proper share values
elif not request.form.get("edition").isdigit():
return apology("must provide valid edition", 400)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper share values", 403)
NFT = request.form.get("NFT")
stock = dem_say(NFT)
# image = lookup(NFT)
rows = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])
cash = rows[0]["cash"]
balance = cash - edition * stock['price']
if balance < 0:
return apology("insufficient funds")
db.execute("UPDATE users SET cash=:balance WHERE id=:id",
balance=balance, id=session["user_id"])
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = edition)
flash("Dem Say Bought!")
return redirect("/")
# else:
# return render_template("buy.html")
@app.route("/buy_kilimanjaro", methods=["GET", "POST"])
@login_required
def buy_kilimanjaro():
"""Buy edition of NFT"""
if request.method == "POST":
#verify nft field isn't null
if not request.form.get("NFT"):
return apology("must provide NFT", 400)
#verify nft
elif not kilimanjaro(request.form.get("NFT")):
return apology("NFT does not exist", 400)
#get proper share values
elif not request.form.get("edition").isdigit():
return apology("must provide valid edition", 400)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper share values", 403)
NFT = request.form.get("NFT")
stock = kilimanjaro(NFT)
# image = lookup(NFT)
rows = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])
cash = rows[0]["cash"]
balance = cash - edition * stock['price']
if balance < 0:
return apology("insufficient funds")
db.execute("UPDATE users SET cash=:balance WHERE id=:id",
balance=balance, id=session["user_id"])
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = edition)
flash("Kilimanjaro Bought!")
return redirect("/")
# else:
# return render_template("buy.html")
@app.route("/buy_naomi", methods=["GET", "POST"])
@login_required
def buy_naomi():
"""Buy edition of NFT"""
if request.method == "POST":
#verify nft field isn't null
if not request.form.get("NFT"):
return apology("must provide NFT", 400)
#verify nft
elif not naomi(request.form.get("NFT")):
return apology("NFT does not exist", 400)
#get proper share values
elif not request.form.get("edition").isdigit():
return apology("must provide valid edition", 400)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper share values", 403)
NFT = request.form.get("NFT")
stock = naomi(NFT)
# image = lookup(NFT)
rows = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])
cash = rows[0]["cash"]
balance = cash - edition * stock['price']
if balance < 0:
return apology("insufficient funds")
db.execute("UPDATE users SET cash=:balance WHERE id=:id",
balance=balance, id=session["user_id"])
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = edition)
flash("Naomi Bought!")
return redirect("/")
# else:
# return render_template("buy.html")
@app.route("/records")
@login_required
def records():
"""Show history of transactions"""
#read database for user share values and NFTs
rows = db.execute("""SELECT *
FROM purchases
WHERE user_id = :user_id;""",
user_id=session["user_id"])
#create list for database values to display
portfolio = []
total_cash = 0
#connecting database to corresponding value(list)
for row in rows:
portfolio.append({
"NFT": row["NFT"],
"edition": row["edition"],
"price": usd(row["price"]),
"transacted": row["transaction"]
})
#update cash
rows = db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=session["user_id"])
total_cash += rows[0]["cash"]
#return update portfolio
return render_template("records.html", purchases=portfolio, cash=usd(rows[0]["cash"]), total=usd(total_cash))
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return apology("invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "POST":
username = request.form['username']
password = request.form['password']
hash = generate_password_hash(password)
# Ensure username was submitted
if username is None or not request.form.get("username"):
return apology("must provide username", 400)
# Ensure password was submitted
elif password is None or not request.form.get("password"):
return apology("must provide password", 400)
elif not request.form.get("confirmation"):
return apology("must provide password again.", 400)
if request.form.get("confirmation") != request.form.get("password"):
return apology("Password un-matched, try again.", 400)
try:
# insert username and password hash to database
db.execute("INSERT INTO users (username, hash) VALUES(?,?)",
username, hash)
except:
return apology("Username already taken.", 400)
flash("Registered!")
# Redirect user to home page
return redirect("/login")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
@app.route('/settings', methods=['GET', 'POST'])
@login_required
def change_password():
"""Change password"""
if request.method == "POST":
user_id=session["user_id"]
c_password = request.form['current_password']
n_password = request.form['new_password']
hash = generate_password_hash(n_password)
# update password hash in database
db.execute("UPDATE users SET hash=? WHERE id=?",
hash, user_id)
# Ensure current password was submitted
if c_password is None or request.form.get("current_password"):
return apology("must provide current password", 403)
# Ensure new password was submitted
elif n_password is None or not request.form.get("new_password"):
return apology("must provide a new password", 403)
#confirm new password
elif not request.form.get("confirmation"):
return apology("must confirm new password", 403)
#verify new password confirmation
if request.form.get("confirmation") != request.form.get("new_password"):
return apology("Password un-matched, try again.", 403)
flash("Password Changed!")
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("settings.html")
@app.route('/nft_closer', methods=['GET', 'POST'])
@login_required
def nft_closer():
"""Open nft_closer"""
if request.method == "GET":
return render_template("closer.html")
@app.route('/nft_dem_say', methods=['GET', 'POST'])
@login_required
def nft_dem_say():
"""Open nft_dem_say"""
if request.method == "GET":
return render_template("dem_say.html")
@app.route('/nft_kilimanjaro', methods=['GET', 'POST'])
@login_required
def nft_kilimanjaro():
"""Open nft_kilimanjaro"""
if request.method == "GET":
return render_template("kilimanjaro.html")
@app.route('/nft_naomi', methods=['GET', 'POST'])
@login_required
def nft_naomi():
"""Open nft_naomi"""
if request.method == "GET":
return render_template("naomi.html")
@app.route("/sell_dem_say", methods=["GET", "POST"])
@login_required
def sell_dem_say():
"""Sell edition of NFT"""
if request.method == "POST":
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
user_id=session["user_id"]
NFT = request.form.get("NFT")
stock = dem_say(NFT)
# image = lookup(NFT)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper edition values", 403)
owned_editions = db.execute("SELECT edition FROM purchases WHERE user_id= ? AND NFT = ? GROUP BY NFT", user_id, NFT)
o_editions = owned_editions[0]["edition"]
if o_editions < edition:
return apology("Not enough editions!", 400)
present_cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"]) [0] ["cash"]
price = edition * stock['price']
db.execute("UPDATE users SET cash= ? WHERE id= ?",
present_cash + price, user_id)
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = -edition)
flash("Dem Say Sold!")
return redirect("/")
else:
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
return render_template("sell_dem_say.html", Data=NFTs)
@app.route("/sell_closer", methods=["GET", "POST"])
@login_required
def sell_closer():
"""Sell edition of NFT"""
if request.method == "POST":
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
user_id=session["user_id"]
NFT = request.form.get("NFT")
stock = closer(NFT)
# image = lookup(NFT)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper edition values", 403)
owned_editions = db.execute("SELECT edition FROM purchases WHERE user_id= ? AND NFT = ? GROUP BY NFT", user_id, NFT)
o_editions = owned_editions[0]["edition"]
if o_editions < edition:
return apology("Not enough editions!", 400)
present_cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"]) [0] ["cash"]
price = edition * stock['price']
db.execute("UPDATE users SET cash= ? WHERE id= ?",
present_cash + price, user_id)
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = -edition)
flash("Closer Sold!")
return redirect("/")
else:
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
return render_template("sell_closer.html", Data=NFTs)
@app.route("/sell_kilimanjaro", methods=["GET", "POST"])
@login_required
def sell_kilimanjaro():
"""Sell edition of NFT"""
if request.method == "POST":
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
user_id=session["user_id"]
NFT = request.form.get("NFT")
stock = kilimanjaro(NFT)
# for stock in nfts:
# stock = stock
# image = lookup(NFT)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper edition values", 403)
owned_editions = db.execute("SELECT edition FROM purchases WHERE user_id= ? AND NFT = ? GROUP BY NFT", user_id, NFT)
o_editions = owned_editions[0]["edition"]
if o_editions < edition:
return apology("Not enough editions!", 400)
present_cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"]) [0] ["cash"]
price = edition * stock['price']
db.execute("UPDATE users SET cash= ? WHERE id= ?",
present_cash + price, user_id)
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = -edition)
flash("Kilimanjaro Sold!")
return redirect("/")
else:
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
return render_template("sell_kilimanjaro.html", Data=NFTs)
@app.route("/sell_naomi", methods=["GET", "POST"])
@login_required
def sell_naomi():
"""Sell edition of NFT"""
if request.method == "POST":
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
user_id=session["user_id"]
NFT = request.form.get("NFT")
stock = naomi(NFT)
# for stock in nfts:
# stock = stock
# image = lookup(NFT)
#get positive values for "edition" input
edition = int(request.form.get("edition"))
if edition is None or edition <= 0:
return apology("please enter proper edition values", 403)
owned_editions = db.execute("SELECT edition FROM purchases WHERE user_id= ? AND NFT = ? GROUP BY NFT", user_id, NFT)
o_editions = owned_editions[0]["edition"]
if o_editions < edition:
return apology("Not enough editions!", 400)
present_cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"]) [0] ["cash"]
price = edition * stock['price']
db.execute("UPDATE users SET cash= ? WHERE id= ?",
present_cash + price, user_id)
db.execute("""INSERT INTO purchases (user_id, NFT, price, edition)
VALUES(:user_id, :NFT, :price, :edition)""",
user_id=session["user_id"],
NFT = stock["NFT"],
price = stock["price"],
edition = -edition)
flash("Naomi Sold!")
return redirect("/")
else:
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id
GROUP BY NFT;""",
user_id=session["user_id"])
return render_template("sell_naomi.html", Data=NFTs)
@app.route("/collections", methods=["GET", "POST"])
@login_required
def collections():
"""Sell edition of NFT"""
if request.method == "GET":
NFTs = db.execute("""SELECT NFT, SUM(edition) as S_total
FROM purchases
WHERE user_id = :user_id AND edition > 0
GROUP BY NFT;""",
user_id=session["user_id"])
return render_template("collections.html", Data=NFTs)
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
# Listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)