TelegramAktienBot/api/api_blueprint_shares.py

83 lines
2.9 KiB
Python

import os
from apiflask import APIBlueprint, abort
from auth import auth
from db import db
from helper_functions import get_user_id_from_username, get_username_or_abort_401, make_response
from models import Share
from schema import SymbolSchema, SymbolResponseSchema, DeleteSuccessfulSchema
shares_blueprint = APIBlueprint('share', __name__, url_prefix='/api')
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
@shares_blueprint.route('/share', methods=['POST'])
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
@shares_blueprint.input(schema=SymbolSchema)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Add new symbol", description="Adds new symbol for current user")
def add_symbol(data):
username = get_username_or_abort_401()
check_if_symbol_data_exists(data)
symbol = data['symbol']
check_share = db.session.query(Share).filter_by(symbol=symbol, user_id=get_user_id_from_username(username)).first()
if check_share is None:
# Keyword doesn't exist yet for this user
new_symbol = Share(
user_id=get_user_id_from_username(username),
symbol=symbol
)
db.session.add(new_symbol)
db.session.commit()
return make_response(new_symbol.as_dict(), 200, "Successfully added symbol")
else:
return make_response({}, 500, "Symbol already exist for this user")
@shares_blueprint.route('/share', methods=['DELETE'])
@shares_blueprint.output(DeleteSuccessfulSchema, 200)
@shares_blueprint.input(schema=SymbolSchema)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Removes existing symbol", description="Removes existing symbol for current user")
def remove_symbol(data):
username = get_username_or_abort_401()
check_if_symbol_data_exists(data)
symbol = data['symbol']
db.session.query(Share).filter_by(symbol=symbol, user_id=get_user_id_from_username(username)).delete()
db.session.commit()
return make_response({}, 200, "Successfully removed symbol")
@shares_blueprint.route('/shares', methods=['GET'])
@shares_blueprint.output(SymbolResponseSchema(many=True), 200)
@shares_blueprint.auth_required(auth)
@shares_blueprint.doc(summary="Returns all symbols", description="Returns all symbols for current user")
def get_symbol():
username = get_username_or_abort_401()
return_symbols = []
symbols = db.session.query(Share).filter_by(user_id=get_user_id_from_username(username)).all()
if symbols is not None:
for row in symbols:
return_symbols.append(row.as_dict())
return make_response(return_symbols, 200, "Successfully loaded symbols")
def check_if_symbol_data_exists(data):
if "symbol" not in data:
abort(400, message="Symbol missing")
if data['symbol'] == "" or data['symbol'] is None:
abort(400, message="Symbol missing")