Skip to content

Commit

Permalink
added update watchlist route,
Browse files Browse the repository at this point in the history
  • Loading branch information
Spectre-ak committed May 23, 2023
1 parent 5ef554a commit 90aeef2
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 17 deletions.
30 changes: 20 additions & 10 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import os
from flask import Flask, app, json,render_template, request, jsonify
from flask.helpers import send_file
import uuid
import local_setup


from flask import Flask, app, request, redirect, url_for, make_response
import json as jsonLoader
import psycopg2
# from flask_cors import CORS, cross_origin
import configs
import request_utils
from request_utils import req_auth, send_api_request
from utils import logger, get_auth_token
from user_auth import user_signup, user_login, validate_token
from watchlists_utils import create_watchlist
from watchlists_utils import create_watchlist, update_watchlist

app = Flask(__name__, static_url_path='', static_folder='static')
conn = psycopg2.connect(database=configs.DB_NAME,
Expand All @@ -20,6 +19,12 @@
cursor = conn.cursor()
# cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.before_request
def before_request():
auth_res = req_auth(request, cursor, conn)

if auth_res["status"] is False:
return auth_res["res"]

@app.route("/")
def route_dashboard():
Expand All @@ -28,12 +33,12 @@ def route_dashboard():
@app.route("/v1/stocks/<stock_name>", methods=["GET"])
def route_fetch_stock_metrics(stock_name):
logger(request, f"Fetching stock details for {stock_name}")
return request_utils.send_api_request(request, {"function": "GLOBAL_QUOTE", "symbol": stock_name})
return send_api_request(request, {"function": "GLOBAL_QUOTE", "symbol": stock_name})

@app.route("/v1/stocks/search/<keywords>", methods=["GET"])
def route_fetch_stock_symbols(keywords):
logger(request, f"Fetching stock symbols for {keywords}")
return request_utils.send_api_request(request, {"function": "SYMBOL_SEARCH", "keywords": keywords})
return send_api_request(request, {"function": "SYMBOL_SEARCH", "keywords": keywords})

@app.route("/v1/auth/signup", methods=["POST"])
def route_user_signup():
Expand All @@ -55,9 +60,14 @@ def route_create_watchlist():
logger(request, f"Creating watchlist")
return create_watchlist(request, cursor, conn)

@app.route("/v1/watchlist/update", methods=["POST"])
def route_update_watchlist():
logger(request, f"Creating watchlist")
return update_watchlist(request, cursor, conn)

if __name__ == "__main__":
if configs.ENV == "LOCAL":
app.run(host='0.0.0.0', port=5000, debug=True)
app.run(port=5000, debug=True)
elif configs.ENV == "UAT":
app.run(host='0.0.0.0', port=5000)
else:
Expand Down
32 changes: 27 additions & 5 deletions request_utils.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,56 @@
from urllib.parse import urlencode
import os
import requests
from flask import make_response
import random
import string
from utils import logger
from configs import api_base_url, proxy_base_url, api_keys, proxy_api_keys
from utils import get_auth_token
from user_auth import validate_token, get_username

def req_auth(request, cursor, connection):
res = make_response('Response')
res.status_code = 401
try:
path = request.path
if path in ["/v1/auth/login", "/v1/auth/validate/token", "/v1/auth/signup"]:
return {
"res": res,
"status": True
}
headers = request.headers
if "Authorization" not in headers.keys() or "Bearer" not in headers["Authorization"]:
raise Exception("Invalid auth header")
user_info = get_username(cursor, get_auth_token(headers["Authorization"]), connection)
return {
"res": res,
"status": len(user_info) == 1
}
except Exception as e:
return{
"res": res,
"status": False
}


def send_api_request(request, params):
api_res={}
fetched=False
for api_key in api_keys:
logger(request, f"API key in use {api_key}")
params['apikey']=api_key
req_url=f"{api_base_url}?{urlencode(params)}"
r = requests.get(req_url)
api_res = r.json()
logger(request, f"Results fetched directly: {api_res}")
if 'Error Message' in api_res or 'Note' in api_res:
logger(request, f"Trying with the scrape(proxy) API")
for proxy_api_key in proxy_api_keys:
proxy_server_params = {
'access_key': proxy_api_key,
'url': req_url
}
r = requests.get(proxy_base_url, proxy_server_params)
api_res = r.json()
logger(request, f"Results fetched using proxy {proxy_api_key}: {api_res}")
if 'success' in api_res and api_res['success'] is False:
logger(request, f"Cannot fetch using proxy, trying different proxy api key")
continue
else:
logger(request, f"Proxy returned response succesfully")
Expand Down
5 changes: 3 additions & 2 deletions user_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_user_hashed_pass(cursor, userid):
query_res = cursor.fetchall()
return query_res

def get_username(cursor, session_token):
def get_username(cursor, session_token, connection):
cursor.execute("""
SELECT
username,
Expand All @@ -46,6 +46,7 @@ def get_username(cursor, session_token):
WHERE
user_session_token = %s;
""".format(SCHEMA), (session_token,))
connection.commit()
query_res = cursor.fetchall()
if datetime.datetime.now() > query_res[0][1]:
return []
Expand Down Expand Up @@ -178,7 +179,7 @@ def validate_token(request, cursor, connection, token):
"msg": "",
"status": False
}
user_info = get_username(cursor, token)
user_info = get_username(cursor, token, connection)
if len(user_info) != 1:
token_validate_res["msg"] = "Token invalid"
return token_validate_res
Expand Down
23 changes: 23 additions & 0 deletions watchlists_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,26 @@ def create_watchlist(request, cursor, conn):



def update_watchlist(request, cursor, conn):
watchlist_update_res = {
"status": False,
"msg": ""
}
try:
watchlist_dict = request.get_json()
check_res = create_watchlist_checks(watchlist_dict)
if "watchlistId" not in watchlist_dict.keys():
check_res["msg"] = f'{check_res["msg"]},Watchlist id is not present!'
check_res["status"] = False
if check_res["status"] is False:
return check_res
watchlist_id = watchlist_dict["watchlistId"]
user_watchlist_update(conn, cursor, f"{{{watchlist_id}}}", json.dumps({"name": watchlist_dict["wathclistName"], "symbols": watchlist_dict["selectedSymbols"]}), watchlist_dict["username"])
watchlist_update_res["status"] = True
watchlist_update_res["msg"] = "Watchlist updated!"
watchlist_update_res["watchlist_id"] = watchlist_id
except Exception as e:
logger(request, f"Watchlist update error: {e}")
watchlist_update_res["msg"] = "Something went wront, unable to update watchlist!"
return watchlist_update_res

0 comments on commit 90aeef2

Please sign in to comment.