-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
103 lines (76 loc) · 2.74 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
from flask import Flask, render_template
import os
import requests
import urllib.parse
import sqlite3
from flask import Flask, flash, redirect, render_template, request, session
app = Flask(__name__)
def lookup(symbol):
"""Look up quote for symbol."""
# Contact API
try:
api_key = "pk_fc6f5ddb92a3402db06c38afd053fe19"
url = f"https://cloud.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}"
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
quote = response.json()
return {
"name": quote["companyName"],
"price": float(quote["latestPrice"]),
"high": float(quote["week52High"]),
"low": float(quote["week52Low"]),
"market":quote["isUSMarketOpen"],
"symbol": quote["symbol"]
}
except (KeyError, TypeError, ValueError):
return None
def usd(value):
"""Format value as USD."""
return f"${value:,.2f}"
# Custom filter
app.jinja_env.filters["usd"] = usd
@app.route("/", methods=["GET", "POST"])
def index():
# connect withe the myTable database
connection = sqlite3.connect("myTable.db", check_same_thread=False)
# cursor object
crsr = connection.cursor()
if request.method == "POST":
sym = request.form.get("symbol")
form_name = request.form.get("form-name")
if form_name == "form1":
# execute the command to fetch all the data from the table emp
crsr.execute("SELECT * FROM names")
# store all the fetched data in the ans variable
data = crsr.fetchall()
chk = 1
for name in data:
if str(name[1]) == str(sym):
chk = 0
if chk:
crsr.execute("INSERT INTO names(symbol) values(?)", (sym,))
redirect("/")
else:
# execute the command to fetch all the data from the table emp
crsr.execute("SELECT * FROM names WHERE symbol=?", (sym,))
# store all the fetched data in the ans variable
data = crsr.fetchall()
if len(data)==1:
crsr.execute("DELETE FROM names WHERE symbol=?",(sym,))
redirect("/")
# execute the command to fetch all the data from the table emp
crsr.execute("SELECT * FROM names")
# store all the fetched data in the ans variable
data = crsr.fetchall()
prices = []
for name in data:
item = lookup(name[1])
prices.append(item)
connection.commit()
# Close the connection
connection.close()
return render_template("index.html", prices=prices)