async def post(self): before_users = await User.query.all() username = self.request.post["username"] password = self.request.post["password"] first_name = self.request.post["first_name"] last_name = self.request.post["last_name"] await create_user( username, password, first_name=first_name, last_name=last_name, is_staff=True, is_superuser=False, ) first_user = await User.query.first() new_user = await User.query.last() after_users = await User.query.all() await login(self.request, username, password) response = JSONResponse( self.request, { "first_username": first_user["username"], "username": new_user["username"], "len_before": len(before_users), "len_after": len(after_users), "names_after": [x["username"] for x in after_users], }, ) return response
async def __call__(self, scope, receive, send): if self.request.method == "POST": self.context = {"data": self.request.post["data"]} response = JSONResponse(self.request, self.context) else: response = TextResponse(self.request, "Text content") await response(scope, receive, send)
async def post(self): """ Create new customer :return: 201 {"success": "Created"} :return: 400 Bad Request :par bulk: true :par first_name: str required :par username: str :par password: str :par bio: str """ if self.request.post: # This for compatibility with swagger and vue both if isinstance(self.request.post, str): self.request.post = json.loads(self.request.post) if "users" in self.request.post: data = self.request.post["users"] else: data = self.request.post if isinstance(data, str): data = json.loads(data) try: await CustomerB.query.bulk_insert(values=data) self.context = {"success": "Created"} except Exception as e: self.context = {"error": str(e)} else: self.context = {"error": "No data for creation given"} response = JSONResponse(self.request, self.context) return response
async def get(self): """ Get customer's discounts list """ if not self.request.params: self.context = await CustomerDiscount.query.all() response = JSONResponse(self.request, self.context) return response
async def patch(self): """ Update customer """ CustomerB.query.execute(CustomerB.table.update().where( CustomerB.c.id == self.request.params["customer_id"]).values( {"first_name": "Fred"})) response = JSONResponse(self.request, self.context) return response
async def post(self): """ :par pic: file :content_type: multipart/form-data """ if self.request.files: await self.request.files["pic"].save() response = JSONResponse(self.request, self.request.post) return response
async def get(self): """ Get customer's discount by ID """ query = select([ CustomerDiscount.c.name, CustomerDiscount.c.percent ]).where(CustomerDiscount.c.id == self.request.params["discount_id"]) self.context = await CustomerDiscount.query.fetch_one(query=query) response = JSONResponse(self.request, self.context) return response
async def get(self): """ get customer by ID """ query = select([ CustomerB.c.id, CustomerDiscount.c.name ]).where(CustomerB.c.id == int(self.request.params["customer_id"])) self.context = await CustomerB.query.fetch_one(query=query) response = JSONResponse(self.request, self.context) return response
async def delete(self): """ Delete discount :return: """ await CustomerDiscount.query.execute( query=CustomerDiscount.table.delete().where( CustomerDiscount.c.id == int( self.request.params["discount_id"]))) response = JSONResponse(self.request, self.context) return response
async def __call__(self, scope, receive, send): base_url = get_settings_variable("BASE_URL") if self.request.method == "POST": test_dir = f"{os.path.dirname(os.path.dirname(base_url))}/tests" command_ = f"cd .. && {test_dir}/venv/bin/python3 -m coverage html" os.system(command_) cove_dir = f"{test_dir}/htmlcov" docker_dir = f"{test_dir}/docker" static_dir = f"{docker_dir}/static" if not os.path.exists(static_dir): os.mkdir(static_dir) template_dir = f"{docker_dir}/streams/templates" if os.path.exists(cove_dir): for file_ in os.listdir(cove_dir): if file_.endswith(".html"): shutil.copyfile(f"{cove_dir}/{file_}", f"{template_dir}/{file_}") for match in REPLACEMENTS: replacement(f"{template_dir}/{file_}", match[0], match[1]) elif re.match(r".*\.js|.*css|.*\.png", file_): shutil.copyfile(f"{cove_dir}/{file_}", f"{static_dir}/{file_}") response = JSONResponse(self.request, {"success": "Coverage created"}) else: response = JSONResponse( self.request, {"error": "Failed to create coverage report"}) await response(scope, receive, send) else: response = StreamingResponse(self.request, send_file()) await response(scope, receive, send) started = os.environ.get("CRAX_TEST_SESSION_STARTED") if started is None: file_path = f"{base_url}/test.log" if os.path.isfile(file_path): run_ = asyncio.create_task(run_pub_sub()) os.environ["CRAX_RUN_TEST_CORO"] = str(id(run_)) os.environ["CRAX_TEST_SESSION_STARTED"] = "Started"
async def patch(self): """ Update customer's discount """ if isinstance(self.request.post, str): self.request.post = json.loads(self.request.post) await CustomerDiscount.query.execute( query=CustomerDiscount.table.update().where( CustomerDiscount.c.id == int( self.request.params["discount_id"])).values( json.loads(self.request.post["discount"]))) response = JSONResponse(self.request, self.context) return response
async def post(self): if isinstance(self.request.post, str): self.request.post = json.loads(self.request.post) if "order" in self.request.post: data = self.request.post["order"] else: data = self.request.post if isinstance(data, str): data = json.loads(data) await Orders.query.insert(values=data) self.context = {"success": "Created"} response = JSONResponse(self.request, self.context) return response
async def post(self): before_users = await User.query.all() users = self.request.post["users"] if isinstance(json.loads(users), list): await User.query.bulk_insert(values=json.loads(users)) else: await User.query.insert(values=json.loads(users)) after_users = await User.query.all() response = JSONResponse( self.request, { "len_before": len(before_users), "len_after": len(after_users) }, ) return response
async def post(self): username = self.request.post["username"] password = self.request.post["password"] await login(self.request, username, password) response = JSONResponse( self.request, { "username": username, "session": self.request.user.session, "pk": self.request.user.pk, "is_authenticated": self.request.user.is_authenticated, "is_active": self.request.user.is_active, "is_staff": self.request.user.is_staff, "is_superuser": self.request.user.is_superuser, }, ) return response
async def get(self): signer = itsdangerous.TimestampSigner("WrongKey") max_age = 600 cookie_name = "session_id" sign = signer.sign("mark:4") encoded = b64encode(sign) session = encoded.decode("utf-8") session_cookie = (f"{cookie_name}={session}; path=/;" f" Max-Age={max_age}; httponly; samesite=lax") signed = {"mark:4": session_cookie} self.request.session = json.dumps(signed) response = JSONResponse( self.request, {"user": self.request.session}, ) return response
async def post(self): """ Create new discount :par name: str required :par percent: int :content_type: application/x-www-form-urlencoded """ if isinstance(self.request.post, str): self.request.post = json.loads(self.request.post) if "discount" in self.request.post: data = self.request.post["discount"] else: data = self.request.post if isinstance(data, str): data = json.loads(data) await CustomerDiscount.query.insert(values=data) self.context = {"success": "Created"} response = JSONResponse(self.request, self.context) return response
async def get(self): secret_key = get_settings_variable("SECRET_KEY") max_age = get_settings_variable("SESSION_EXPIRES", default=1209600) cookie_name = get_settings_variable("SESSION_COOKIE_NAME", default="session_id") signer = itsdangerous.TimestampSigner(str(secret_key)) sign = signer.sign("Anonymous:0") encoded = b64encode(sign) session = encoded.decode("utf-8") session_cookie = (f"{cookie_name}={session}; path=/;" f" Max-Age={max_age}; httponly; samesite=lax") signed = {"Anonymous:0": session_cookie} self.request.session = json.dumps(signed) response = JSONResponse( self.request, {"user": self.request.session}, ) return response
async def __call__(self, scope, receive, send): response = JSONResponse(self.request, {"Error": "Testing Method Not Allowed"}) response.status_code = 405 await response(scope, receive, send)
async def create_context(self) -> JSONResponse: response = JSONResponse(self.request, self.context, status_code=self.status_code) return response
async def post(self): await self.request.files["pic"].save() response = JSONResponse(self.request, self.request.post) return response
async def __call__(self, scope, receive, send): response = JSONResponse(self.request, {"Error": "Testing Access Denied"}) response.status_code = 403 await response(scope, receive, send)
async def post(self): response = JSONResponse(self.request, self.request.post) return response
} for row_id, number in updates] async with connection_pool.acquire() as connection: statement = await connection.prepare(READ_ROW_SQL) for row_id, number in updates: await statement.fetchval(row_id) await connection.executemany(WRITE_ROW_SQL, updates) self.context = worlds class TestSingleFortunes(TemplateView): template = "fortune.html" async def get(self): async with connection_pool.acquire() as connection: fortunes = await connection.fetch('SELECT * FROM Fortune') fortunes.append([0, 'Additional fortune added at request time.']) fortunes.sort(key=itemgetter(1)) self.context["fortunes"] = fortunes APPLICATIONS = ["hello"] URL_PATTERNS = [ Route(Url('/json'), JSONResponse(None, {'message': 'Hello, world!'})), Route(Url('/plaintext'), BaseResponse(None, b'Hello, world!')), Route(Url('/db'), TestSingleQuery), Route(Url('/queries'), TestMultiQueries), Route(Url('/updates'), TestUpdates), Route(Url('/fortunes'), TestSingleFortunes) ] app = Crax('hello.app', debug=True, on_startup=setup_database)
async def get(self): self.context = await Orders.query.all() response = JSONResponse(self.request, self.context) return response
async def get(self): self.context = await Orders.query.fetch_one( query=Orders.table.select().where( Orders.c.id == int(self.request.params["order_id"]))) response = JSONResponse(self.request, self.context) return response
async def get(self): """Get list of customers""" self.context = await CustomerB.query.all() response = JSONResponse(self.request, self.context) return response
async def delete(self): """ Delete customer """ response = JSONResponse(self.request, self.context) return response
async def delete(self): query = Orders.table.delete().where( Orders.c.id == int(self.request.params["order_id"])) self.context = await CustomerB.query.execute(query=query) response = JSONResponse(self.request, self.context) return response