def __init__(self, request): super(UpdateDBViewer, self).__init__(request) #self.layout.main_menu = make_main_menu(self.request).render() #self.layout.ctx_menu = make_ctx_menu(self.request).output() make_context_menu(self.request) self.games = NFLGameManager(self.request.db) self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) settings = self.get_app_settings() url = settings['vignewton.nfl.odds.url'] self.odds.oddscache.set_url(url) url = settings['vignewton.nfl.schedule.url'] self.games.schedules.set_url(url) self.mgr = UpdateDBManager(self.request.db) self.context = self.request.matchdict['context'] # make dispatch table self._cntxt_meth = dict( main=self.main_view, games=self.update_games, odds=self.update_odds, bets=self.determine_bets, report=self.show_update_report, ) if self.context in self._cntxt_meth: self._cntxt_meth[self.context]() else: msg = 'Undefined Context: %s' % self.context self.layout.content = '<b>%s</b>' % msg
def __init__(self, session): self.session = session self.games = NFLGameManager(self.session) self.teams = NFLTeamManager(self.session) self.odds = NFLOddsManager(self.session) self.accounts = AccountingManager(self.session) # FIXME: put this in config or database self.max_bet = 500
def __init__(self, request): super(BetsViewer, self).__init__(request) #self.layout.main_menu = make_main_menu(self.request).render() #self.layout.ctx_menu = make_ctx_menu(self.request).output() make_context_menu(self.request) self.accounts = AccountingManager(self.request.db) self.teams = NFLTeamManager(self.request.db) self.games = NFLGameManager(self.request.db) self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) settings = self.get_app_settings() url = settings['vignewton.nfl.odds.url'] self.odds.oddscache.set_url(url) self.context = self.request.matchdict['context'] # make dispatch table self._cntxt_meth = dict( main=self.main_view, allpending=self.view_all_pending_bets, allclosed=self.view_all_closed_bets, ) if self.context in self._cntxt_meth: self._cntxt_meth[self.context]() else: msg = 'Undefined Context: %s' % self.context self.layout.content = '<b>%s</b>' % msg
def __init__(self, request): super(MainViewer, self).__init__(request) prepare_main_data(request) self.games = NFLGameManager(self.request.db) self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) template = 'vignewton:templates/admin-main-view.mako' env = dict(odds=self.odds, games=self.games, bets=self.bets) content = self.render(template, env) self.layout.content = content
def even_more_setup(env): from vignewton.managers.util import parse_odds_html games = parse_odds_html(text) env['games'] = games #from vignewton.models.main import NFLGame gm = NFLGameManager(db) env['gm'] = gm dbgames = [gm.get_game_from_odds(g) for g in games] env['dbgames'] = dbgames from vignewton.managers.odds import NFLOddsManager om = NFLOddsManager(db) env['om'] = om om.oddscache.set_url(odds_url)
def __init__(self, request): super(MainViewer, self).__init__(request) self.route = self.request.matched_route.name self.layout.main_menu = make_main_menu(self.request).render() self.layout.ctx_menu = make_ctx_menu(self.request).output() if self.accounts is not None: self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) # make form resources available schema = CreditAmountSchema() form = deform.Form(schema, buttons=('submit',)) self.layout.resources.deform_auto_need(form) del schema, form # begin dispatch if self.route == 'home': self.main_view() return elif self.route == 'initdb': self.initialize_database() return if self.route == 'main': self.context = self.request.matchdict['context'] # make dispatch table self._cntxt_meth = dict( main=self.main_view, schedcal=self.schedule_view, initialize=self.initialize_database, ) if self.context in self._cntxt_meth: self._cntxt_meth[self.context]() else: msg = 'Undefined Context: %s' % self.context self.layout.content = '<b>%s</b>' % msg
def setup(env): request = env['request'] db = request.db env['db'] = db settings = env['registry'].settings url = settings['vignewton.nfl.schedule.url'] env['url'] = url odds_url = settings['vignewton.nfl.odds.url'] from vignewton.managers.nflgames import NFLTeamManager tm = NFLTeamManager(db) env['tm'] = tm from vignewton.managers.odds import NFLOddsManager om = NFLOddsManager(db) env['om'] = om om.oddscache.set_url(odds_url) if not om.get_current_odds(): filename = 'testdata/o.pickle' if not os.path.isfile(filename): om.update_current_odds() else: om.populate_from_pickle(filename) from vignewton.managers.nflgames import NFLGameManager gm = NFLGameManager(db) env['gm'] = gm gm.set_schedule_url(url) update_game_schedule = False if update_game_schedule: update_games(gm) env['ug'] = update_games from vignewton.managers.accounting import AccountingManager am = AccountingManager(db) am.initialize_bets_manager() env['am'] = am #env['games'] = om.oddscache.get_latest()[0].content #env['bg'] = env['games'][-3] from vignewton.managers.util import determine_max_bet env['dmb'] = determine_max_bet env['game'] = gm.query().get(125) backup_cache(gm, om) from vignewton.managers.bets import BetsManager bm = BetsManager(db) env['bm'] = bm from vignewton.managers.util import chop_ical_nflgame_desc env['cind'] = chop_ical_nflgame_desc env['g'] = gm.get(131)
class UpdateDBViewer(AdminViewer): def __init__(self, request): super(UpdateDBViewer, self).__init__(request) #self.layout.main_menu = make_main_menu(self.request).render() #self.layout.ctx_menu = make_ctx_menu(self.request).output() make_context_menu(self.request) self.games = NFLGameManager(self.request.db) self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) settings = self.get_app_settings() url = settings['vignewton.nfl.odds.url'] self.odds.oddscache.set_url(url) url = settings['vignewton.nfl.schedule.url'] self.games.schedules.set_url(url) self.mgr = UpdateDBManager(self.request.db) self.context = self.request.matchdict['context'] # make dispatch table self._cntxt_meth = dict( main=self.main_view, games=self.update_games, odds=self.update_odds, bets=self.determine_bets, report=self.show_update_report, ) if self.context in self._cntxt_meth: self._cntxt_meth[self.context]() else: msg = 'Undefined Context: %s' % self.context self.layout.content = '<b>%s</b>' % msg def main_view(self): self.layout.header = 'Main Update View' self.layout.content = 'Main Update View' def update_games(self): updated = self.games.update_games() if updated: self.layout.content = 'Game Schedule updated.' else: self.layout.content = 'No need to update yet.' def update_odds(self): olist, updated = self.odds.update_current_odds() if updated: self.layout.content = 'Game Odds updated.' else: self.layout.content = 'No need to update yet.' def determine_bets(self): template = 'vignewton:templates/admin-determine-bets.mako' clist = self.bets.determine_bets() env = dict(bm=self.bets, clist=clist) content = self.render(template, env) self.layout.content = content def show_update_report(self): reports = self.mgr.get_all() template = 'vignewton:templates/admin-full-update-report.mako' env = dict(reports=reports) content = self.render(template, env) self.layout.content = content
def __init__(self, session): self.session = session self.games = NFLGameManager(self.session) self.odds = NFLOddsManager(self.session) self.bets = BetsManager(self.session)
class UpdateDBManager(object): def __init__(self, session): self.session = session self.games = NFLGameManager(self.session) self.odds = NFLOddsManager(self.session) self.bets = BetsManager(self.session) def set_schedule_url(self, url): self.games.schedules.set_url(url) def set_schedule_ttl(self, **kw): self.games.schedules.set_ttl(**kw) def set_odds_url(self, url): self.odds.oddscache.set_url(url) def set_odds_ttl(self, **kw): self.odds.oddscache.set_ttl(**kw) def query(self): return self.session.query(UpdateReport) def get(self, report_id): return self.query().get(report_id) def _order_desc_filter(self, query): return query.order_by(UpdateReport.created.desc()) def get_latest(self): q = self.query() q = self._order_desc_filter(q) return q.first() def get_all(self): q = self.query() q = self._order_desc_filter(q) return q.all() def _add_report(self, content): with transaction.manager: now = datetime.now() ur = UpdateReport() ur.created = now ur.content = content self.session.add(ur) return self.session.merge(ur) def _update_database(self): games_updated = self.games.update_games() #games_updated = False oddslist, odds_updated = self.odds.update_current_odds() determined = self.bets.determine_bets() oddslist = [serialize_odds(o) for o in oddslist] determined = [serialize_closed_bet(b) for b in determined] data = dict(games_updated=games_updated, odds_updated=odds_updated, oddslist=oddslist, determined=determined) return data def update(self): content = self._update_database() report = self._add_report(content) return report
class BetsManager(object): def __init__(self, session): self.session = session self.games = NFLGameManager(self.session) self.teams = NFLTeamManager(self.session) self.odds = NFLOddsManager(self.session) self.accounts = AccountingManager(self.session) # FIXME: put this in config or database self.max_bet = 500 def query(self): return self.session.query(UserBet) def get(self, bet_id): return self.query().get(bet_id) def get_current_bet(self, user_id): q = self.session.query(CurrentBet) return q.get(user_id) def _get_odds(self, game_id): odds = self.odds.get_odds(game_id) return odds def _copy_current_odds(self, bet, odds): for field in ['favored_id', 'underdog_id', 'total', 'spread']: setattr(bet, field, getattr(odds, field)) def _check_amount(self, user_id, amount): if amount % 10 != 0: raise BetNotInTensError, "Bad amount %d" % amount if amount < 10: raise MinimumBetError, "Bet must be at least ten: %d" % amount if amount > self.max_bet: msg = "Bet must be no more than %d: amount %d" raise MaximumBetError, msg % (self.max_bet, amount) acct = self.accounts.get(user_id) balance = acct.balance.balance max_bet = determine_max_bet(balance) if amount > max_bet: juice_insurance = amount / 10 total = amount + juice_insurance msg = "Total needed %d, current balance %d" % (total, balance) raise InsufficientFundsError, msg return True def check_bet_amount(self, user_id, amount): return self._check_amount(user_id, amount) # pick is either an NFLTeam object, 'over', or 'under' def request_bet(self, user_id, game_id, amount, bettype, pick): # here we sanitize the bettype and # amount arguments if bettype not in ['line', 'underover']: raise RuntimeError, "Bad bettype %s:" % bettype # check amount # self.accounts.check_bet_amount(user_id, amount) self._check_amount(user_id, amount) if self.get_current_bet(user_id) is not None: raise UnconfirmedBetExistsError, "Betting in progress" with transaction.manager: now = datetime.now() curbet = CurrentBet() curbet.user_id = user_id curbet.game_id = game_id curbet.created = now curbet.amount = amount curbet.bet_type = bettype if bettype == 'line': # the pick is a team curbet.team_id = pick.id else: # the pick is under/over curbet.underover = pick self.session.add(curbet) return self.session.merge(curbet) def show_requested_bet(self, user_id): current = self.get_current_bet(user_id) if current is None: raise NoCurrentBetError, "No current bet" odds = self._get_odds(current.game_id) odata = self.odds.get_data(odds) return current, odata def cancel_requested_bet(self, user_id): with transaction.manager: q = self.session.query(CurrentBet) q = q.filter_by(user_id=user_id) q.delete() def place_requested_bet(self, user_id): current, odata = self.show_requested_bet(user_id) game_id = current.game_id amount = current.amount bettype = current.bet_type underover = current.underover team_id = current.team_id account = self.accounts.get(user_id) txn = self.accounts.place_bet(account.id, amount) with transaction.manager: now = datetime.now() bet = UserBet() bet.user_id = user_id bet.game_id = current.game_id bet.txn_id = txn.id bet.created = current.created bet.amount = current.amount bet.bet_type = current.bet_type bet.underover = current.underover bet.team_id = current.team_id for field in odata: setattr(bet, field, odata[field]) self.session.add(bet) dq = self.session.query(CurrentBet).filter_by(user_id=user_id) dq.delete() return self.session.merge(bet) def get_bets(self, user_id=None, game_id=None): pass def get_game_bets(self, game_id): q = self.query() q = q.filter_by(game_id=game_id) return q.all() def get_user_bets(self, user_id, game_id=None): q = self.query() q = q.filter_by(user_id=user_id) if game_id is not None: q = q.filter_by(game_id=game_id) return q.all() def get_user_closed_bets(self, user_id, game_id=None): q = self.session.query(ClosedBet) q = q.filter_by(user_id=user_id) if game_id is not None: q = q.filter_by(game_id=game_id) return q.all() def _get_score(self, bet): "returns score as favored, underdog" game = bet.game score = game.score if bet.favored_id == game.away_id: favored_score = score.away_score elif bet.favored_id == game.home_id: favored_score = score.home_score else: raise RuntimeError, "Team/score mismatch game %d" % game.id if bet.underdog_id == game.away_id: underdog_score = score.away_score elif bet.underdog_id == game.home_id: underdog_score = score.home_score else: raise RuntimeError, "Team/score mismatch game %d" % game.id return favored_score, underdog_score def _determine_bet(self, bet_id): bet = self.query().get(bet_id) if bet is None: raise RuntimeError, "Bad bet id %d" % bet_id if bet.game.score is None: return fscore, uscore = self._get_score(bet) result = determine_bet(bet, fscore, uscore) acct = self.accounts.get(bet.user_id) if result == 'push': txn = self.accounts.push_bet(acct.id, bet.amount) elif result == 'win': txn = self.accounts.win_bet(acct.id, bet.amount) elif result == 'lose': txn = self.accounts.lose_bet(bet.amount) else: raise RuntimeError, "bad result %s" % result with transaction.manager: cb = make_closed_bet(bet, result, txn) self.session.add(cb) self.session.delete(bet) return self.session.merge(cb) def determine_bet(self, bet_id): return self._determine_bet(bet_id) def determine_bets(self): closed = list() for bet in self.get_all_bets(): cb = self.determine_bet(bet.id) closed.append(cb) return closed def get_all_bets(self): return self.query().all() def get_all_closed_bets(self): return self.session.query(ClosedBet).all()
class MainViewer(BaseViewer): def __init__(self, request): super(MainViewer, self).__init__(request) self.route = self.request.matched_route.name self.layout.main_menu = make_main_menu(self.request).render() self.layout.ctx_menu = make_ctx_menu(self.request).output() if self.accounts is not None: self.odds = NFLOddsManager(self.request.db) self.bets = BetsManager(self.request.db) # make form resources available schema = CreditAmountSchema() form = deform.Form(schema, buttons=('submit',)) self.layout.resources.deform_auto_need(form) del schema, form # begin dispatch if self.route == 'home': self.main_view() return elif self.route == 'initdb': self.initialize_database() return if self.route == 'main': self.context = self.request.matchdict['context'] # make dispatch table self._cntxt_meth = dict( main=self.main_view, schedcal=self.schedule_view, initialize=self.initialize_database, ) if self.context in self._cntxt_meth: self._cntxt_meth[self.context]() else: msg = 'Undefined Context: %s' % self.context self.layout.content = '<b>%s</b>' % msg def main_view(self): authn_policy = self.request.context.authn_policy authn = authn_policy.authenticated_userid(self.request) if authn is None: self._unauthenticated_view() else: self._authenticated_view(authn) def _unauthenticated_view(self): if self.accounts is None: mkurl = self.request.route_url url = mkurl('initdb', context='initialize', id='database') msg = "Create Database" anchor = '<a class="action-button" href="%s">%s</a>' % (url, msg) content = anchor # clear context menu self.layout.ctx_menu = '' # clear main menu self.layout.main_menu = '' else: url = self.request.route_url('login') content = '<a href="%s">Login</a>' % url self.layout.content = content def _authenticated_view(self, authn): if self.is_admin_authn(authn): url = self.request.route_url('admin') self.response = HTTPFound(url) return else: return self.main_authenticated_view() def main_authenticated_view(self): self.layout.subheader = 'NFL Bettable Games' user_id = self.get_current_user_id() try: current, odata = self.bets.show_requested_bet(user_id) except NoCurrentBetError: current = None if current is not None: rfun = self.request.route_url url = rfun('vig_betgames', context='showbet', id='user') self.response = HTTPFound(url) return olist = self.odds.get_current_odds() collector = BettableGamesCollector(olist) dates = collector.dates.keys() dates.sort() game_date_format = '%A - %B %d' template = 'vignewton:templates/main-betgames-view.mako' env = dict(collector=collector, dates=dates, game_date_format=game_date_format) content = self.render(template, env) self.layout.content = content #self.layout.resources.lightbox.need() self.layout.resources.main_betgames_view.need() def main_admin_view(self): self.layout.content = "Main Admin View" def schedule_view(self): content = "Schedule Page" self.layout.content = content self.layout.subheader = 'Vig Newton' self.layout.resources.main_calendar_view.need() self.layout.resources.cornsilk.need() template = 'vignewton:templates/mainview-calendar.mako' env = {} content = self.render(template, env) self.layout.content = content def initialize_database(self): context = self.request.matchdict['context'] if context != 'initialize': self.layout.content = "Bad Call" return id = self.request.matchdict['id'] if id != 'database': self.layout.content = "Bad Call" return if self.accounts is None: from vignewton.models.initialize import initialize_database settings = self.get_app_settings() initialize_database(settings) self.layout.content = "Database Initialized" else: self.layout.content = "Unnecessary"