def reviews(): if request.method == "GET": product = request.args.get('product') if product: data = client.query( q.map_( lambda x: q.get(x), q.paginate(q.match(q.index("reviews_by_product"), product)))) response = [i["data"] for i in data["data"]] for i in range(0, len(response)): response[i]['id'] = str(data["data"][i]["ref"].id()) return jsonify(data=response) data = client.query( q.map_(lambda x: q.get(x), q.paginate(q.documents(q.collection("reviews"))))) response = [i["data"] for i in data["data"]] for i in range(0, len(response)): response[i]['id'] = str(data["data"][i]["ref"].id()) return jsonify(data=response) elif request.method == "POST": request_data = request.get_json() response = client.query( q.create(q.collection("reviews"), {"data": request_data})) return jsonify(id=response["ref"].id())
def get_multiple(index, data=None): """ Get multiple records by ID """ try: serverClient = FaunaClient( secret=os.environ.get("FAUNA_SERVER_SECRET")) res_arr = [] if data is None: res = serverClient.query( q.map_(q.lambda_("data", q.get(q.var("data"))), q.paginate(q.match(q.index(index))))) res_arr.extend(res["data"]) elif isinstance(data, list): for x in data: res = serverClient.query( q.map_(q.lambda_("data", q.get(q.var("data"))), q.paginate(q.match(q.index(index), q.casefold(x))))) res_arr.extend(res["data"]) else: res = serverClient.query( q.map_(q.lambda_("data", q.get(q.var("data"))), q.paginate(q.match(q.index(index), q.casefold(data))))) res_arr.extend(res["data"]) arr = [] for x in res_arr: x["data"]["ref_id"] = x["ref"].id() arr.append(x["data"]) return arr except Exception as ex: raise ex
def products(): if request.method == "GET": category = request.args.get("category") or None if category: data = client.query( q.map_( lambda x: q.get(x), q.paginate( q.match(q.index("products_by_category"), category)))) response = [i["data"] for i in data["data"]] for i in range(0, len(response)): response[i]['id'] = str(data["data"][i]["ref"].id()) return jsonify(data=response) data = client.query( q.map_(lambda x: q.get(x), q.paginate(q.documents(q.collection("products"))))) response = [i["data"] for i in data["data"]] for i in range(0, len(response)): response[i]['id'] = str(data["data"][i]["ref"].id()) return jsonify(data=response) elif request.method == "POST": request_data = request.get_json() response = client.query( q.create(q.collection("products"), {"data": request_data})) return jsonify(id=response["ref"].id())
def test_lambda_query(self): invalid_lambda = lambda: query.add(1, 2) self.assertRaises(ValueError, lambda: self._q(query.map_(query.lambda_query(invalid_lambda), []))) expr = query.map_(query.lambda_query(lambda a: query.add(a, 1)), [1, 2, 3]) self.assertEqual(self._q(expr), [2, 3, 4])
def get(self, message_hash=None): if not message_hash: page = q.paginate(q.match(q.index("confirmed"), 'True')) ns = q.map_(lambda a: q.select(["data"], q.get(a)), page) result = client.query(ns)['data'] for message in result: messages[message['hash']] = message message_hash = random.choice(messages.keys()) message = fill_line(messages[message_hash]['title']) suggester = messages[message_hash]['suggester'] else: page = q.paginate(q.match(q.index("hash"), message_hash)) ns = q.map_(lambda a: q.select(["data"], q.get(a)), page) result = client.query(ns)['data'] if len(result) > 0: message = fill_line(result[0]['title']) suggester = result[0]['suggester'] else: raise tornado.web.HTTPError(404) self.output_message(message, message_hash, suggester) image = Image.new("RGBA", (300, 150), (255, 255, 255)) image_size = image.size # load the font and image font = ImageFont.truetype(fontFile, 18) # image = Image.open(imageFile) # firts you must prepare your text (you dont need this for english text) # text = unicode(message, "utf-8") text = message # start drawing on image draw = ImageDraw.Draw(image) lines = text_wrap(text, font, image_size[0] - 10) line_height = font.getsize('hg')[1] x = 10 y = 20 for line in lines: reshaped_text = arabic_reshaper.reshape(line) # correct its shape bidi_text = get_display(reshaped_text) # correct its direction # draw the line on the image x = image_size[0] - font.getsize(bidi_text)[0] - x draw.text((x, y), bidi_text, (0, 0, 0), font=font) # update the y position so that we can use it for next line y = y + line_height x = 10 # draw.text((10, 0), bidi_text, (0,0,0), font=font) draw = ImageDraw.Draw(image) # save it image.save("thumbnails/{}.png".format(message_hash))
def processHeroInformation(match_data): radiant_win = match_data['result']['radiant_win'] players = match_data['result']['players'] win_heros = [] heros_in_game = [] for player in players: win_flag = getWinFlag(player, radiant_win) heros_in_game.append(player['hero_id']) if win_flag: win_heros.append(player['hero_id']) hero_list=client.query( q.map_( q.lambda_( 'hero', q.get(q.ref(q.collection('heroes'), q.var('hero'))) ), heros_in_game ) ) update_hero_list = [] for hero_info in hero_list: ref = hero_info['ref'] data = hero_info['data'] if data['id'] in win_heros: data['wins'] += 1 data['games'] += 1 else: data['games'] += 1 for player in players: if player['hero_id'] == data['id']: getItemsData(player, data) update_info = {} update_info['ref'] = ref update_info['data'] = data update_hero_list.append(update_info) client.query( q.map_( q.lambda_( 'hero', q.update( q.select(['ref'], q.var('hero')), { 'data': q.select(['data'], q.var('hero')) } ) ), update_hero_list ) )
def read_list_of_customers(client, cust_list): # # Finally a much more general use case where we can supply any number of id values # and return the data for each. # res = client.query( q.map_( lambda x: q.select("data", q.get(x)), q.paginate( q.union( q.map_(lambda y: q.match(q.index("customer_by_id"), y), cust_list))))) print('Union variable \'customer\' {0}: {1}'.format(cust_list, res))
def test_map(self): # This is also test_lambda_expr (can't test that alone) self.assertEqual( self._q(query.map_(lambda a: query.multiply(2, a), [1, 2, 3])), [2, 4, 6]) self._create(n=10) self._create(n=10) self._create(n=10) page = query.paginate(query.match(self.n_index_ref, 10)) ns = query.map_(lambda a: query.select(["data", "n"], query.get(a)), page) self.assertEqual(self._q(ns), {"data": [10, 10, 10]})
def updatePairInformationForTeam(hero_ids, team_win): key_list=[] for k in range(0, len(hero_ids)): for j in range(k + 1, len(hero_ids)): if hero_ids[k] < hero_ids[j]: key = format(hero_ids[k], '03d') + format(hero_ids[j], '03d') else: key = format(hero_ids[j], '03d') + format(hero_ids[k], '03d') key_list.append(key) try: hero_data_list=client.query( q.map_( q.lambda_( 'hero_pair', q.get(q.ref(q.collection('hero_pairs'), q.var('hero_pair'))) ), key_list ) ) except Exception as e: logging.info(e) logging.info(key_list) hero_team_list=[] for hero_data in hero_data_list : hero_team_dictionary = {} hero_pair_ref=hero_data['ref'] hero_pair_data = hero_data['data'] hero_pair_data['games']+=1 if team_win: hero_pair_data['wins'] += 1 hero_team_dictionary['ref']=hero_pair_ref hero_team_dictionary['data']=hero_pair_data hero_team_list.append(hero_team_dictionary) client.query( q.map_( q.lambda_( 'hero_pair', q.update( q.select(['ref'],q.var('hero_pair')), {'data': q.select(['data'], q.var('hero_pair'))} ) ), hero_team_list ) )
def processTemporalHeroInformation(match_data): radiant_win = match_data['result']['radiant_win'] players = match_data['result']['players'] temporal_hero_list = [] for player in players: win_flag = False if player['player_slot'] <= 4 and radiant_win: win_flag = True elif player['player_slot'] > 4 and not radiant_win: win_flag = True temporal_hero = {} temporal_hero['id'] = player['hero_id'] temporal_hero['win'] = win_flag temporal_hero['match_start_time'] = pytz.utc.localize(datetime.utcfromtimestamp(match_data['result']['start_time'])) temporal_hero_list.append(temporal_hero) client.query( q.map_( q.lambda_( 'temporal_hero', q.create(q.collection('heroes_temporal'), { "data": q.var('temporal_hero') }) ), temporal_hero_list ) )
def create_collection(client): collections = ["products", "users", "orders", "categories", "users"] client.query( q.map_( lambda collection_name: q.if_( q.exists(q.collection(collection_name)), True, q.create_collection({"name": collection_name})), collections))
def _sort_document_set(document_set: QueryExpression, order_by: typing.Optional[sql.OrderBy]): if order_by is None: return q.paginate(document_set, size=common.MAX_PAGE_SIZE) if len(order_by.columns) > 1: raise exceptions.NotSupportedError( "Ordering by multiple columns is not yet supported.") ordered_column = order_by.columns[0] assert ordered_column.table_name is not None ordered_document_set = q.join( document_set, q.index( common.index_name( ordered_column.table_name, column_name=ordered_column.name, index_type=common.IndexType.SORT, )), ) if order_by.direction == sql.OrderDirection.DESC: ordered_document_set = q.reverse(ordered_document_set) return q.map_( q.lambda_(["_", "ref"], q.var("ref")), q.paginate(ordered_document_set, size=common.MAX_PAGE_SIZE), )
def unsubscribe(update: Update, context: CallbackContext): user = User(update.effective_chat.id) try: animes_watched = client.query( q.let({'bot_user': q.ref(q.collection(users), user.chat_id)}, q.if_( q.exists(q.var('bot_user')), q.map_( q.lambda_('doc_ref', q.get(q.var('doc_ref'))), q.select(['data', 'animes_watching'], q.get(q.var('bot_user')))), []))) for anime in animes_watched: markup = [[ InlineKeyboardButton('Unsubscribe', callback_data='unsubscribe=' + anime['ref'].id()) ]] context.bot.send_message(chat_id=user.chat_id, text=anime['data']['title'], reply_markup=InlineKeyboardMarkup(markup)) # update last command user.last_command = '' if not animes_watched: context.bot.send_message( chat_id=user.chat_id, text='You are currently not subscribed to any anime') except Exception as err: log_error(err)
def create_customers(client, num_customers, init_balance): # # Create 'numCustomers' customer records with ids from 1 to 'numCustomers' # # in this example we use a list of dictionary items to build the 'data' # payload for the create function in Fauna # # THe return is a list of Fauna RefV that can be used to access records # directly. # cust_list = [] for cust_id in range(1, num_customers + 1): customer = {"id": cust_id, "balance": init_balance} cust_list.append(customer) res = client.query( q.map_( lambda customer: q.create(q.class_("customers"), {"data": customer}), cust_list) ) print('Create {0} customers:'.format(num_customers)) cust_refs = [] for cust_ref in res: cust_refs.append(cust_ref['ref']) return cust_refs
def read_all_customers(client): # # Read all the records that we created. This is a more generalized usage of the # paginate functionality. Notice the capture and passing of the "after" cursor # that is part of the return of the paginate if records are remaining. # # Use a small'ish page size so that we can demonstrate a paging example. # # NOTE: after is inclusive of the value. # pageSize = 8 cursorPos = None while True: res = client.query( q.map_( lambda x: q.select("data", q.get(q.select(1, x))), q.paginate(q.match(q.index("customer_id_filter")), after=cursorPos, size=pageSize))) for i in res['data']: print(i) if 'after' in res: cursorPos = res['after'] else: break
def user_contacts(user): contacts = s_client.query( q.map_( q.paginate( q.match(q.index("contacts_by_username"), user['data']['username'])), lambda x: q.get(x))) print(contacts)
def _create_documents(let_params, records, build_document): results = [] idx = 0 while True: if idx > len(records): break end_idx = idx + BATCH_LIMIT batch = _execute_with_retries( q.let( let_params, q.map_( q.lambda_( "document", q.create( q.var("collection"), {"data": build_document(q.var("document"))}, ), ), records[idx:end_idx], ), ) ) results.extend(batch) idx = end_idx return results
def _load_matches(data): matches = data["matches"] records = list(matches.values()) build_document = lambda match: q.to_object( q.map_( q.lambda_( ["key", "value"], [ q.var("key"), q.if_( q.equals(q.var("key"), "winner_id"), _assign_ref(q.var("teams"), q.var("team_map"), q.var("value")), q.var("value"), ), ], ), q.to_array(match), ) ) let_params = { "collection": q.collection("matches"), "teams": q.collection("teams"), "team_map": data["teams"], } documents = _create_documents(let_params, records, build_document) for record, document in zip(records, documents): record["id"] = document["ref"].id()
def get_orders(secret, after=None, before=None, size=5): client = FaunaClient(secret=secret) return client.query( q.map_( lambda ref: q.get(ref), q.paginate(q.documents(q.collection('orders')), size=size, after=after, before=before) ) )
def get_categories(after=None, before=None, size=5): return fauna.query( q.map_( lambda ref: q.get(ref), q.paginate(q.documents(q.collection('categories')), size=size, after=after, before=before)))
async def read_get_snippet() -> dict: result = client.query( q.map_(lambda x: q.get(x), q.paginate(q.match(q.index("all_snippets"))))) result = result['data'] obj = result[random.randint(0, len(result) - 1)] return obj['data']
def get_all_students(self): result = self.clientf.query( query.map_( query.lambda_("x", query.get(query.var('x'))), query.paginate(query.match(query.index('all_students')), size=1000))) students = result['data'] students = [student['data'] for student in students] return students
def create_customers(client): # # Create 20 customer records with ids from 1 to 20 # client.query( q.map_( lambda id: q.create(q.class_("customers"), {"data": { "id": id, "balance": 100.0 }}), list(range(1, 21))))
def get_subscribed_users_for_anime(anime_doc_id): """ This function gets all the user subscribed to a particular anime """ subscribed_users = client.query( q.map_( q.lambda_('doc_ref', q.get(q.var('doc_ref'))), q.paginate(q.match(q.index(all_users_by_anime), q.ref(q.collection(animes), str(anime_doc_id))), size=100000))) subscribed_users = subscribed_users['data'] return subscribed_users
def get(self, post_title=None): try: if post_title: posts = client.query( q.map_( lambda x: q.get(x), q.paginate( q.match(q.index("posts_by_title"), post_title)))) else: posts = client.query( q.map_(lambda x: q.get(x), q.paginate(q.match(q.index("all_posts"))))) except Exception as e: app.logger.debug(e) return Response(jsonify('Failed to fetch posts.'), status=500, mimetype='application/json') return Response(json.dumps(to_json(result)), status=200, mimetype='application/json')
def wordPartsGenerator(word): return q.let( { "indexes": q.map_( # Reduce this array if you want less ngrams per word. # Setting it to [ 0 ] would only create the word itself, Setting it to [0, 1] would result in the word itself # and all ngrams that are one character shorter, etc.. lambda index: q.subtract(q.length(word), index), maxNgrams), "indexesFiltered": q.filter_( # left min parts length 3 lambda l: q.gte(l, 3), q.var('indexes')), "ngramsArray": q.distinct( q.union( q.map_(lambda l: q.ngram(q.lowercase(word), l, l), q.var('indexesFiltered')))) }, q.var('ngramsArray'))
def list(self, limit: int = 10) -> List[BaseModel]: """ Returns list of objects :param limit: int - limit for pagination :return: objects: List[Model] """ object_list: dict = self.client.query( query.map_(lambda ref: query.get(ref), self._expr_documents(limit=limit))) return [ self._parse_model_instance(object_data=object_data) for object_data in object_list['data'] ]
def read_three_customers(client, cust_id1, cust_id2, cust_id3): # # Here is a more general use case where we retrieve multiple class references # by id and return the actual data underlying them. # res = client.query( q.map_( lambda x: q.select("data", q.get(x)), q.paginate( q.union(q.match(q.index("customer_by_id"), cust_id1), q.match(q.index("customer_by_id"), cust_id2), q.match(q.index("customer_by_id"), cust_id3))))) print('Union specific \'customer\' 1, 3, 8: {0}'.format(res))
def read_customers_less_than(client, max_cust_id): # # In this example we use the values based filter 'customer_id_filter'. # using this filter we can query by range. This is an example of returning # all the values less than(<) or before 5. The keyword 'after' can replace # 'before' to yield the expected results. # res = client.query( q.map_( lambda x: q.select("data", q.get(q.select(1, x))), q.paginate(q.match(q.index("customer_id_filter")), before=[max_cust_id]))) print('Query for id\'s < {0} : {1}'.format(max_cust_id, res))
def read_customers_between(client, min_cust_id, max_cust_id): # # Extending the previous example to show getting a range between two values. # res = client.query( q.map_( lambda x: q.select("data", q.get(q.select(1, x))), q.filter_( lambda y: q.lte(min_cust_id, q.select(0, y)), q.paginate(q.match(q.index("customer_id_filter")), before=[max_cust_id])))) print('Query for id\'s > {0} and < {1} : {2}'.format( min_cust_id, max_cust_id, res))