async def register( request: Request, db: Session = Depends(get_db), ) -> Union[_TemplateResponse, RedirectResponse]: """rendering register route post method.""" form = await request.form() form_dict = dict(form) try: # creating pydantic schema object out of form data new_user = schemas.UserCreate(**form_dict) except ValidationError as e: # if pydantic validations fails, rendering errors to register.html errors = get_error_messages_by_fields(e.errors()) return templates.TemplateResponse( "register.html", {"request": request, "errors": errors, "form_values": form_dict}, ) errors = await check_unique_fields(db, new_user) if errors: return templates.TemplateResponse( "register.html", {"request": request, "errors": errors, "form_values": form_dict}, ) await create_user(db=db, user=new_user) return RedirectResponse("/profile", status_code=HTTP_302_FOUND)
async def get_single_instrument( request: Request, instrument_name: str, current_user: UserInDB = Depends(get_current_active_user), page: int = Query(1), sort: str = Query("piece"), direction: int = Query(1), ): limit = int(os.getenv("SHEETS_PER_PAGE", 20)) prev_page, next_page = util.get_next_prev_page_urls(request.url, page) sheets = await crud.get_instrument_sheets(current_user.email, instrument_name, limit, page, sort, direction) if not await crud.instrument_sheets_has_next(current_user.email, instrument_name, limit, page): next_page = None return templates.TemplateResponse( "list.html", { "request": request, "page": page, "sort": sort, "direction": direction, "sheets": sheets, "next_page": next_page, "prev_page": prev_page, "sort_links": util.get_sort_links(request.url, sort, direction), "title": instrument_name, }, )
async def get_sheet_info( request: Request, sheet_id: str, current_user: UserInDB = Depends(get_current_active_user), current_version: str = Query(None), ): sheet_id = uuid.UUID(sheet_id) sheet = await crud.get_sheet_by_id(current_user.email, sheet_id) prev_version_records = await crud.get_previous_versions(sheet) logger.debug(prev_version_records) related_lists = { "piece": { "items": await crud.find_related(sheet, "piece", limit=3), "plural": False, }, "composers": { "items": await crud.find_related(sheet, "composers", limit=3), "plural": True, }, "tags": { "items": await crud.find_related(sheet, "tags", limit=3), "plural": True, }, } return templates.TemplateResponse( "sheets/single.html", { "request": request, "sheet": sheet, "related_lists": related_lists, "prev_versions": prev_version_records, "current_version": current_version, }, )
async def profile(request: Request, session=Depends(get_db), new_user=Depends(get_placeholder_user)): # Get relevant data from database upcoming_events = range(5) user = session.query(User).filter_by(id=1).first() if not user: session.add(new_user) session.commit() user = session.query(User).filter_by(id=1).first() signs = [ 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces' ] on_this_day_data = get_on_this_day_events(session) return templates.TemplateResponse( "profile.html", { "request": request, "user": user, "events": upcoming_events, "signs": signs, 'google_error': GOOGLE_ERROR, "on_this_day_data": on_this_day_data, })
async def eventview( request: Request, event_id: int, db: Session = Depends(get_db), ) -> Response: event, comments, end_format = get_event_data(db, event_id) start_format = START_FORMAT if event.all_day: start_format = "%A, %d/%m/%Y" end_format = "" waze_link = get_waze_link(event) event_considering_privacy = event_to_show(event, db) if not event_considering_privacy: raise_for_nonexisting_event(event.id) messages = request.query_params.get("messages", "").split("---") return templates.TemplateResponse( "eventview.html", { "request": request, "waze_link": waze_link, "event": event_considering_privacy, "comments": comments, "start_format": start_format, "end_format": end_format, "messages": messages, }, )
def get_template_to_share_event( event_id: int, user_name: str, db: Session, request: Request, ) -> _TemplateResponse: """Gives shareable template of the event. Args: event_id: Event to share user_name: The user who shares the event db: The database to get the event from request: The request we got from the user using FastAPI. Returns: Shareable HTML with data from the database about the event. """ event = by_id(db, event_id) msg_info = {"sender_name": user_name, "event": event} return templates.TemplateResponse( "share_event.html", { "request": request, "msg_info": msg_info }, )
async def post_create_sheet( request: Request, current_user: UserInDB = Depends(get_current_active_user), sheet_file: UploadFile = File(...), ): form = SheetForm(await request.form(), meta={"csrf_context": request.session}) if form.validate(): sheet = models.Sheet( **form.data, owner_email=current_user.email, sheet_id=uuid.uuid4(), file_ext=sheet_file.filename.split(".")[-1], ) await storage.save_sheet(sheet_file, sheet.sheet_id, sheet.owner_email, sheet.file_ext) created_sheet = await crud.create_sheet(sheet) return templates.TemplateResponse( "sheets/created.html", { "request": request, "sheet_id": created_sheet.sheet_id }, ) return "Something went wrong"
async def get_sheets( request: Request, current_user: UserInDB = Depends(get_current_active_user), page: int = Query(1), sort: str = Query("piece"), direction: int = Query(1), ): limit = int(os.getenv("SHEETS_PER_PAGE", 20)) sheet_cursor = await crud.get_user_sheets(current_user.email, page, sort, direction, limit) prev_page, next_page = get_next_prev_page_urls(request.url, page) if not await crud.user_sheets_has_next(current_user.email, page, limit): next_page = None user_sheets = [ models.SheetOut.parse_obj(sheet) async for sheet in sheet_cursor ] sort_links = get_sort_links(request.url, sort, direction) return templates.TemplateResponse( "list.html", { "request": request, "page": page, "sort": sort, "direction": direction, "sheets": user_sheets, "prev_page": prev_page, "next_page": next_page, "title": "All Sheets", "sort_links": sort_links, }, )
async def home(request: Request, db: Session = Depends(get_db)): quote = daily_quotes.quote_per_day(db) return templates.TemplateResponse("home.html", { "request": request, "message": "Hello, World!", "quote": quote })
async def show_results(request: Request, keywords: str = Form(None), db: Session = Depends(get_db)): # Made up user details until there's a user login system current_username = "******" current_user = 1 message = "" if not keywords: message = "Invalid request." results = None else: results = get_results_by_keywords(db, keywords, owner_id=current_user) if not results: message = f"No matching results for '{keywords}'." return templates.TemplateResponse( "search.html", { "request": request, "username": current_username, "message": message, "results": results, "keywords": keywords })
def agenda( request: Request, db: Session = Depends(get_db), start_date: Optional[date] = None, end_date: Optional[date] = None, days: Optional[int] = None, ) -> _TemplateResponse: """Route for the agenda page, using dates range or exact amount of days.""" user_id = 1 # there is no user session yet, so I use user id- 1. start_date, end_date = calc_dates_range_for_agenda(start_date, end_date, days) events_objects = agenda_events.get_events_per_dates( db, user_id, start_date, end_date) events = defaultdict(list) for event_obj in events_objects: event_duration = agenda_events.get_time_delta_string( event_obj.start, event_obj.end) events[event_obj.start.date()].append((event_obj, event_duration)) return templates.TemplateResponse( "agenda.html", { "request": request, "events": events, "start_date": start_date, "end_date": end_date, })
async def weight(request: Request, session: Session = Depends(get_db)): user_id = 1 user = session.query(User).filter_by(id=user_id).first() data = await request.form() target = data['target'] current_weight = data['current_weight'] if target: user.target_weight = target session.commit() else: target = user.target_weight if not target: target = current_weight way_to_go = float(current_weight) - float(target) way_to_go = round(way_to_go, 2) if way_to_go > 0: way_message = f"Weight to lose: {way_to_go} Kg" elif way_to_go < 0: way_to_go = abs(way_to_go) way_message = f"Weight to add: {way_to_go} Kg" else: way_message = f"Great! You have reached your goal: {target} Kg" return templates.TemplateResponse( "weight.html", { "request": request, "target": target, "current_weight": current_weight, "way_message": way_message })
def audio_settings( request: Request, session: Session = Depends(get_db), user: User = Depends(current_user), ) -> templates.TemplateResponse: """A route to the audio settings. Args: request (Request): the http request session (Session): the database. Returns: templates.TemplateResponse: renders the audio.html page with the relevant information. """ mp3_files = Path(SOUNDS_PATH).glob("**/*.mp3") wav_files = Path(SOUNDS_PATH).glob("**/*.wav") songs = [Sound(SoundKind.SONG, path.stem, path) for path in mp3_files] sfxs = [Sound(SoundKind.SFX, path.stem, path) for path in wav_files] sounds = songs + sfxs init_audio_tracks(session, sounds) return templates.TemplateResponse( "audio_settings.html", { "request": request, "songs": songs, "sound_effects": sfxs, }, )
async def get_tags(request: Request, current_user: UserInDB = Depends(get_current_active_user)): tags = await crud.get_all_tags(current_user.email) return templates.TemplateResponse("tags/all.html", { "request": request, "tags": sorted(tags), "title": "All Tags" })
async def login_user_form(request: Request, message: Optional[str] = "") -> templates: """rendering login route get method""" return templates.TemplateResponse("login.html", { "request": request, "message": message, 'current_user': "******" })
def search(request: Request): # Made up user details until there's a user login system current_username = "******" return templates.TemplateResponse("search.html", { "request": request, "username": current_username })
async def get_create_sheet( request: Request, _current_user: UserInDB = Depends(get_current_active_user)): form = SheetForm(meta={"csrf_context": request.session}) return templates.TemplateResponse("sheets/create.html", { "request": request, "form": form })
async def home(request: Request, db: Session = Depends(get_db)): quote = daily_quotes.get_quote_of_day(db) return templates.TemplateResponse( "index.html", { "request": request, "quote": quote, }, )
async def calendar(request: Request) -> Response: user_local_time = cg.Day.get_user_local_time() day = cg.create_day(user_local_time) return templates.TemplateResponse( "calendar_monthly_view.html", { "request": request, "day": day, "week_days": cg.Week.DAYS_OF_THE_WEEK, "weeks_block": cg.get_month_block(day) })
def view_invitations(request: Request, db: Session = Depends(get_db)): return templates.TemplateResponse( "invitations.html", { "request": request, # TODO: create current user # recipient_id should be the current user # but because we don't have one yet, # "get_all_invitations" returns all invitations "invitations": get_all_invitations(session=db), })
def currency(request: Request, date: str): """Custom date currency router""" # TODO: get user default/preferred currency base = "USD" return templates.TemplateResponse("currency.html", { "request": request, "base": base, "date": date })
async def confirm_magic_form(request: Request): form = EnterEmailForm(await request.form(), meta={"csrf_context": request.session}) if not form.validate(): error_message = urllib.parse.quote_plus("Login Link failed. Please try again.") return RedirectResponse(url=f"/auth/login?error={error_message}") user = await security.authenticate_user_magic(form.email.data, form.secret.data) if not user or user.disabled: return "Could not log in" response = templates.TemplateResponse( "auth/login-successful.html", {"request": request} ) return add_login_cookie(response, user)
async def get_instruments( request: Request, current_user: UserInDB = Depends(get_current_active_user)): instruments = await crud.get_all_instruments(current_user.email) return templates.TemplateResponse( "instruments/all.html", { "request": request, "instruments": sorted(instruments), "title": "All instruments", }, )
async def set_category(request: Request, name: str = Form(None), color: str = Form(None), db_sess: Session = Depends(get_db)): message = "" user_id = 1 # until issue#29 will get current user_id from session color = color.replace('#', '') if not validate_color_format(color): raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Color {color} if not from " f"expected format.") try: Category.create(db_sess, name=name, color=color, user_id=user_id) except IntegrityError: db_sess.rollback() message = "Category already exists" return templates.TemplateResponse( "categories.html", dictionary_req(request, message, name, color)) message = f"Congratulation! You have created a new category: {name}" return templates.TemplateResponse( "categories.html", dictionary_req(request, message, name, color))
async def eventview(request: Request, event_id: int, db: Session = Depends(get_db)): event = by_id(db, event_id) start_format = '%A, %d/%m/%Y %H:%M' end_format = ('%H:%M' if event.start.date() == event.end.date() else start_format) return templates.TemplateResponse( "event/eventview.html", { "request": request, "event": event, "start_format": start_format, "end_format": end_format })
async def eventedit( request: Request, db_session: Session = Depends(get_db), ) -> Response: user_id = 1 # until issue#29 will get current user_id from session categories_list = get_user_categories(db_session, user_id) return templates.TemplateResponse( "eventedit.html", { "request": request, "categories_list": categories_list, "privacy": PrivacyKinds, }, )
def celebrity(request: Request) -> Response: """Returns the Celebrity page route. Args: request: The HTTP request. Returns: The Celebrity HTML page. """ today = get_today_month_and_day() return templates.TemplateResponse("celebrity.html", { "request": request, "date": today, })
async def login( request: Request, next_location: str = Query(None, alias="next"), error: str = Query(None), ): form = RequestLoginForm(meta={"csrf_context": request.session}) return templates.TemplateResponse( "auth/login.html", { "request": request, "next_location": next_location, "form": form, "error": error, }, )
async def submit_code(request: Request, next_location: str = Query(None, alias="next")): code_form = SubmitCodeForm( await request.form(), meta={"csrf_context": request.session} ) if not code_form.email.data: error_message = urllib.parse.quote_plus("No email found. Please log in again.") return RedirectResponse(url=f"/auth/login?error={error_message}") if not code_form.validate(): return templates.TemplateResponse( "auth/submit-code.html", { "request": request, "email": code_form.email.data, "next_location": next_location, "form": code_form, }, ) user = await security.authenticate_user(code_form.email.data, code_form.code.data) if not user or user.disabled: return "Could not log in" response = templates.TemplateResponse( "auth/login-successful.html", {"request": request} ) return add_login_cookie(response, user)
def friendview( request: Request, db: Session = Depends(get_db), my_friend: Union[str, None] = None, ) -> _TemplateResponse: # TODO: Waiting for user registration user_id = 1 events_list = friend_view.get_events_per_friend(db, user_id, my_friend) return templates.TemplateResponse("friendview.html", { "request": request, "events": events_list, "my_friend": my_friend, })