def wrapper(handler, **kwargs): items = db.get_items(handler.dbc, handler.group.gameid, handler.sender_id) room = db.get_items(handler.dbc, handler.group.gameid, handler.chat_id) options = OrderedDict() if adding: # show special containers even if empty options['Room items'] = db.room_container options['Saved rolls'] = db.rolls_container else: # show special containers if not empty if db.room_container in room: options['Room items'] = db.room_container if db.rolls_container in items: options['Saved rolls'] = db.rolls_container for container in items.keys(): if container == db.rolls_container: continue else: options[container] = container if allownew: options['New container...'] = '__new__container__' handler.send(string, options=options, allowedit=True) kwargs['containercallback'] = func kwargs['argname'] = argname handler.read_answer(new_container_callback, 'newcontainer', kwargs) elif len(options) == 0: # no options to show handler.send('You don\'t seem to have anything with you.') return False else: handler.send(string, options=options, allowedit=True) handler.read_answer(func, argname, kwargs)
def wrapper(handler, container, **kwargs): if container == db.room_container: items = db.get_items(handler.dbc, handler.group.gameid, handler.chat_id) else: items = db.get_items(handler.dbc, handler.group.gameid, handler.sender_id) options = OrderedDict() for key, value in items[container].items(): options['{} ({})'.format(key, value)] = key handler.send(string, options=options, allowedit=True) kwargs['container'] = container handler.read_answer(func, argname, kwargs)
def get_tools(self): """ Returns a list of the tools. """ logger.debug("Getting the tools") return db.get_items('tools')
def pay(): payload = request.get_json() name = payload.get("name") email = payload.get("email") card = payload.get("card") tags = payload.get("tags") # collect all the items items = db.get_items(tags) # make sale db.make_sale(card, tags) # FIXME - refer to #36 - stripe api raises connection error # charge_id = payment_processor.send_invoice(name, email, items) # check payment status # resp = {"status": "pending"} # if payment_processor.is_paid(charge_id): # resp["status"] = "done" # return jsonify(resp) return jsonify({"status": "ok"})
def sync_all_account_regions(): # for each account and region do a sync in parallel (within account/region its sequential) print('Starting sync all accounts/regions at %s' % datetime.datetime.now()) accounts = [] db.get_connection() for account in models.Account.objects: for region in account.regions: accounts.append([account.account_number, region]) db.close() processes = {} for account in accounts: # account is [account_number, region] pname = '%s-%s' % (account[0], account[1]) p = Process(target=sync_account_region, args=(account), name=pname) print('Started', pname) p.start() processes[p.pid] = p print('Started', len(processes), 'processes') wait_for_processes(processes) db.get_connection() for account in db.get_items(models.Account, page_size=0, json_output=False): account.last_updated = datetime.datetime.utcnow() account.save() db.close() print('Ending sync cycle at %s' % datetime.datetime.now()) return
def get_keys(self): """ Returns a list of the keys. """ logger.debug("Getting the keys") return db.get_items('keys')
def siritai(): if request.method == 'POST': item_id = request.form['learn_cat'] print(item_id) # 教えたい側のdbから対応するユーザーidをとってくる user_ids = db.get_uids(item_id) # 別のページに移動+ユーザーidを渡す print(user_ids) item_name = db.get_item_name(item_id) for user_id in user_ids: print(user_id) firebase.put('', 'counselors/' + str(user_id), {'tag': item_name}) firebase.put('', 'rooms/room1/', { 'tag': item_name, 'caller': None, 'listener': 'in', 'chats': None }) return render_template('chat.html') return render_template("siritai.html", items=db.get_items())
def store(bot, update): """Handles the "kauppa" commad for the bot. Prints the products as buttons that can be used to buy products.""" if not is_registered(bot, update): return products = db.get_items() #print(products) y = 2 x = math.ceil(len(products) / y) keyboard = [[]] for i in range(x): row = [] for j in range(y): if j + i*y < len(products): prod = products[j + i*y][0] price = products[j + i*y][1] / 100 btn = InlineKeyboardButton("{} {:.2f}€".format(prod, price), callback_data = prod) row.append(btn) keyboard.append(row) keyboard.append([InlineKeyboardButton("Poistu", callback_data="Poistu")]) reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Mitä laitetaan?', reply_markup=reply_markup)
def hinnasto(bot, update): """Prints items in stock and their prices.""" items = db.get_items() text = "```\nHinnasto:\n" for i in items: text += "{:_<18.18} {:.2f}€\n".format(i[0].strip() + " ", i[1] /100) bot.send_message(update.message.chat.id, text + "```", parse_mode="MARKDOWN")
def items(): if request.method == 'GET': return jsonify({'items': get_items()}) elif request.method == 'POST': q.enqueue(record_item, request.get_json()) return jsonify({'ok': True}) else: abort(405)
def home_page(): global inputdata inputdata = db.get_items(0) if request.method == 'POST': item_name = request.form['name'] print(item_name) tempdata = db.find_items(0, item_name) return render_template('index.html', data=tempdata) return render_template('index.html', data=inputdata)
def loadItems(self,filter_value=''): items = db.get_items(filter_value) self.ui.itemsTable.setRowCount(len(items)) for i in range(len(items)): self.ui.itemsTable.setItem(i,0,qtw.QTableWidgetItem(str(items[i][1]))) self.ui.itemsTable.setItem(i,1,qtw.QTableWidgetItem(str(items[i][3]))) self.ui.itemsTable.setItem(i,2,qtw.QTableWidgetItem(str(items[i][4]))) self.ui.itemsTable.setItem(i,3,qtw.QTableWidgetItem(f'{Decimal(items[i][6]):.2f}')) self.ui.itemsTable.setItem(i,4,qtw.QTableWidgetItem(str(items[i][7])))
def checkout_request(payload): # set add_tag to False to stop the loop global add_tag add_tag = False # save the cart global cart cart = payload.get("data") print("===> cart:", cart) # tags is a list of tag reading values added in the cart tags = [] # total is the total value of all items in the cart total = 0 for k, v in cart.items(): # get rid of prefix $ and convert back to float total += float(v.get("cost")[1:]) tags.append(v.get("tag")) # wait for customer to tap their card # FIXME - sim print("reading card") card = card_reader.sim_read() print("finish reading card:", card) # validate the card if db.check_card(card): card_info = db.get_buyer(card) name = card_info.get("name") email = card_info.get("email") # collect all the items items = db.get_items(tags) # make sale db.make_sale(card, tags) # send a confirmation request to the customer # TODO - refer to #36. in short, frontend will make stripe payment payment_info = { "name": name, "email": email, "card": card, "tags": tags, "total": total, "msg": "a payment link will be sent to " + name + " (" + email + ")" } print(payment_info) # sleep for 5 seconds so that the websocket client is ready to listen again, # since it takes sometimes to load into a different page time.sleep(5); socketio.emit('checkout_response', payment_info, namespace='/checkout')
def get_items(): """Retrieves items.""" mediatype = request.args.get('mediatype', None) reviewmin = request.args.get('reviewmin', 0) reviewmax = request.args.get('reviewmax', 10) sort = request.args.get('sort', 'nameasc') return db.wrap_json( db.get_items(mediatype=mediatype, reviewmin=reviewmin, reviewmax=reviewmax, sort=sort))
def save_meta(fn): try: publishers = db.get_items(filename=fn, key="jpsps_cor:IssuerNameCoverPage".lower()) if not publishers: print(fn) return publisher = publishers[0] t = db.get_items(filename=fn, key="jpsps_cor:AccountingPeriodCoverPage".lower()) if not t: print("t", fn) return splited_t = space_split(t[0]) term=splited_t[0] term_from = convert(splited_t[1]) term_to = convert(splited_t[2]) db.insert_meta(fn, publisher, term, term_from, term_to) except: print(fn) print(traceback.format_exc()) sys.exit()
def oshietai(): if request.method == 'POST': item_ids = request.form.getlist('teach_cat') item_ids = list(map(int, item_ids)) print(item_ids) # 教えたい側のdbから対応するユーザーidをとってくる uid = db.register(item_ids) item_names = db.get_item_names(item_ids) # 別のページに移動 return render_template('thanks.html', user_id=uid, item_names=item_names) return render_template("checkbox.html", items=db.get_items())
def account_list(): if request.method == 'GET': items = db.get_items(models.Account, **request.args) # dont send the secret_key [i.pop('secret_key') for i in items['items']] return items elif request.method == 'POST': data = request.json creds = { 'aws_access_key_id': data.get('access_key', ''), 'aws_secret_access_key': data.get('secret_key', ''), 'role_arn': data.get('role_arn', '') } data['regions'] = data['regions'].split(",") _, account_id = get_boto3_resource('sts', creds=creds) models.Account(account_number=account_id, **data).save() return data['name']
def index(): '''Shows categories and latest items''' categories = db.get_categories() categories = [category.name for category in categories] items = db.get_items() latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in items] #NOQA (state, logged_in, username) = gplus.get_login_state() data = { 'categories': categories, 'latest_items': latest_items, 'state': state, 'logged_in': logged_in, 'username': username } return render_template('index.html', data = data)
def showgame(handler): gamename, template, groups, players = db.get_game_info( handler.dbc, handler.group.gameid) players_string = [ x + (' (gm)' if (y == db.ROLE_MASTER) else '') for x, y in players.items() ] ret = '{} ({})\nGroups: {}\nPlayers: {}'.format( gamename, db.game_templates[template], ', '.join(groups), ', '.join(players_string)) items = db.get_items(handler.dbc, handler.group.gameid, handler.chat_id) if db.room_container in items: room_items = [ ' - {}: {}\n'.format(key, items[db.room_container][key]) for key in sorted(items[db.room_container]) ] if len(room_items) > 0: ret += '\nRoom aspects:\n{}'.format('\n'.join(room_items)) handler.send(ret)
def index(): '''Shows categories and latest items''' categories = db.get_categories() categories = [category.name for category in categories] items = db.get_items() latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in items] #NOQA (state, logged_in, username) = gplus.get_login_state() data = { 'categories': categories, 'latest_items': latest_items, 'state': state, 'logged_in': logged_in, 'username': username } return render_template('index.html', data=data)
def show_player(handler, playerid=None): dbc = handler.dbc gameid = handler.group.gameid items = db.get_items(dbc, gameid, playerid) playername = db.get_player_name(dbc, gameid, playerid) if playername is None: handler.send('You are not in a game.') return ret = '' ret += 'Character sheet for {}:\n'.format(playername) if items is None: handler.send('No items found.') return for container in db.preferred_container_order: if container not in items: continue if container in db.preferred_key_order: keys = db.preferred_key_order[container] else: keys = [] ret += container + ':\n' # print keys in preferred order for key in keys: if key not in items[container]: continue ret += ' - {} ({})\n'.format(key, items[container][key]) del items[container][key] # print remaining keys for key in sorted(items[container]): ret += ' - {} ({})\n'.format(key, items[container][key]) del items[container] # print everything in remaining containers for container in items: ret += container + ':\n' for key in sorted(items[container]): ret += ' - {} ({})\n'.format(key, items[container][key]) handler.send(ret)
def tgw_attachment_list(): return db.get_items(models.TgwAttachment, **request.args)
def instance_list(): return db.get_items(models.Instance, **request.args)
def route_table_list(): return db.get_items(models.RouteTable, **request.args)
def task_list(): return db.get_items(models.VpcSyncTask, sort='-start_date', **request.args)
def security_group_list(): return db.get_items(models.SecurityGroup, **request.args)
def gconnect(): if is_logged_in(): categories = db.get_categories() categories = [category.name for category in categories] latest_items = db.get_items() latest_items = [[item.name, db.get_category_name_by_id(item.category_id)] for item in latest_items] #NOQA data = { 'categories': categories, 'latest_items': latest_items, 'logged_in': True, 'username': views.login_session['username'] } return render_template('index.html', data = data) if request.args.get('state') != views.login_session['state']: response = make_response(views.json.dumps('Invalid state paremeter'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = views.flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except views.FlowExchangeError: response = make_response(views.json.dumps('Failed to upgrade the authorization code.'), 401) #NOQA response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid: access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) #NOQA http = httplib2.Http() result = views.json.loads(http.request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(views.json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' # Verify that the access token is used for the intended user: gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response("Token's user ID doesn't match given user ID.", 401) #NOQA response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app: if result['issued_to'] != views.CLIENT_ID: response = make_response(views.json.dumps("Token's client ID does not match app's."), 401) #NOQA print("Token's client ID does not match app's.") response.headers['Content-Type'] = 'application/json' return response # Check to see if user is already logged in stored_credentials = views.login_session.get('credentials') stored_gplus_id = views.login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response(views.json.dumps("Current user is already connected."), 200) #NOQA response.headers['Content-Type'] = 'application/json' # Get user info userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo' params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params = params) data = views.json.loads(answer.text) # Store the access token in the session for later use. views.login_session['credentials'] = credentials.access_token views.login_session['gplus_id'] = gplus_id views.login_session['username'] = data['name'] # Add a new user if this user doesn't already exist user_id = db.get_user_id_by_name(data['name']) if not user_id: user_id = db.create_user(views.login_session) views.login_session['user_id'] = user_id return redirect('/')
return usersname if __name__ == "__main__": db = db.DB() print("****************Welcome to the Task Shop****************") print("Please login before continue.") username = input("Enter username: "******"Enter password: "******"admin": choice = get_admins_option() if choice == 1: items = db.get_items() for x in items: print("Item Name: {} \t Item Price: {}".format(x[1], x[2])) if choice == 2: item_name = input("Enter product name: ") price = int(input("Enter price: ")) add_product = db.insert_item(item_name, price, user[0]) if add_product: print("Product added successfully") if choice == 3: item_id = input("Enter ID to delete item: ") response = db.remove_item(item_id) if response: print("Item removed successfully!!!!!") if choice == 4: order_report = db.get_all_orders()
def vpc_list(): return db.get_items(models.Vpc, **request.args)
def get_items(): resp = Response(db.get_items(), 200) resp.headers['Access-Control-Allow-Origin'] = '*' return resp
def subnet_list(): return db.get_items(models.Subnet, **request.args)
def lb_list(): return db.get_items(models.LoadBalancer, **request.args)