def public_list(list_name): db = Watchlist() username = session['__auth'] if not db.check_watchlist(username, list_name): return render_template('404.html') db.public_list(username, list_name) return redirect(url_for("watchlists", username=username))
def test_confirmed(self): """Test if the remove from watchlist dialog confirmed works. Flow, there is a stock in users watchlist, user asks to remove it but denies it afterwards.""" # Setup: check if there is stock in users watchlist with self.app.app_context(): watchlist = Watchlist.get_users_tickers(test_user_id) self.assertIn(test_add_stock, watchlist) # Step 1 ask to remove stock (stock present) res = self._remove_from_watchlist(test_add_stock) # Assert self.assertEqual(res.status_code, 200) self.assertIn(RESPONSE_intent_remove_from_watchlist_ask_confirmation, str(res.data)) # Step 2 Confirm removing the stock # Prepare request request = json.dumps(intent_remove_from_watchlist_confirm()) # Execute res = self.client().post('/api/', data=request, content_type='application/json') # Assert self.assertEqual(res.status_code, 200) self.assertIn( RESPONSE_intent_remove_from_watchlist_confirmed.format( test_add_stock), str(res.data)) # Check if stock was removed from watchlist with self.app.app_context(): watchlist = Watchlist.get_users_tickers(test_user_id) self.assertNotIn(test_add_stock, watchlist)
def setUp(self): """Define test variables and initialize app.""" self.app = create_app(config_name="testing") self.client = self.app.test_client # binds the app to the current context with self.app.app_context(): # create all tables db.create_all() # Insert testing data Stock(test_stock_1_ticker, test_stock_1_date_1, close=test_stock_1_close_1).save() Stock(test_stock_1_ticker, test_stock_1_date, close=test_stock_1_close).save() Stock(test_stock_2_ticker, test_stock_2_date_1, close=test_stock_2_close_1).save() Stock(test_stock_2_ticker, test_stock_2_date, close=test_stock_2_close).save() User(test_user_id, test_user_name).save() Watchlist(test_stock_1_ticker, test_user_id).save() Watchlist(test_stock_2_ticker, test_user_id).save()
def list_films(username, list_name): db = Watchlist() list_id = db.get_list_id(session['__auth'], username, list_name) if list_id is None: return render_template('404.html') films, watchlist = db.watchlist_films(list_id) return render_template('list_films.html', list_name=list_name, films=films, username=username, watchlists=watchlist)
def watchlists(username): db = Watchlist() user = User() id = user.current_user(username) if not id: return render_template('404.html') watchlists = db.watchlists(session['__auth'], username) return render_template('watchlist.html', watchlists=watchlists, username=username)
def new_watchlist(): username = session["__auth"] form = WatchlistForm(username) db = Watchlist() if form.validate_on_submit(): list_name = form.title.data body = form.content.data db.add_watchlist(username, list_name, body) return redirect(url_for("watchlists", username=username)) return render_template('newlist.html', form=form, title="New Flow", )
def test_intent_report__empty_watchlist(self): """Test API answers intent request report watchlist.""" # Setup with self.app.app_context(): Watchlist.delete_all() request = json.dumps(intent_report_watchlist()) # Execute res = self.client().post('/api/', data=request, content_type='application/json') # Assert self.assertEqual(res.status_code, 200) self.assertIn(RESPONSE_intent_report_empty_watchlist, str(res.data))
def _handle_dialog_remove_started(request): """ Check if the provided ticker is valid and stock is in watchlist, if yes, ask for confirmation. Otherwise, inform about the state. :type request AlexaRequest """ logger.debug("dialogState STARTED") user_id = request.user_id() # Check if ticker is provided try: ticker = _check_valid_ticker_provided(request) except AttributeError as e: logger.exception("No valid ticker provided") message = strings.INTENT_REMOVE_FROM_WATCHLIST_FAIL return ResponseBuilder.create_response(request, message=message) \ .with_reprompt(strings.INTENT_GENERAL_REPROMPT) # Check if stock is in users Watchlist is_in_watchlist = Watchlist.ticker_in_watchlist_exists(user_id, ticker) # Inform that stock not in watchlist, or ask user to confirm ticker remove if is_in_watchlist: logger.debug( f"Ask confirmation: remove stock {ticker} from user:{user_id} watchlist" ) message = strings.INTENT_REMOVE_FROM_WATCHLIST_ASK_CONFIRMATION \ .format(ticker) return ResponseBuilder.create_response(request, message) \ .with_dialog_confirm_intent() else: logger.debug( f"Trying to remove stock {ticker}, which is not in wathclist") message = strings.INTENT_REMOVE_FROM_WATCHLIST_NOT_THERE.format(ticker) return ResponseBuilder.create_response(request, message)
def signup(): data = request.get_json() user = User.query.filter(User.email == data["email"]).first() if user: return {"error": "This user account already exists."} if (len(data["password"]) < 8): return {"error": "Password must be at least 8 characters."} elif data: newWatchlist = Watchlist(name=data["email"]) db.session.add(newWatchlist) db.session.commit() createdWatchlist = Watchlist.query.filter( Watchlist.name == data["email"]).first() newUser = User(email=data["email"], password=sha256_crypt.hash(data["password"]), firstName=data["firstName"], lastName=data["lastName"], balance=(data["balance"] if "balance" in data else 0), watchlist=createdWatchlist) db.session.add(newUser) db.session.commit() created = User.query.filter(User.email == data["email"]).first() return { "id": created.id, "email": created.email, "balance": str(created.balance) }
def _handle_dialog_add_started(request): """ Check if the provided ticker is supported or is not already in watchlist, if not, ask for confirmation. :type request AlexaRequest """ print("LOG-d: dialogState STARTED") # Check if ticker is provided try: ticker = _check_valid_ticker_provided(request) except AttributeError as e: logger.exception("No valid ticker provided") message = strings.INTENT_ADDED_TO_WATCHLIST_FAIL return ResponseBuilder.create_response(request, message=message) \ .with_reprompt(strings.INTENT_GENERAL_REPROMPT) # Ask user to confirm ticker add message = strings.INTENT_ADD_TO_WATCHLIST_ASK_CONFIRMATION.format(ticker) # Check if ticker not already in Watchlist user_id = request.get_user_id() watchlist_tickers = Watchlist.get_users_tickers(user_id) for ticker_in_watchlist in watchlist_tickers: if ticker == ticker_in_watchlist: message = strings.INTENT_ADDED_TO_WATCHLIST_EXISTS.format(ticker) return ResponseBuilder.create_response(request, message) \ .with_dialog_confirm_intent()
def new_filmInlist(film_id): username = session["__auth"] form = WatchlistForm(username) db = Watchlist() if form.validate_on_submit(): list_name = form.title.data body = form.content.data if request.form.get("mycheckbox"): db.add_watchlist(username, list_name, body) list_id = db.get_list_id(username, session['__auth'], list_name) db.add_film(list_id, film_id) else: db.add_watchlist(username, list_name, body) return redirect(url_for("movie", film_id=film_id)) return render_template('newlist.html', form=form, title="New Flow", checkbox=True)
def movie(film_id): form = ReviewForm() db = Film() db_w = Watchlist() db_user = User() page = request.args.get('page', '1') if not db.check_film(film_id): return render_template('404.html') (film, directors, actors, genres, reviews, page, pageCount) = db.get_film(film_id, page) if session.get("__auth"): list_names = db_w.watchlist_names(session["__auth"]) rate = db_user.check_rate(film_id) else: list_names = [] rate = 0 return render_template('movie.html', form=form, film=film, directors=directors, actors=actors, genres=genres, reviews=reviews, list_names=list_names, rate=rate, page=page, pageCount=pageCount)
def add_filmInList(list_name, film_id): db = Watchlist() username = session['__auth'] if not db.check_watchlist(username, list_name): return render_template('404.html') list_id = db.get_list_id(username, session['__auth'], list_name) db.add_film(list_id, film_id) return redirect(url_for('movie', film_id=film_id))
def del_watchlist(list_name): db = Watchlist() username = session['__auth'] if not db.check_watchlist(username, list_name): return render_template('404.html') list_id = db.get_list_id(username, session['__auth'], list_name) db.delete_watchlist(list_id) return redirect(url_for("watchlists", username=username))
def test_watchlist_empty(self): """Test removing stock from watchlist when watchlist is empty.""" # Setup: check the target stock is not in users watchlist with self.app.app_context(): watchlist = Watchlist.get_users_tickers(test_user_id) self.assertNotIn(test_stock_1_ticker, watchlist) # Step 1 ask to remove stock (stock not present) res = self._remove_from_watchlist(test_stock_1_ticker) # Assert self.assertEqual(res.status_code, 200) self.assertIn(RESPONSE_intent_remove_from_watchlist_not_there, str(res.data)) pass
def add_to_watchlist_dialog_deny(self): # Setup request = json.dumps(intent_add_to_watchlist_deny()) # Execute res = self.client().post('/api/', data=request, content_type='application/json') # Assert 1st step self.assertEqual(res.status_code, 200) self.assertIn(RESPONSE_intent_add_to_watchlist_denied, str(res.data)) # check if stock not in watchlist just yet with self.app.app_context(): watchlist = Watchlist.get_users_tickers(test_user_id) for item in watchlist: self.assertNotEqual(item, test_add_stock)
def create_watchlist(): '''Create a Watchlist Route''' form = WatchlistForm() if form.validate_on_submit(): new_watchlist = Watchlist( name=form.name.data, photo_url = form.photo_url.data, user = current_user ) db.session.add(new_watchlist) db.session.commit() flash('New watchlist created successfully.') return redirect(url_for('main.home')) # if form was not valid, or was not submitted yet return render_template('create_watchlist.html', form=form)
def update_list(list_name): username = session["__auth"] form = UpdateList(username, list_name) db = Watchlist() username = session['__auth'] if not db.check_watchlist(username, list_name): return render_template('404.html') elif form.validate_on_submit(): list_title = form.title.data body = form.content.data list_id = db.get_list_id(username, session['__auth'], list_name) db.update_watchlist(list_id, list_title, body, username) return redirect(url_for("watchlists", username=username)) form.title.data = list_name form.content.data = db.get_list_body(username, list_name) return render_template('newlist.html', form=form, title="Update Flow")
def create_anime(): a1 = Studio(name='Mappa') g1 = Genre(name='Shounen') p1 = Watchlist(name='Shounens') s1 = Anime( title='Jujutsu Kaisen', photo_url= "https://static.wikia.nocookie.net/jujutsu-kaisen/images/8/88/Anime_Key_Visual_2.png/revision/latest?cb=20201212034001", date=date(2020, 9, 19), studio=a1, genres=g1, watchlists=p1) db.session.add(s1) a2 = Studio(name='Bones') s2 = Anime(title='My Hero Academia', studio=a2) db.session.add(s2) db.session.commit()
def _add_ticker_to_watchlist(request): """ Add ticker to users Watchlist and build response. :type request AlexaRequest """ user_id = request.get_user_id() ticker = request.get_slot_value('stockTicker') if ticker is None: ticker = request.get_session_attribute('stockTicker') message = strings.INTENT_ADD_TO_WATCHLIST_CONFIRMED.format(ticker) reprompt_message = strings.INTENT_GENERAL_REPROMPT # Save stock to watchlist try: user_id = request.get_user_id() Watchlist(ticker, user_id).save() except EntryExistsError as e: message = strings.ERROR_CANT_ADD_TO_WATCHLIST.format(ticker) return ResponseBuilder.create_response(request, message=message) \ .with_reprompt(reprompt_message)
def handle_report_stock_watchlist(request): """ Generate response to intent type ReportStockWatchlistIntent reporting the current portfolio performance. :type request AlexaRequest :return: JSON response including the performance report. """ user_id = request.get_user_id() # Query DB for watchlist data ticker_list = Watchlist.get_users_tickers(user_id) changes = _get_stocks_24h_change(ticker_list) if len(ticker_list) > 2: max_idx = _find_biggest_value(changes) gainer_ticker = ticker_list.pop(max_idx) gainer_value = changes.pop(max_idx) min_idx = _find_smallest_value(changes) loser_ticker = ticker_list.pop(min_idx) loser_value = changes.pop(min_idx) gainer_message = strings.INTENT_WATCHLIST_REPORT_TOP_STOCK.format( Ticker2Name.ticker_to_name(gainer_ticker), _get_movement_direction(gainer_value), abs(gainer_value)) loser_message = strings.INTENT_WATCHLIST_REPORT_WORST_STOCK.format( Ticker2Name.ticker_to_name(loser_ticker), _get_movement_direction(loser_value), abs(loser_value)) message = gainer_message + loser_message + _build_report_msg(ticker_list, changes) elif len(ticker_list) == 2 or len(ticker_list) == 1: message = _build_report_msg(ticker_list, changes) else: message = strings.INTENT_WATCHLIST_EMPTY_MSG reprompt_message = strings.INTENT_GENERAL_REPROMPT return ResponseBuilder.create_response(request, message=message) \ .with_reprompt(reprompt_message)
def _remove_ticker_from_watchlist(request): """ Remove ticker from users Watchlist if there and build response. :type request AlexaRequest """ user_id = request.get_user_id() ticker = request.get_slot_value('stockTicker') if ticker == "NONE": ticker = request.get_session_attribute('stockTicker') message = strings.INTENT_REMOVE_FROM_WATCHLIST_CONFIRMED.format(ticker) reprompt_message = strings.INTENT_GENERAL_REPROMPT # Delete stock from watchlist try: Watchlist(ticker, user_id).delete() except EntryExistsError as e: logger.exception( f"Error while deleting ticker {ticker} from Watchlist") logger.debug(f"Deleted stock {ticker} from user:{user_id} watchlist") return ResponseBuilder.create_response(request, message=message) \ .with_reprompt(reprompt_message)
def seed_users(): watchlist = Watchlist(name="watchlist") appl = Stock(ticker="AAPL") watchlistContent = WatchlistContent(watchlistId=21, stockId=17) demo = User(username='******', full_name='Demo User', email='*****@*****.**', buying_power=10000000, password='******', watchlistId=21) watchlistContent = WatchlistContent(watchlistId=21, stockId=17) stocklist = Stocklist(shares=3, stockId=17, userId=5) db.session.add(watchlist) db.session.add(appl) db.session.add(watchlistContent) db.session.add(demo) db.session.add(stocklist) db.session.commit()
from dotenv import load_dotenv load_dotenv() from app import app, db from app.models import User, Watchlist, Stocklist, Trade, Stock, WatchlistContent from passlib.hash import sha256_crypt with app.app_context(): db.drop_all() db.create_all() watchlist = Watchlist(name="watchlist") apple = Stock(ticker="AAPL") stock2 = Stock(ticker="AMZN") stock3 = Stock(ticker="BABA") stock4 = Stock(ticker="TSLA") stock5 = Stock(ticker="MSFT") stock6 = Stock(ticker="FB") stock7 = Stock(ticker="DIS") stock8 = Stock(ticker="NFLX") stock9 = Stock(ticker="F") stock10 = Stock(ticker="NVDA") watchlistContent = WatchlistContent(watchlistId=1, stockId=1) guest = User(email='*****@*****.**', firstName='Bruce', lastName='Wayne', password=sha256_crypt.hash('password'), balance=25000, watchlistId=1) stocklist = Stocklist(shares=3, stockId=1, userId=1) watchlistContent2 = WatchlistContent(watchlistId=1, stockId=2)
def validate_title(self, title): watchlist = Watchlist() if title.data != self.list_name: ok = watchlist.validate_listname(self.username, title.data) if not ok: raise ValidationError('Please use a different title.')