-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
125 lines (94 loc) · 3.07 KB
/
helpers.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
import csv
import urllib.request
from flask import redirect, render_template, request, session
from functools import wraps
def apology(message, code=400):
"""Renders message as an apology to user."""
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
s = s.replace(old, new)
return s
return render_template("apology.html", top=code, bottom=escape(message)), code
def login_required(f):
"""
Decorate routes to require login.
http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def lookup(symbol):
"""Look up quote for symbol."""
# reject symbol if it starts with caret
if symbol.startswith("^"):
return None
# reject symbol if it contains comma
if "," in symbol:
return None
# query Yahoo for quote
# http://stackoverflow.com/a/21351911
try:
# GET CSV
url = f"http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={symbol}"
webpage = urllib.request.urlopen(url)
# read CSV
datareader = csv.reader(webpage.read().decode("utf-8").splitlines())
# parse first row
row = next(datareader)
# ensure stock exists
try:
price = float(row[2])
except:
return None
# return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)
return {
"name": row[1],
"price": price,
"symbol": row[0].upper()
}
except:
pass
# query Alpha Vantage for quote instead
# https://www.alphavantage.co/documentation/
try:
# GET CSV
url = f"https://www.alphavantage.co/query?apikey=NAJXWIA8D6VN6A3K&datatype=csv&function=TIME_SERIES_INTRADAY&interval=1min&symbol={symbol}"
webpage = urllib.request.urlopen(url)
# parse CSV
datareader = csv.reader(webpage.read().decode("utf-8").splitlines())
# ignore first row
next(datareader)
# parse second row
row = next(datareader)
# ensure stock exists
try:
price = float(row[4])
except:
return None
# return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)
return {
"name": symbol.upper(), # for backward compatibility with Yahoo
"price": price,
"symbol": symbol.upper()
}
except:
return None
def usd(value):
"""Formats value as USD."""
return f"${value:,.2f}"
def IsInt(s):
try:
int(s)
if int(s) < 0:
return False
return True
except ValueError:
return False