-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
40 lines (31 loc) · 1.06 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
import requests
from flask import redirect, render_template, session
from functools import wraps
def login_required(f):
"""
Decorate routes to require login.
https://flask.palletsprojects.com/en/latest/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."""
url = f"https://finance.cs50.io/quote?symbol={symbol.upper()}"
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for HTTP error responses
quote_data = response.json()
return {
"name": quote_data["companyName"],
"price": quote_data["latestPrice"],
"symbol": symbol.upper()
}
except requests.RequestException as e:
print(f"Request error: {e}")
except (KeyError, ValueError) as e:
print(f"Data parsing error: {e}")
return None