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 create_question(request): quiz_all=client.query(q.paginate(q.match(q.index("quiz_get_index"), "active"))) all_quiz=[] for i in quiz_all["data"]: all_quiz.append(q.get(q.ref(q.collection("Quiz"),i.id()))) context = {"quiz_all":client.query(all_quiz)} if request.method=="POST": quiz_name=request.POST.get("quiz_name") question_asked=request.POST.get("question") answer_1=request.POST.get("answer_1") answer_2=request.POST.get("answer_2") answer_3=request.POST.get("answer_3") answer_4=request.POST.get("answer_4") correct_answer=request.POST.get("correct_answer") try: question_create = client.query(q.get(q.match(q.index("question_index"), question_asked))) messages.add_message(request, messages.INFO, 'This question already exists') return redirect("App:create-question") except: question_create = client.query(q.create(q.collection("Question"), { "data": { "quiz_name": quiz_name, "question_asked": question_asked, "answer_1": answer_1, "answer_2": answer_2, "answer_3": answer_3, "answer_4": answer_4, "correct_answer": correct_answer, } })) messages.add_message(request, messages.INFO, 'Question Created Successfully.') return redirect("App:create-question") return render(request,"create-questions.html",context)
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 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 schema(event, context): create_todos = query.create_class({ 'name': 'todos' }) create_all_todos = query.create_index({ 'name': 'all_todos', 'source': TODOS }) client.query(query.if_expr( query.exists(TODOS), query.get(TODOS), create_todos )) client.query(query.if_expr( query.exists(ALL_TODOS), query.get(ALL_TODOS), create_all_todos )) # create a response response = { "statusCode": 200 } return response
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 login(data): try: return current_app.fauna_client.query( q.let( { 'response': q.login( q.match(q.index('unique_account_username_type'), [data.get('username'), 'EMAIL']), {'password': data.get('password')}), 'user': q.select_with_default( ['data', 'user'], q.get(q.select(['instance'], q.var('response'))), None) }, { 'data': { 'token': q.select('secret', q.var('response')), 'user': q.if_( q.is_ref(q.var('user')), q.select(['data', 'alias'], q.get(q.var('user'))), None) } })) except Exception as e: print(e)
def create_user(data): try: current_identity = get_current_identity() email_hash = md5( current_identity['data']['username'].encode('utf-8')).hexdigest() return current_app.fauna_client.query( q.if_( q.is_ref( q.select_with_default(['data', 'user'], q.get(q.current_identity()), None)), q.abort('exists'), q.let( { 'userMetaRef': q.new_id(), 'userRef': q.new_id() }, q.do( q.create( q.ref(q.collection('user_metas'), q.var('userMetaRef')), { 'data': { 'name': data.get('name'), 'email': q.select(['data', 'username'], q.get(q.current_identity())), 'dob': parser.parse(data.get('dob')).date() } }), q.create( q.ref(q.collection('users'), q.var('userRef')), { 'data': { 'alias': data.get('alias'), 'avatar': f'https://www.gravatar.com/avatar/{email_hash}', 'public': False, 'meta': q.ref(q.collection('user_metas'), q.var('userMetaRef')), } }), q.update( q.current_identity(), { 'data': { 'user': q.ref(q.collection('users'), q.var('userRef')) } }), q.call('current_user', []))))) except Exception as e: if str(e) == 'exists': abort(409, 'User for current identity already exists.') print(e)
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 event_id_from_project_id(project_id): return int( client.query( q.get( q.match( q.index("event_by_region_name"), client.query( q.get(q.ref( q.collection("projects"), project_id)))['data']['region'])))['ref'].id())
def test_remove(self): document = self._create(n=0) ref = document["ref"] # Change it new_instance = self._q(query.replace(ref, {"data": {"n": 1}})) self.assertEqual(self._q(query.get(ref)), new_instance) # Delete that event self._q(query.remove(ref, new_instance["ts"], "create")) # Assert that it was undone self.assertEqual(self._q(query.get(ref)), document)
def unsubscribe_from_anime(self, anime_doc_id: str): try: anime = client.query( q.get(q.ref(q.collection(animes), anime_doc_id))) client.query( q.let( { 'anime_ref': q.ref(q.collection(animes), anime_doc_id), 'bot_user': q.ref(q.collection(users), self.chat_id), 'followers': q.select(['data', 'followers'], q.get(q.var('anime_ref'))), }, q.do( q.update( q.var('anime_ref'), { 'data': { 'followers': q.subtract( q.var('followers'), 1) } }), q.update( q.var('bot_user'), { 'data': { 'animes_watching': q.filter_( q.lambda_( 'watched_anime_ref', q.not_( q.equals( q.var('watched_anime_ref'), q.var('anime_ref')))), q.select(['data', 'animes_watching'], q.get(q.var('bot_user')))) } }), q.if_(q.equals(q.var('followers'), 1), q.delete(q.var('anime_ref')), 'successful!')))) updater.bot.send_message(chat_id=self.chat_id, text='You have stopped following ' + anime['data']['title']) except errors.NotFound: logger.info( 'Somehow, a user {0} almost unsubscribed from an anime that did not exist' .format(self.chat_id)) except Exception as err: log_error(err)
def view_profile(username): try: user = client.query(q.get(q.match(q.index("users_index"), username))) except: abort(404) question_indexes = client.query( q.paginate(q.match(q.index("questions_index"), True, username), size=100_000)) questions = [ q.get(q.ref(q.collection("questions"), i.id())) for i in question_indexes["data"] ] return render_template("view-profile.html", username=username, questions=client.query(questions)[::-1])
def login(): if "user" in session: return redirect(url_for("dashboard")) if request.method == "POST": username = request.form.get("username").strip().lower() password = request.form.get("password") next_url = request.form.get("next") try: user = client.query( q.get(q.match(q.index("users_index"), username))) if hashlib.sha512( password.encode()).hexdigest() == user["data"]["password"]: session["user"] = { "id": user["ref"].id(), "username": user["data"]["username"] } if next_url: return redirect(next_url) redirect(url_for('dashboard')) else: flash( "You have supplied invalid login credentials, please try again!", "danger") except: flash("Network error, try again", "danger") return redirect(url_for("login", next=next_url)) return render_template("login.html")
def read_customer(client, cust_id): # # Read the customer we just created # res = client.query( q.select("data", q.get(q.match(q.index("customer_by_id"), cust_id)))) print('Read \'customer\' {0}: {1}'.format(cust_id, res))
def questions(): username = session["user"]["username"] question_type = request.args.get("type", "all").lower() if question_type == "answered": question_indexes = client.query( q.paginate(q.match(q.index("questions_index"), True, username), size=100_000)) elif question_type == "unanswered": question_indexes = client.query( q.paginate(q.match(q.index("questions_index"), False, username), size=100_000)) elif question_type == "all": question_indexes = client.query( q.paginate(q.union( q.match(q.index("questions_index"), True, username), q.match(q.index("questions_index"), False, username)), size=100_000)) else: return redirect(url_for("questions")) questions = [ q.get(q.ref(q.collection("questions"), i.id())) for i in question_indexes["data"] ] return render_template("questions.html", questions=client.query(questions)[::-1])
def register(request): if request.method == "POST": username = request.POST.get("username").strip().lower() email = request.POST.get("email").strip().lower() password = request.POST.get("password") try: user = client.query( q.get(q.match(q.index("users_index"), username))) messages.add_message(request, messages.INFO, 'User with that username already exists.') return redirect("core:register") except: user = client.query( q.create( q.collection("Users"), { "data": { "username": username, "email": email, "password": hashlib.sha512(password.encode()).hexdigest(), "date": datetime.datetime.now(pytz.UTC) } })) messages.add_message(request, messages.INFO, 'Registration successful.') return redirect("core:login") return render(request, "register.html")
def update_documents(sql_query: sql.SQLQuery) -> QueryExpression: """Update document fields with the given values. Params: ------- table: Table object that contains the parameters for building an update query in FQL. Returns: -------- An FQL update query for the given collection and documents. """ assert len(sql_query.tables) == 1 table = sql_query.tables[0] assert len(sql_query.filter_groups) <= 1 filter_group = (None if not any(sql_query.filter_groups) else sql_query.filter_groups[0]) field_updates = {column.name: column.value for column in table.columns} return q.let( {"document_set": build_document_set_intersection(table, filter_group)}, q.do( q.update( q.select( "ref", q.get(q.var("document_set")), ), {"data": field_updates}, ), {"data": [{ "count": q.count(q.var("document_set")) }]}, ), )
def all_appointment(request): if "user" in request.session: try: appointments = client.query( q.paginate( q.match(q.index("events_index_paginate"), request.session["user"]["username"])))["data"] appointments_count = len(appointments) page_number = int(request.GET.get('page', 1)) appointment = client.query( q.get( q.ref(q.collection("Events"), appointments[page_number - 1].id()))) if request.GET.get("delete"): client.query( q.delete( q.ref(q.collection("Events"), appointments[page_number - 1].id()))) return redirect("core:all-appointment") context = { "count": appointments_count, "appointment": appointment, "page_num": page_number, "next_page": min(appointments_count, page_number + 1), "prev_page": max(1, page_number - 1) } return render(request, "all-appointments.html", context) except: return render(request, "all-appointments.html") else: return HttpResponseNotFound("Page not found!") return render(request, "all-appointments.html")
def ask_question(username): try: user = client.query(q.get(q.match(q.index("users_index"), username))) except: abort(404) if request.method == "POST": user_asking = request.form.get("user_asking", "").strip().lower() question_text = request.form.get("question").strip() question = client.query( q.create( q.collection("questions"), { "data": { "resolved": False, "user_asked": username, "question": question_text, "user_asking": "anonymous" if user_asking == "" else user_asking, "answer": "", "date": datetime.now(pytz.UTC) } })) flash(f"You have successfully asked {username} a question!", "success") return redirect(url_for("ask_question", username=username)) return render_template("ask-question.html", username=username)
def create_appointment(request): if "user" in request.session: if request.method == "POST": name = request.POST.get("name") description = request.POST.get("description") time = request.POST.get("time") date = request.POST.get("date") try: user = client.query( q.get(q.match(q.index("events_index"), date, time))) messages.add_message( request, messages.INFO, 'An Event is already scheduled for the specified time.') return redirect("core:create-appointment") except: user = client.query( q.create( q.collection("Events"), { "data": { "name": name, "description": description, "time": time, "date": date, "user": request.session["user"]["username"], "status": 'False', } })) messages.add_message(request, messages.INFO, 'Appointment Scheduled Successfully.') return redirect("core:create-appointment") return render(request, "appoint/create-appointment.html") else: return HttpResponseNotFound("Page not found!")
def register(): if request.method == "POST": username = request.form.get("username").strip().lower() password = request.form.get("password") try: user = client.query( q.get(q.match(q.index("users_index"), username))) flash("The account you are trying to create already exists!", "danger") except: user = client.query( q.create( q.collection("users"), { "data": { "username": username, "password": encrypt_password(password), "date": datetime.now(pytz.UTC) } })) flash( "You have successfully created your account, you can proceed to login!", "success") return redirect(url_for("register")) return render_template("register.html")
def update_loan(): action = request.form.get("action") amount = request.form.get("amount") loan_id = request.form.get("loanID") loan_data = client.query( q.get( q.ref(q.collection("loans"), int(loan_id)) ) ) old_amount = loan_data["data"]["amount"] if action == "Borrow More": new_amount = old_amount + float(amount) elif action == "Repay Loan": new_amount = old_amount - float(amount) client.query( q.update( q.ref(q.collection("loans"), int(loan_id)), { "data": { "amount": new_amount } } ) ) flash("You have successfully updated loan information!", "success") return redirect(url_for("loans"))
def login(): if "user" in session: return redirect(url_for("dashboard")) if request.method == "POST": username = request.form.get("username").strip().lower() password = request.form.get("password") try: user = client.query( q.get(q.match(q.index("users_index"), username))) if encrypt_password(password) == user["data"]["password"]: session["user"] = { "id": user["ref"].id(), "username": user["data"]["username"] } return redirect(url_for("dashboard")) else: raise Exception() except: flash( "You have supplied invalid login credentials, please try again!", "danger") return redirect(url_for("login")) return render_template("login.html")
async def scrape_article(article: ReadingReference, response: Response): if NHK_PREFIX in article.url: try: # see if an article exists client.query(q.get(q.match(q.index('reading_by_url'), article.url))) return {"success": True, "status": "DocumentExists"} except: # scrape article and save article = requests.get(article.url) soup = BeautifulSoup(article.content, 'html.parser') article_body_text = soup.find( class_='article-main__body').get_text() article_title_text = soup.find( class_='article-main__title').get_text() client.query( q.create( q.collection('Reading'), { "data": { "reading_url": article.url, "article_title": article_title_text, "text": article_body_text } })) response.status_code = status.HTTP_201_CREATED return {"success": True, "status": "CreatedDocument"} else: response.status_code = status.HTTP_400_BAD_REQUEST return {"success": False, "status": "UnknownArticleType"}
def echo(update, context): chat_id = update.effective_chat.id message = update.message.text user = client.query(q.get(q.match(q.index("users"), chat_id))) last_command = user["data"]["last_command"] if last_command == "add_todo": todo = client.query( q.create( q.collection("todo"), { "data": { "user_id": chat_id, "todo": message, "completed": False, "date": datetime.now(pytz.UTC) } })) client.query( q.update(q.ref(q.collection("users"), user["ref"].id()), {"data": { "last_command": "" }})) context.bot.send_message( chat_id=chat_id, text= "Successfully added todo task 👍\n\nSee all your todo with /list_todo" )
def start_quiz(update, context): ''' Starts the quiz and gets the questions from aloc API, then saves to database ''' chat_id = update.effective_chat.id message = update.message.text try: name = update["message"]["chat"]["first_name"] except: name = update["message"]["chat"]["username"] subject = message.split('_')[1] questions = get_questions(subject=subject, mode='utme') quiz = client.query( q.create( q.collection("quiz"), { "data": { "user_id": chat_id, "subject": subject, "answered": 0, "score": 0, "id_": random.randint(0, 100), 'completed': False, 'questions': questions, } })) user = client.query(q.get(q.match(q.index("users"), chat_id))) client.query( q.update(q.ref(q.collection("users"), user["ref"].id()), {"data": { "last_command": "start_quiz" }})) msg = f"{subject.upper()}\n\n10 questions, enter 'q' to continue\n\n/end_quiz to end the quiz session." context.bot.send_message(chat_id=chat_id, text=msg)
def product(id): if request.method == "GET": try: response = client.query(q.get(q.ref(q.collection("products"), id))) return jsonify(data=response["data"]) except errors.NotFound: return jsonify(data=None) elif request.method == "PUT": # update a products document try: response = client.query( q.update(q.ref(q.collection("products"), id), {"data": response.get_json()})) except Exception as e: return jsonify(error=str(e)) elif request.method == "DELETE": # delete a reviews document try: response = client.query( q.delete(q.ref(q.collection("products"), id))) return response except Exception as e: return jsonify(error=str(e))
def start(update, context): ''' Starts the bot and saves the user details if it is not existing ''' chat_id = update.effective_chat.id try: name = update["message"]["chat"]["first_name"] except: name = update["message"]["chat"]["username"] try: client.query(q.get(q.match(q.index("users"), chat_id))) except: client.query( q.create( q.collection("users"), { "data": { "id": chat_id, "name": name, "last_command": "", "date": datetime.now(pytz.UTC) }, })) botler = Botler().get() msg = messenger.get(name, botler) context.bot.send_message(chat_id=chat_id, text=msg)
def add_book(request): if request.method=="POST": title= request.POST.get("title") genres=request.POST.get("genres") summary=request.POST.get("summary") pages=request.POST.get("pages") copies=request.POST.get("copies") author= request.POST.get("author") about=request.POST.get("about") try: book = client.query(q.get(q.match(q.index("book_index"), title))) messages.add_message(request, messages.INFO, 'Book Already Exists') return redirect("App:add_book") except: book = client.query(q.create(q.collection("Books"), { "data": { "title":title, "genres": genres, "summary": summary, "pages":pages, "copies":copies, "author":author, "about":about, "availability":"True" } })) messages.add_message(request, messages.INFO, 'Book added Successfully') return redirect("App:add_book") return render(request,"add-book.html")
def detail(request,slug): try: book= client.query(q.get(q.match(q.index("book_index"), slug)))["data"] context={"book":book} return render(request,"detail.html",context) except: return render(request,"detail.html")
def get(event, context): # fetch todo from the database ref = Ref(TODOS, event['pathParameters']['id']) fetched = client.query(query.get(ref)) # create a response response = { "statusCode": 200, "body": json.dumps(make_result(fetched)) } return response
def list(event, context): # fetch all todos from the database results = client.query( query.map_expr(lambda ref: query.get(ref), query.paginate(query.match(ALL_TODOS)))) # create a response response = { "statusCode": 200, "body": json.dumps(map(make_result, results['data'])) } return response