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 delete(collection, id): try: serverClient = FaunaClient(secret=os.environ.get("FAUNA_SERVER_SECRET")) serverClient.query(q.delete(q.ref(q.collection(collection), id))) return True except Exception as ex: raise ex
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 create_database(scheme, domain, port, secret, db_name): # # Create an admin client. This is the client we will use to create the database. # # If you are using the the FaunaDB-Cloud you will need to replace the value of the # 'secret' in the command below with your "secret". # adminClient = FaunaClient(secret=secret, domain=domain, scheme=scheme, port=port) print("Connected to FaunaDB as admin!") # # The code below creates the Database that will be used for this example. Please note that # the existence of the database is evaluated, deleted if it exists and recreated with a single # call to the Fauna DB. # res = adminClient.query( q.if_( q.exists(q.database(db_name)), [q.delete(q.database(db_name)), q.create_database({"name": db_name})], q.create_database({"name": db_name})) ) print('DB {0} created:'.format(db_name)) pprint.pprint(res) # # Create a key specific to the database we just created. We will use this to # create a new client we will use in the remainder of the examples. # res = adminClient.query(q.select(["secret"], q.create_key({"database": q.database(db_name), "role": "server"}))) print('DB {0} secret: {1}'.format(db_name, res)) return res
def main(argv): # # Create an admin client. This is the client we will use to create the database. # scheme = "http" domain = "127.0.0.1" port = "8443" secret = "secret" adminClient = FaunaClient(secret=secret, domain=domain, scheme=scheme, port=port) # # If you are using the the FaunaDB-Cloud use these lines to create the connection. # Change the secret to your value and comment out the lines above # # secret = "Your Secret Goes here" # adminClient = FaunaClient(secret=secret) dbName = "TestDB" # # Call to Create the database # res = adminClient.query(q.create_database({"name": dbName})) print('DB {0} created: {1}'.format(dbName, res)) # # Call to check to see if database exists and to delete it id it does. # res = adminClient.query( q.if_(q.exists(q.database(dbName)), q.delete(q.database(dbName)), True)) print('DB {0} deleted: {1}'.format(dbName, res))
def delete_project(id): try: client.query( q.delete(client.query(q.ref(q.collection("projects"), id)))) return True except: return False
async def asyncSetUp(self): # Turn off annoying logging about reset connections. getLogger("requests").setLevel(WARNING) self.root_client = self._get_client() rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(10)) self.db_name = "faunadb-python-test" + rnd self.db_ref = query.database(self.db_name) exists = await self.root_client.query(query.exists(self.db_ref)) if exists: await self.root_client.query(query.delete(self.db_ref)) await self.root_client.query( query.create_database({"name": self.db_name})) res = await self.root_client.query( query.create_key({ "database": self.db_ref, "role": "server" })) self.server_key = res["secret"] self.client = self.root_client.new_session_client( secret=self.server_key) res = await self.root_client.query( query.create_key({ "database": self.db_ref, "role": "admin" })) self.admin_key = res["secret"] self.admin_client = self.root_client.new_session_client( secret=self.admin_key)
def setUpClass(cls): super(FaunaTestCase, cls).setUpClass() # Turn off annoying logging about reset connections. getLogger("requests").setLevel(WARNING) cls.root_client = cls._get_client() rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(10)) cls.db_name = "faunadb-python-test" + rnd cls.db_ref = query.database(cls.db_name) if cls.root_client.query(query.exists(cls.db_ref)): cls.root_client.query(query.delete(cls.db_ref)) cls.root_client.query(query.create_database({"name": cls.db_name})) cls.server_key = cls.root_client.query( query.create_key({ "database": cls.db_ref, "role": "server" }))["secret"] cls.client = cls.root_client.new_session_client(secret=cls.server_key) cls.admin_key = cls.root_client.query( query.create_key({ "database": cls.db_ref, "role": "admin" }))["secret"] cls.admin_client = cls.root_client.new_session_client( secret=cls.admin_key)
def _delete_data(): resources = [q.functions(), q.indexes(), q.collections()] delete = lambda res: q.foreach( q.lambda_("res", q.delete(q.var("res"))), q.paginate(res) ) delete_queries = [delete(res) for res in resources] _execute_with_retries(q.do(*delete_queries))
def delete_appointment(update, context): chat_id = update.effective_chat.id message = update.message.text event_id = message.split("_")[1] client.query(q.delete(q.ref(q.collection("Appointments"), event_id))) context.bot.send_message(chat_id=chat_id, text="Successfully deleted appointment👌")
def test_do(self): ref = self._create()["ref"] self.assertEqual(self._q(query.do(query.delete(ref), 1)), 1) self.assertFalse(self._q(query.exists(ref))) self.assertEqual(self._q(query.do(1)), 1) self.assertEqual(self._q(query.do(1, 2)), 2) self.assertEqual(self._q(query.do([1, 2])), [1, 2])
def fauna_delete_database(self, **kwargs: str) -> Tuple[bool, Any, str]: """Fauna delete database.""" client = self.get_fauna_connection() database: str = kwargs["database"] try: return client.query(q.delete(q.database(database))) except (BadRequest) as _error: # pragma: no cover raise ValueError("Fauna error.") from _error
def delete_comment(self, comment_id: str): """ DELETE - Delete a comment """ try: deleted_comment = client.query( q.delete(q.ref(q.collection(self.collection), comment_id))) except (Exception, NotFound) as e: return None return deleted_comment['data']
def clear_loan(loan_id): client.query( q.delete( q.ref(q.collection("loans"), loan_id) ) ) flash("You have successfully cleared loan information!", "success") return redirect(url_for("loans"))
def delete_customer(client, cust_id): # # Delete the customer # res = client.query( q.delete( q.select("ref", q.get(q.match(q.index("customer_by_id"), cust_id))))) print('Delete \'customer\' {0}: {1}'.format(cust_id, res))
def delete(event, context): # delete the todo from the database client.query(query.delete(Ref(TODOS, event['pathParameters']['id']))) # create a response response = { "statusCode": 200 } return response
def delete_election(election_id): try: _ = client.query(q.get(q.ref(q.collection("Elections"), election_id))) except: return render_template('404.html') _ = client.query(q.delete(q.ref(q.collection("Elections"), election_id))) flash("The election have been deleted", "success") return redirect(url_for("dashboard"))
def delete_tweet(self, tweet_id: str): """ DELETE - Delete tweet based on tweet_id """ try: id = self.get_tweet(tweet_id)['ref'].id() deleted_tweet = client.query( q.delete(q.ref(q.collection(self.collection), id))) except (Exception, NotFound) as e: return None return deleted_tweet['data']
def delete(self, id): try: return client.query( q.delete( q.select( "ref", q.get( q.match(q.index(self.collection_name + "_by_id"), id)))))['data'] except NotFound: return 'Not found'
def delete_user(self, user_id: str): """ DELETE - Delete a user from the users collection. """ try: id = self.get_user(user_id)['ref'].id() deleted_user = client.query( q.delete(q.ref(q.collection(self.collection), id))) except (Exception, NotFound) as e: print(e) return None return deleted_user['data']
def delete_todo(update, context): chat_id = update.effective_chat.id message = update.message.text todo_id = message.split("_")[1] client.query(q.delete(q.ref(q.collection("todo"), todo_id))) context.bot.send_message( chat_id=chat_id, text= "Successfully deleted todo task status 👌\n\nAdd a new todo with /add_todo" )
def delete(self, pk: int) -> bool: """ Deletes object in FaunaDB :param pk: int - FaunaDB object id :return: success: bool """ try: object_data: dict = self.client.query( query.delete(self._expr_reference(pk), )) except NotFound: raise DoesNotExist return self._parse_pk(object_data) == pk
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 send_broadcast(args): print(args) try: updater.bot.send_message(chat_id=args[0], text=args[1]) except Unauthorized: # user blocked bot so delete user from list user = client.query(q.get(q.ref(q.collection(users), args[0]))) client.query(q.delete(user['ref'], )) logger.info("a user has been deleted from user list") return '' except Exception as err: log_error(err) return '' else: return 'success'
def test_singleton_events(self): instance_ref = self._create(n=1000)["ref"] self._q(query.update(instance_ref, {"data": {"n": 1001}})) self._q(query.delete(instance_ref)) events = self._q(query.paginate(query.events(query.singleton(instance_ref))))["data"] self.assertEqual(len(events), 2) self.assertEqual(events[0]["action"], "add") self.assertEqual(events[0]["document"], instance_ref) self.assertEqual(events[1]["action"], "remove") self.assertEqual(events[1]["document"], instance_ref)
def test_events(self): instance_ref = self._create(n=1000)["ref"] self._q(query.update(instance_ref, {"data": {"n": 1001}})) self._q(query.delete(instance_ref)) events = self._q(query.paginate(query.events(instance_ref)))["data"] self.assertEqual(len(events), 3) self.assertEqual(events[0]["action"], "create") self.assertEqual(events[0]["document"], instance_ref) self.assertEqual(events[1]["action"], "update") self.assertEqual(events[1]["document"], instance_ref) self.assertEqual(events[2]["action"], "delete") self.assertEqual(events[2]["document"], instance_ref)
def today_appointment(request): if "user" in request.session: try: appointments = client.query( q.paginate( q.match(q.index("events_today_paginate"), request.session["user"]["username"], str(datetime.date.today()))))["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())))["data"] if request.GET.get("complete"): client.query( q.update( q.ref(q.collection("Events"), appointments[page_number - 1].id()), {"data": { "status": "True" }}))["data"] return redirect("core:today-appointment") if request.GET.get("delete"): client.query( q.delete( q.ref(q.collection("Events"), appointments[page_number - 1].id()))) return redirect("core:today-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, "today-appointment.html", context) except: return render(request, "today-appointment.html") else: return HttpResponseNotFound("Page not found.")
def delete(self, post_id): try: post_id = post_id.encode('ascii', 'ignore') result = client.query(q.delete(q.ref(q.class_("posts"), post_id))) except fauna_error.NotFound as e: app.logger.debug(e) return Response( jsonify('Failed to delete a post - post not found.'), status=404, mimetype='application/json') except Exception as e: app.logger.debug(e) return Response(jsonify('Failed to delete a post.'), status=500, mimetype='application/json') return Response(json.dumps(to_json(result)), status=204, mimetype='application/json')
def translate_delete(sql_query: sql.SQLQuery) -> typing.List[QueryExpression]: """Translate a DELETE SQL query into an equivalent FQL query. Params: ------- sql_query: An SQLQuery instance. Returns: -------- An FQL query expression. """ tables = sql_query.tables if len(tables) > 1: document_set = common.join_collections(sql_query) else: document_set = common.build_document_set_union(tables[0], sql_query.filter_groups) return q.map_(q.lambda_("ref", q.delete(q.var("ref"))), q.paginate(document_set))
def on_start(event): self.assertEqual(event.type, 'start') self.assertTrue(isinstance(event.event, int)) self.root_client.query(query.delete(server_key["ref"])) self.client.query(query.update(ref, {"data": {"k": "v"}}))