def user_form(request): if request.method == 'POST': # объект SQLAlchemy для связи с существующей db engine = make_app().database_engine # получаем обрабатываем загруженый фаил file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(basedir1, filename)) replace_id_loc1(basedir1, filename, engine) return redirect(url_for("table")) return redirect(url_for("table"))
def staff_post(): if not current_user.is_authenticated: return redirect(url_for('auth.login')) form = PostForm() if form.validate_on_submit(): user = current_user is_dev = form.is_dev.data text = form.text.data project = form.project.data post = Post(is_dev=is_dev, text=text, project=project, user_id=user.id) db.session.add(post) db.session.commit() return redirect(url_for('main.index')) return render_template('staff/post.html', title="Staff Post", form=form)
def list_case_studies(): page = get_valid_page_or_1() supplier_code = get_int_or_400(request.args, 'supplier_code') case_studies = CaseStudy.query if supplier_code is not None: case_studies = case_studies.filter(CaseStudy.supplier_code == supplier_code) if supplier_code: return jsonify( caseStudies=[case_study.serialize() for case_study in case_studies.all()], links={'self': url_for('.list_case_studies', supplier_code=supplier_code)} ) results_per_page = get_positive_int_or_400( request.args, 'per_page', current_app.config['DM_API_PAGE_SIZE'] ) case_studies = case_studies.paginate( page=page, per_page=results_per_page ) return jsonify( caseStudies=[case_study.serialize() for case_study in case_studies.items], links=pagination_links( case_studies, '.list_case_studies', request.args ) )
def list_case_studies(): page = get_valid_page_or_1() supplier_code = get_int_or_400(request.args, 'supplier_code') case_studies = CaseStudy.query if supplier_code is not None: case_studies = case_studies.filter( CaseStudy.supplier_code == supplier_code) if supplier_code: return jsonify(caseStudies=[ case_study.serialize() for case_study in case_studies.all() ], links={ 'self': url_for('.list_case_studies', supplier_code=supplier_code) }) results_per_page = get_positive_int_or_400( request.args, 'per_page', current_app.config['DM_API_PAGE_SIZE']) case_studies = case_studies.paginate(page=page, per_page=results_per_page) return jsonify(caseStudies=[ case_study.serialize() for case_study in case_studies.items ], links=pagination_links(case_studies, '.list_case_studies', request.args))
def popdb(port): """Populates the database with sample data""" with app.app_context(): initdb() raw = utils.get_init_data() name, data = utils.process(raw, Todo) url = utils.url_for(name, port=port) for r in utils.post(url, data=data): print('ok!' if r.ok else r.json()) print('Database populated')
async def start_logout( req: Request, frontend_path: str = Query(..., alias="frontendPath"), return_path: str = Query(..., alias="returnPath"), id_token: str = Cookie(...), ): # Validate the frontend path and set the error page accordingly try: frontend_settings = get_frontend_settings_by_path(frontend_path) except KeyError: raise HTTPException(status_code=404, detail="Not found") error_page = f"{frontend_path}{frontend_settings.auth_error_page}" try: try: await validate_return_path(return_path) except ReturnPathValidationFailed: raise AuthException(400, "Invalid returnPath") state = generate_logout_state(return_path) params = { "post_logout_redirect_uri": url_for(req, "logout"), "state": state, } if conf.OPENID_CONNECT_INCLUDE_ID_TOKEN_HINT_IN_LOGOUT: params["id_token_hint"] = id_token params = urllib.parse.urlencode(params) uri = f"{openid_conf.end_session_endpoint}?{params}" return RedirectResponse(uri) except AuthException as ex: # This page is rendered in the browser, so any errors need to be handled by # redirecting to an actual error page rendered by the frontend logger.exception("Exception handled through redirect") message = urllib.parse.quote_plus(ex.detail) status_code = ex.status_code return RedirectResponse( f"{error_page}?message={message}&status_code={status_code}") except Exception: logger.exception("Unhandled exception handled through redirect") message = urllib.parse.quote_plus("Unknown error, please try again.") return RedirectResponse( f"{error_page}?message={message}&status_code=500")
async def start_login(req: Request, data: StartLoginRequest, id_token: str = Cookie(None)): """ API endpoint for starting the login flow; will give back a redirectUri to which the user should be redirected to authenticate. """ if is_authenticated(id_token=id_token): raise HTTPException(403, "Already authenticated") return_path = data.returnPath await validate_return_path(return_path) try: get_frontend_settings_by_path(data.frontendPath) except KeyError: raise HTTPException( status_code=422, detail=f"Invalid frontendPath '{data.frontendPath}'") nonce = generate_nonce() state = generate_state(return_path, nonce) params = urllib.parse.urlencode({ "response_type": "code", "client_id": conf.OPENID_CONNECT_CLIENT_ID, "acr_values": conf.OPENID_CONNECT_ACR_VALUES, "scope": conf.OPENID_CONNECT_SCOPES, "redirect_uri": url_for(req, "code_exchange", frontend_path=data.frontendPath), "nonce": nonce, "state": state, }) uri = f"{openid_conf.authorization_endpoint}?{params}" return StartLoginResponse(redirectUri=uri)
def list_work_orders(): page = get_valid_page_or_1() brief_id = get_int_or_400(request.args, 'brief_id') supplier_code = get_int_or_400(request.args, 'supplier_code') work_orders = WorkOrder.query if supplier_code is not None: work_orders = work_orders.filter(WorkOrder.supplier_code == supplier_code) if brief_id is not None: work_orders = work_orders.filter(WorkOrder.brief_id == brief_id) if brief_id or supplier_code: return jsonify( workOrders=[work_order.serialize() for work_order in work_orders.all()], links={'self': url_for('.list_work_orders', supplier_code=supplier_code, brief_id=brief_id)} ) results_per_page = get_positive_int_or_400( request.args, 'per_page', current_app.config['DM_API_PAGE_SIZE'] ) work_orders = work_orders.paginate( page=page, per_page=results_per_page ) return jsonify( workOrders=[work_order.serialize() for work_order in work_orders.items], links=pagination_links( work_orders, '.list_work_orders', request.args ) )
def test_app(client): assert client.get(url_for('main.index')).status_code == 200
def client_url_for(table_name=None, **kwargs): with app.test_request_context(): kwargs['instid'] = kwargs.pop('id', None) return url_for(table_name, **kwargs)
def table(request): url = url_for("table") # подключаем необходимые таблицы для списков в jinja2 regions = Region.query.all() queries = Users.query.all() # инициируем и преобразуем для чтетия выгрузку таблицы Users db = sqlite3.connect('data.db', uri=True) c = db.cursor() script = """ SELECT * FROM Users """ c.execute(script) columns = [desc[0] for desc in c.description] data = c.fetchall() df = pd.DataFrame(list(data), columns=columns) writer = pd.ExcelWriter(basedir2 + r'/database.xlsx') df.to_excel(writer, sheet_name='0', index=False) writer.save() replace_id_loc2(basedir2, r'/database.xlsx') # получаем данные из формы далее записывает данные в таблицу users if request.method == "POST": # запись в db полученой информации из формы try: firstName = request.form['firstName'] middleName = request.form['middleName'] lastName = request.form['lastName'] phone = request.form['phone'] email = request.form['email'] city = request.form['city'] rel_city = City.query.filter(City.name == city).first() try: done_db = Users( firstName=firstName, middleName=middleName, lastName=lastName, phone=phone, email=email, region_id=rel_city.region_id, city_id=rel_city.id, ) session.add(done_db) session.commit() return redirect(url_for("table")) except Exception as e: # обработаем исключение если город и регин не заполнен выведим пустую ячейку try: error = e.args[0].split() error_str = error[5].replace("'", "") if error_str == 'region_id' or error_str == 'city_id': done_db = Users( firstName=firstName, middleName=middleName, lastName=lastName, phone=phone, email=email, region_id=None, city_id=None, ) session.add(done_db) session.commit() finally: return redirect(url_for("table")) except Exception as e: try: return e finally: # сереализуем post запрос в json для ajax if request.form['region']: region = request.form['region'] records = [ z.to_json() for z in Region.query.filter_by(name_region=region) ] cont = json.dumps(records[0], sort_keys=True) return Response(cont, content_type="application/json") return render_template("table.html", url=url, queries=queries, regions=regions)
def home(request): url = url_for("home") return render_template("home.html", url=url)
def favicon(): return send_from_directory(url_for('static', filename='favicon.ico'), mimetype='image/vnd.microsoft.icon')
async def code_exchange( request: Request, frontend_path: str, code: str, state: str, id_token: str = Cookie(None), ): """ The endpoint at which the user will land when coming back from the OpenID Connect provider. Handles the token exchange and sets the id_token and access_token cookies. Note that this endpoint is served in a web browser, not through an API call from the frontend. Hence any errors are handled by redirecting the user to a frontend side error page with a message and status code. """ # Validate the frontend path and set the error page accordingly try: frontend_settings = get_frontend_settings_by_path(frontend_path) except KeyError: raise HTTPException(status_code=404, detail="Not found") error_page = f"{frontend_path}{frontend_settings.auth_error_page}" try: if is_authenticated(id_token=id_token): raise AuthException(403, "Already authenticated") login_state = get_valid_state(state) if not login_state: raise AuthException(400, "Invalid state") params = { "grant_type": "authorization_code", "redirect_uri": url_for(request, "code_exchange", frontend_path=frontend_path), "code": code, } res = await client.post( url=openid_conf.token_endpoint, data=params, auth=( conf.OPENID_CONNECT_CLIENT_ID, conf.OPENID_CONNECT_CLIENT_SECRET.get_secret_value(), ), ) if res.is_error: logger.error("Code exchange failed", code=res.status_code, err=res.text) raise AuthException(502, "Code exchange failed") result = OAuthTokenResponse(**res.json()) try: id_token = validate_token(result.id_token) except jwt.exceptions.InvalidTokenError: logger.exception("Failed to validate token") raise AuthException(500, "Token validation failed") if login_state.nonce != id_token.nonce: logger.error("Got invalid nonce") raise AuthException(500, "Token validation failed") response = RedirectResponse(login_state.returnPath) set_cookie(response, "id_token", result.id_token) set_cookie(response, "access_token", result.access_token) return response except AuthException as ex: # This page is rendered in the browser, so any errors need to be handled by # redirecting to an actual error page rendered by the frontend logger.exception("Exception handled through redirect") message = urllib.parse.quote_plus(ex.detail) status_code = ex.status_code return RedirectResponse( f"{error_page}?message={message}&status_code={status_code}") except Exception: logger.exception("Unhandled exception handled through redirect") message = urllib.parse.quote_plus("Unknown error, please try again.") return RedirectResponse( f"{error_page}?message={message}&status_code=500")
def login(): local.response = redirect(url_for("index")) local.response.set_cookie("user_id", 1)
def logout(): local.response = redirect(url_for("index")) local.response.delete_cookie("user_id")