def populate(): p1 = Person('Alice') p2 = Person('Anamika') p3 = Person('Annie') p4 = Person('Anson') p5 = Person('Bob') p6 = Person('Carol') p7 = Person('Don') p8 = Person('Evi') session.add_all([p1, p2, p3, p4, p5, p6, p7, p8]) orders = [(p1, 'veggies', 120), (p2, 'veggies', 20), (p3, 'veggies', 120), (p4, 'veggies', 10), (p5, 'veggies', 280), (p1, 'ketchup', 80), (p1, 'spices', 220), (p1, 'tissues', 50), (p1, 'notebooks', 90), (p5, 'ketchup', 80)] for person, name, price in orders: order = Order(person, name, price) session.add(order) p1 = Project('BSNL billing', 'alice') p2 = Project('BSNL payroll', 'bob') p3 = Project('ABC Institute', 'bob') pu1 = ProjectUser(p1, 'alice') pu2 = ProjectUser(p1, 'carol') pu3 = ProjectUser(p1, 'don') pu4 = ProjectUser(p2, 'alice') pu5 = ProjectUser(p2, 'carol') pu6 = ProjectUser(p3, 'don') pu7 = ProjectUser(p3, 'carol') session.add_all([p1, p2, p3, pu1, pu2, pu3, pu4, pu5, pu6, pu7]) session.commit()
def update_score(self, blob_score, pos_vader_score, neg_vader_score, nuetral_vader_score, compound_vader_score): #self._sentiment = self._sentiment + score # Totals are string because maximum int size would be exceeded in # timeframe. self.total_tweets = str(int(self.total_tweets) + 1) self.blob_score_total = str(int(self.blob_score_total) + round(blob_score)) self.pos_vader_score_total = str(int(self.pos_vader_score_total) + round(pos_vader_score)) self.neg_vader_score_total = str(int(self.neg_vader_score_total) + round(neg_vader_score)) self.nuetral_vader_score_total = str(int(self.nuetral_vader_score_total) + round(nuetral_vader_score)) self.compound_vader_score_total = str(int(self.compound_vader_score_total) + round(compound_vader_score)) vals = ( (blob_score, "blob_score_range_count_"), (pos_vader_score, "pos_vader_score_range_count_"), (neg_vader_score, "neg_vader_score_range_count_"), (nuetral_vader_score, "nuetral_vader_score_range_count_"), (compound_vader_score, "compound_vader_score_range_count_"), ) for score, prefix in vals: key = prefix + self._range(score) count = int(getattr(self, key)) setattr(self, key, str(count + 1)) session.add(self) session.commit()
def main(): c = Coord(id="test", x=0, y=0) print("c: " + str(coord_schema.dump(c).data)) session.add(c) session.commit() coords = session.query(Coord).all() print("all: " + str(coords_schema.dump(coords).data)) if len(sys.argv) > 1 and sys.argv[1] == "exit": return bottle.run(server='gunicorn', host='127.0.0.1', port=5000)
def create_user_bet(user_id, bet_id, deposit): """ Creates a currency for the user. Returns the created currency or None if not exists. """ user_bet = UserBet(user_id=user_id, bet_id=bet_id, deposit=deposit) session.add(user_bet) session.commit() return user_bet
def create_coord(): data = request.json coord = Coord(id=data['id'], x=data['x'], y=data['y']) session.add(coord) session.commit() response.headers['Content-Type'] = 'application/json' print(coord_schema.dump(coord).data) return coord_schema.dump(coord).data
def create_user_currency(user_id, short_code): """ Creates a currency for the user. Returns the created currency or None if not exists. """ currency = UserCurrency(user_id=user_id, short_code=short_code, amount=0) session.add(currency) session.commit() return currency
def create_bet(created_by, bet, rate): """ Creates a currency for the user. Returns the created currency or None if not exists. """ bet = Bet(created_by=created_by, bet=bet, rate=rate) session.add(bet) session.commit() return bet
def create_system_variable(variable, value): """ Creates and returns a system variable with given arguments. """ variable = System(variable=variable, value=value) session.add(variable) session.commit() return variable
def create_user(discord_id): """ Creates a new user in the database. Returns the created user or None if failed. """ user = User(discord_id=discord_id, creation_date=get_current_date()) session.add(user) session.commit() return user
def give_role_to_user(user_id, role_id): """ Gives a role to the user in database and Discord. Returns the given role or None if failed. """ role = UserRole(user_id=user_id, role_id=role_id) session.add(role) session.commit() return role
def delete_coord(coord_id): response.headers['Content-Type'] = 'application/json' coord = session.query(Coord).filter_by(coord_id=coord_id).first() if not coord: return json.dumps({'message': 'No coord found!'}) session.delete(coord) session.commit() return json.dumps({'message': 'The coord has been deleted!'})
def remove_currency_from_user(user_id, short_code, amount): """ Removes specified amount of currency to the user. Returns updated currency. """ currency = get_user_currency(user_id=user_id, short_code=short_code).first() if not currency: currency = create_user_currency(user_id, short_code) currency.amount -= amount session.commit() return currency
def add_currency_to_user(user_id, short_code, amount): """ Adds specified amount of currency to the user. Returns updated currency. """ currency = get_user_currency(user_id=user_id, short_code=short_code).first() if not currency: currency = create_user_currency(user_id, short_code) currency.amount += amount session.commit() return currency
async def bahissonucu(message, arguments): if message.author.permissions_in(message.channel).administrator: bet_id = int(arguments[0]) bet_result = int(arguments[1]) bet = get_bet(id=bet_id).first() if bet_result: await message.channel.send( _("Result of \"{bet}\": `WON`").format_map({"bet": bet.bet})) else: await message.channel.send( _("Result of \"{bet}\": `LOST`").format_map({"bet": bet.bet})) for bet_player in get_user_bet(bet_id=bet_id).all(): discord_user = await client.get_user_info( get_user(id=bet_player.user_id).first().discord_id) if bet_result: award = float(bet.rate * bet_player.deposit) add_currency_to_user(bet_player.user_id, Config.CURRENCY_CODE, award) await message.channel.send( _("{user} has successfully predicted this bet and won {award} {currency}." ).format_map({ "user": discord_user.name, "award": award, "currency": Config.CURRENCY_CODE })) else: await message.channel.send( _("{user} lost {deposit} {currency}.").format_map({ "user": discord_user.name, "deposit": bet_player.deposit, "currency": Config.CURRENCY_CODE })) session.delete(bet_player) session.commit() session.delete(bet) session.commit() else: await message.channel.send(_("You don't have access to this command."))
def update_currencies(): """ Downloads all available currencies and prepares the database. """ response = get("http://apilayer.net/api/live?access_key=%s" % (Config.APILAYER_KEY)).json() for currency_code in response["quotes"].keys(): currency = get_currency(short_code=currency_code[3:]).first() if not currency: currency = Currency(short_code=currency_code[3:]) session.add(currency) session.commit() currency.value = response["quotes"][ currency_code] / Config.CURRENCY_DIVIDER currency.last_update = get_current_date() session.commit()
async def on_message(message): # Parsing and forwarding the command, if message starts with bot prefix. if message.content.startswith(Config.COMMAND_PREFIX): command = message.content.split()[0][1:] arguments = [] try: arguments = message.content.split()[1:] except IndexError: pass try: await getattr(commands, command)(message, arguments) except Exception as e: logger.error(e) print(e) # Checking user, and adding to database if not exists. user = get_user(discord_id=message.author.id).first() if not user: user = create_user(discord_id=message.author.id) # Properly rewarding user for contribution. if not message.content.startswith(Config.COMMAND_PREFIX): message_length = len(message.content) add_currency_to_user(user.id, Config.CURRENCY_CODE, int(message_length / 5)) # Checking currency conversion data request time. last_update = get_system_variable("currency_last_update") if not last_update: last_update = create_system_variable("currency_last_update", get_current_date()) if (get_current_date() - datetime.strptime(last_update.value, "%Y-%m-%d %H:%M:%S.%f")) >= timedelta(hours=1): update_currencies() last_update.value = get_current_date() session.commit()
async def bahisoyna(message, arguments): if arguments: if int(arguments[0]) < 1: await message.channel.send(_("Invalid bet number.")) elif int(arguments[1]) < 1: await message.channel.send(_("Invalid bet amount.")) else: bet_id = int(arguments[0]) bet_amount = float(arguments[1]) bet = get_bet(id=arguments[0]).first() if bet is None: await message.channel.send(_("Invalid bet number.")) else: current_user = get_user(discord_id=message.author.id).first() user_currency = get_user_currency( currency_id=Config.CURRENCY_CODE, user_id=current_user.id).first() if user_currency is None or user_currency.amount < bet_amount: await message.channel.send( _("You don't have have enough {currency}.").format_map( {"currency": Config.CURRENCY_NAME})) else: remove_currency_from_user( get_user(discord_id=message.author.id).first().id, Config.CURRENCY_CODE, bet_amount) user_bet = get_user_bet(user_id=current_user.id, bet_id=bet.id).first() if user_bet: user_bet.deposit += bet_amount session.commit() await message.channel.send( _("You have added {bet_amount} {bet_currency} to your previous bet on #{bet_id}, making a total of {total_bet_amount} {bet_currency} on that bet." ).format_map({ "bet_id": bet.id, "bet_amount": bet_amount, "bet_currency": Config.CURRENCY_CODE, "total_bet_amount": user_bet.deposit })) else: user_bet = create_user_bet(current_user.id, bet.id, bet_amount) await message.channel.send( _("You betted {bet_amount} {bet_currency} for #{bet_id}." ).format_map({ "bet_id": bet.id, "bet_amount": bet_amount, "bet_currency": Config.CURRENCY_CODE })) else: await send_usage_message( message.channel, _("{prefix}bahisoyna (Bet Number) (Bet Amount)*").format_map( {"prefix": Config.COMMAND_PREFIX}))
>>> db.session.add(me) >>> db.session.commit() ''' ''' ENCODED BEFORE HASHING str('asd').encode('utf-8') ''' ''' to connect flask_login to user we use user_loader ''' ''' eg 1 updating in sqlalchemy user.no_of_logins += 1 session.commit() eg2 session.query().\ filter(User.username == form.username.data).\ update({"no_of_logins": (User.no_of_logins +1)}) session.commit() eg3 _______ INSERT one newToner = Toner(toner_id = 1,