def setup_pauli(flask_app, url_prefix="/pauli"): # setup mongodb for alias, attrs in conf.MONGO.items(): mongoengine.register_connection(alias, **attrs) # setup session session_db = mongoengine.connection.get_db(alias="pauli") config_dict = { "SESSION_COOKIE_NAME": conf.SESSION_COOKIE_NAME, "SESSION_TYPE": "mongodb", "SESSION_MONGODB": session_db.client, "SESSION_MONGODB_DB": session_db.name, "SESSION_MONGODB_COLLECT": "sessions", "PERMANENT_SESSION_LIFETIME": conf.PAULI_SESSION_LIFETIME } flask_app.config.update(config_dict) flask_session.Session(flask_app) # import sub level path routings from .user.views import api from .auth.views import api from .auth.views import web from .perm.views import api # bind pauli blueprint flask_app.register_blueprint(pauli_root, url_prefix=url_prefix)
def create_app(config_pattern): # 配置日志 setup_log(config_pattern) app = flask.Flask(__name__) app.config.from_object(config.config[config_pattern]) # 通过app初始化 db.init_app(app) # 帮我们做了:从cookie中取出随机值,从表单中取出随机,然后进行校验,并且响应校验结果 # 我们需要做:1. 在返回响应的时候,往cookie中添加一个csrf_token,2. 并且在表单中添加一个隐藏的csrf_token # 而我们现在登录或者注册不是使用的表单,而是使用 ajax 请求,所以我们需要在 ajax 请求的时候带上 csrf_token 这个随机值就可以了 # 请求服务器使用post,put,delete等需要修改服务器数据的操作都需要csrf保护 # bug:不关闭保护的话,请求400 flask_wtf.csrf.CSRFProtect(app) global redis_db redis_db = redis.StrictRedis(host=config.config['development'].REDIS_HOST, port=config.config['development'].REDIS_PORT, decode_responses=True) flask_session.Session(app) # bug:ImportError: cannot import name 'db' # 循环导入时,db还没有创建,所以导入失败 from info.utils.common import do_index_class app.add_template_filter(do_index_class, 'index_class') # bug:依然会造成循环导入的问题 from info.utils.common import user_login_data @app.errorhandler(404) @user_login_data def page_not_found(e): user = flask.g.user data = {'user': user.to_dict() if user else None} return flask.render_template('news/404.html', data=data) # CSRF对服务器进行数据操作的请求方法都需要设置保护,统一在hook时设置 # bug:400 需要将设置在 flask_session.Session(app)之后,否则发送请求时使用到redis数据库会报错 @app.after_request def after_request(response): csrf_token = generate_csrf() response.set_cookie('csrf_token', csrf_token) return response # 注册相关蓝图 # 顶部导入蓝图的话,会出现循环导入的bug,解决:什么时候注册蓝图什么时候导入蓝图 from info.modules.index import index_blu app.register_blueprint(index_blu) from info.modules.passport import passport_blu app.register_blueprint(passport_blu) from info.modules.news import news_blu app.register_blueprint(news_blu) from info.modules.user import user_blu app.register_blueprint(user_blu) from info.modules.admin import admin_blu app.register_blueprint(admin_blu) # 其实也可以返回元组 app, info_db return app
def Create_app(config_name): InformationApp = flask.Flask(__name__) InformationApp.config.from_object(config[config_name]) db.init_app(InformationApp) from .utls.common import to_index_class InformationApp.add_template_filter(to_index_class, "index_class") global redis_store redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT) flask_wtf.CSRFProtect(InformationApp) @InformationApp.after_request def after_request(response): csrf_token = generate_csrf() response.set_cookie("csrf_token", csrf_token) return response flask_session.Session(app=InformationApp) from Info.modules.index import index_blu InformationApp.register_blueprint(index_blu) from Info.modules.passport import passport_blu InformationApp.register_blueprint(passport_blu) from Info.modules.news import news_blu InformationApp.register_blueprint(news_blu) from Info.modules.Profile import Profile_blu InformationApp.register_blueprint(Profile_blu) from .utls.common import user_login_data @InformationApp.errorhandler(404) @user_login_data def page_not_found(_): user = g.user data = {"user_info": user.to_dict() if user else None} return flask.render_template('news/404.html', user_data=data) from Info.modules.admin import admin_blu InformationApp.register_blueprint(admin_blu) return InformationApp
def create_app(overrides: typing.Dict[str, typing.Any] = None): '''Create and return a Flask app instance for MORA. :param dict overrides: Settings to override prior to extension instantiation. ''' app = flask.Flask(__name__, root_path=distdir, template_folder=templatedir) app.cli = cli.group app.config.from_object(settings) if overrides is not None: app.config.update(overrides) flask_session.Session(app) app.register_blueprint(base.blueprint) app.register_blueprint(sso.blueprint) for blueprint in service.blueprints: app.register_blueprint(blueprint) @app.errorhandler(Exception) def handle_invalid_usage(error): """ Handles errors in case an exception is raised. :param error: The error raised. :return: JSON describing the problem and the apropriate status code. """ if not isinstance(error, werkzeug.routing.RoutingException): util.log_exception('unhandled exception') if not isinstance(error, werkzeug.exceptions.HTTPException): error = exceptions.HTTPException(description=str(error), ) return error.get_response(flask.request.environ) @app.route('/') @app.route('/<path:path>') def root(path=''): if path.split('/', 1)[0] == 'service': raise exceptions.HTTPException( exceptions.ErrorCodes.E_NO_SUCH_ENDPOINT) return flask.send_file('index.html') return app
def create_app(): """DT visualization application factory.""" app = flask.Flask(__name__, instance_relative_config=False) app.config.from_object(config.Config) flask_cors.CORS(app, supports_credentials=True) api = flask_restful.Api(app) flask_session.Session(app) api.add_resource(DecisionTree, "/dt-visualization") api.add_resource(PredictSingleInstance, "/predict-single-instance") api.add_resource(PredictDataset, "/predict-dataset") api.add_resource(MostCommonAttrSeq, "/most-common-attr-seq") api.add_resource(ForestHierarchicalClustering, "/forest-hierarchical-clustering") return app
def init_app(app): if not app.config.get("SESSION_REDIS"): if app.config.get("DM_ENVIRONMENT") == "development": app.config["SESSION_REDIS"] = redis.Redis() else: vcap_services = cf.get_vcap_services() redis_service_name = app.config["DM_REDIS_SERVICE_NAME"] redis_service = cf.get_service_by_name_from_vcap_services( vcap_services, redis_service_name) app.config["SESSION_REDIS"] = redis.from_url( redis_service["credentials"]["uri"]) app.config["SESSION_USE_SIGNER"] = True app.config["SESSION_TYPE"] = 'redis' flask_session.Session(app)
client_id = HYDRA_CLIENT_ID client_secret = HYDRA_CLIENT_SECRET scopes = ['hydra.consent'] auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client, scope=scopes) token = oauth.fetch_token(token_url=HYDRA_HOST + '/oauth2/token', auth=auth, verify=False) return oauth, token """ REDIS_HOST = os.environ['REDIS_HOST'] r = redis.StrictRedis(host=REDIS_HOST, port=6379, db=0) app.config['SESSION_TYPE'] = 'redis' app.config['SESSION_REDIS'] = r flask_session.Session(app) def obtener_consent_id(): consent = request.args.get('consent', None, str) if not consent: consent = flask.session.get('consent', None) return consent def obtener_consent(): id = obtener_consent_id() if not id: return None consent = flask.session.get('consent_{}'.format(id), None)
def create_app(config=None): """ Create the flask application. """ app = flask.Flask(__name__) app.config = pagure_config if config: app.config.update(config) if app.config.get("SESSION_TYPE", None) is not None: import flask_session flask_session.Session(app) pagure.utils.set_up_logging(app=app) @app.errorhandler(500) def fatal_error(error): # pragma: no cover """500 Fatal Error page""" logger.exception("Error while processing request") return flask.render_template("fatal_error.html", error=error), 500 app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True if perfrepo: # Do this as early as possible. # We want the perfrepo before_request to be the very first thing # to be run, so that we can properly setup the stats before the # request. app.before_request(perfrepo.reset_stats) auth = pagure_config.get("PAGURE_AUTH", None) if auth in ["fas", "openid"]: # Only import and set flask_fas_openid if it is needed from pagure.ui.fas_login import FAS FAS.init_app(app) elif auth == "oidc": # Only import and set flask_fas_openid if it is needed from pagure.ui.oidc_login import oidc, fas_user_from_oidc oidc.init_app(app) app.before_request(fas_user_from_oidc) if auth == "local": # Only import the login controller if the app is set up for local login import pagure.ui.login as login app.before_request(login._check_session_cookie) app.after_request(login._send_session_cookie) # Support proxy app.wsgi_app = pagure.proxy.ReverseProxied(app.wsgi_app) # Back port 'equalto' to older version of jinja2 app.jinja_env.tests.setdefault("equalto", lambda value, other: value == other) # Import the application from pagure.api import API # noqa: E402 app.register_blueprint(API) from pagure.ui import UI_NS # noqa: E402 app.register_blueprint(UI_NS) from pagure.internal import PV # noqa: E402 app.register_blueprint(PV) themename = pagure_config.get("THEME", "default") here = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)))) themeblueprint = flask.Blueprint( "theme", __name__, static_url_path="/theme/static", static_folder=os.path.join(here, "themes", themename, "static"), ) # Jinja can be told to look for templates in different folders # That's what we do here template_folders = os.path.join( app.root_path, app.template_folder, os.path.join(here, "themes", themename, "templates"), ) import jinja2 # Jinja looks for the template in the order of the folders specified templ_loaders = [ jinja2.FileSystemLoader(template_folders), app.jinja_loader, ] app.jinja_loader = jinja2.ChoiceLoader(templ_loaders) app.register_blueprint(themeblueprint) app.before_request(set_request) app.teardown_request(end_request) if perfrepo: # Do this at the very end, so that this after_request comes last. app.after_request(perfrepo.print_stats) app.add_url_rule("/login/", view_func=auth_login, methods=["GET", "POST"]) app.add_url_rule("/logout/", view_func=auth_logout) return app
def create_app(config=None): """ Create the flask application. """ app = MultiStaticFlask(__name__) app.config = pagure_config if config: app.config.update(config) if app.config.get('SESSION_TYPE', None) is not None: import flask_session flask_session.Session(app) logging.basicConfig() logging.config.dictConfig(app.config.get('LOGGING') or {'version': 1}) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True if perfrepo: # Do this as early as possible. # We want the perfrepo before_request to be the very first thing # to be run, so that we can properly setup the stats before the # request. app.before_request(perfrepo.reset_stats) if pagure_config.get('THEME_TEMPLATE_FOLDER', False): # Jinja can be told to look for templates in different folders # That's what we do here template_folder = pagure_config['THEME_TEMPLATE_FOLDER'] if template_folder[0] != '/': template_folder = os.path.join(app.root_path, app.template_folder, template_folder) import jinja2 # Jinja looks for the template in the order of the folders specified templ_loaders = [ jinja2.FileSystemLoader(template_folder), app.jinja_loader, ] app.jinja_loader = jinja2.ChoiceLoader(templ_loaders) if pagure_config.get('THEME_STATIC_FOLDER', False): static_folder = pagure_config['THEME_STATIC_FOLDER'] if static_folder[0] != '/': static_folder = os.path.join(app.root_path, 'static', static_folder) # Unlike templates, to serve static files from multiples folders we # need flask-multistatic app.static_folder = [ static_folder, os.path.join(app.root_path, 'static'), ] auth = pagure_config.get('PAGURE_AUTH', None) if auth in ['fas', 'openid']: # Only import and set flask_fas_openid if it is needed from pagure.ui.fas_login import FAS FAS.init_app(app) elif auth == 'oidc': # Only import and set flask_fas_openid if it is needed from pagure.ui.oidc_login import oidc, fas_user_from_oidc oidc.init_app(app) app.before_request(fas_user_from_oidc) # Report error by email if not app.debug and not pagure_config.get('DEBUG', False): app.logger.addHandler( pagure.mail_logging.get_mail_handler( smtp_server=pagure_config.get('SMTP_SERVER', '127.0.0.1'), mail_admin=pagure_config.get('MAIL_ADMIN', pagure_config['EMAIL_ERROR']), from_email=pagure_config.get('FROM_EMAIL', '*****@*****.**'))) # Support proxy app.wsgi_app = pagure.proxy.ReverseProxied(app.wsgi_app) # Back port 'equalto' to older version of jinja2 app.jinja_env.tests.setdefault('equalto', lambda value, other: value == other) # Import the application from pagure.api import API # noqa: E402 app.register_blueprint(API) from pagure.ui import UI_NS # noqa: E402 app.register_blueprint(UI_NS) from pagure.internal import PV # noqa: E402 app.register_blueprint(PV) app.before_request(set_request) app.teardown_request(end_request) # Only import the login controller if the app is set up for local login if pagure_config.get('PAGURE_AUTH', None) == 'local': import pagure.ui.login as login app.before_request(login._check_session_cookie) app.after_request(login._send_session_cookie) if perfrepo: # Do this at the very end, so that this after_request comes last. app.after_request(perfrepo.print_stats) app.add_url_rule('/login/', view_func=auth_login, methods=['GET', 'POST']) app.add_url_rule('/logout/', view_func=auth_logout) return app
def create_app(): app = Flask(__name__) app.config.from_pyfile('settings.py') app.jinja_env.globals['year'] = date.today().year flask_session.Session(app) caches_folder = './.spotify_caches/' if not os.path.exists(caches_folder): os.makedirs(caches_folder) def session_cache_path(): return caches_folder + session.get('uuid') def get_auth_manager(): auth_manager = spotipy.oauth2.SpotifyOAuth( scope='user-library-read', cache_path=session_cache_path(), show_dialog=True, client_id=app.config.get('SPOTIPY_CLIENT_ID'), client_secret=app.config.get('SPOTIPY_CLIENT_SECRET')) return auth_manager @app.route('/') def login(): if not session.get('uuid'): session['uuid'] = str(uuid.uuid4()) auth_manager = get_auth_manager() if not auth_manager.get_cached_token(): # We're not logged in; render connect page! return render_template('login.html') else: # We ARE logged in; render display page! return display(spotipy.Spotify(auth_manager=auth_manager)) @app.route('/connect', methods=['POST']) def connect(): auth_manager = get_auth_manager() return redirect(auth_manager.get_authorize_url()) @app.route('/authorize') def authorize(): if request.args.get("code"): # Being redirected from Spotify auth page! auth_manager = get_auth_manager() auth_manager.get_access_token(request.args.get("code")) return display(spotipy.Spotify(auth_manager=auth_manager)) else: # No code provided, returning to home return redirect('/') class LikedTrack(): spotify_id = None name = None preview_url = None genres = None tempo = None time_signature = None energy = None loudness = None duration = None @app.route('/display') @app.route('/display/<offset>') def display(authorized_sp=None, offset=0): # Gets 50 tracks, starting with the given offset. # In the index page, make a pagination item that, like the action for connect, # renders this display with the given offset by every 50. if authorized_sp is None: authorized_sp = spotipy.Spotify(auth_manager=get_auth_manager()) saved_tracks_info = authorized_sp.current_user_saved_tracks(limit=50) print(f"Given offset of {offset}!") print( f"{saved_tracks_info['total']} total liked tracks for this user!!") print( f"Looking at tracks {saved_tracks_info['offset']} through {len(saved_tracks_info['items'])}" ) liked_tracks = [] for track in saved_tracks_info['items']: l = LikedTrack() l.spotify_id = track['track']['id'] l.name = track['track']['name'] l.preview_url = track['track']['preview_url'] l.duration = track['track']['duration_ms'] / 60 #print(f"\tTrack Name: {l.name}\tDuration: {l.duration}\tPreview URL: {l.preview_url}") liked_tracks.append(l) return render_template("index.html", items=liked_tracks) @app.route('/logoff') @app.route('/signout') def logoff(): os.remove(session_cache_path()) session.clear() try: os.remove(session_cache_path()) except OSError as e: print(f"Error: {e.filename}: {e.strerror}") return redirect('/') return app
def create_app(config=None): """ Create the flask application. """ app = flask.Flask(__name__) app.config = pagure_config if config: app.config.update(config) if app.config.get("SESSION_TYPE", None) is not None: import flask_session flask_session.Session(app) pagure.utils.set_up_logging(app=app) @app.errorhandler(500) def fatal_error(error): # pragma: no cover """500 Fatal Error page""" logger.exception("Error while processing request") return flask.render_template("fatal_error.html", error=error), 500 app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True if perfrepo: # Do this as early as possible. # We want the perfrepo before_request to be the very first thing # to be run, so that we can properly setup the stats before the # request. app.before_request(perfrepo.reset_stats) auth = pagure_config.get("PAGURE_AUTH", None) if auth in ["fas", "openid"]: # Only import and set flask_fas_openid if it is needed from pagure.ui.fas_login import FAS FAS.init_app(app) elif auth == "oidc": # Only import and set flask_fas_openid if it is needed from pagure.ui.oidc_login import oidc, fas_user_from_oidc oidc.init_app(app) app.before_request(fas_user_from_oidc) if auth == "local": # Only import the login controller if the app is set up for local login import pagure.ui.login as login app.before_request(login._check_session_cookie) app.after_request(login._send_session_cookie) # Support proxy app.wsgi_app = pagure.proxy.ReverseProxied(app.wsgi_app) # Back port 'equalto' to older version of jinja2 app.jinja_env.tests.setdefault("equalto", lambda value, other: value == other) # Import the application from pagure.api import API # noqa: E402 app.register_blueprint(API) from pagure.ui import UI_NS # noqa: E402 app.register_blueprint(UI_NS) from pagure.internal import PV # noqa: E402 app.register_blueprint(PV) # Import 3rd party blueprints plugin_config = flask.config.Config("") if "PAGURE_PLUGIN" in os.environ: # Warn the user about deprecated variable (defaults to stderr) warnings.warn( "The environment variable PAGURE_PLUGIN is deprecated and will be " "removed in future releases of Pagure. Please replace it with " "PAGURE_PLUGINS_CONFIG instead.", FutureWarning, ) # Log usage of deprecated variable logger.warning("Using deprecated variable PAGURE_PLUGIN. " "You should use PAGURE_PLUGINS_CONFIG instead.") plugin_config.from_envvar("PAGURE_PLUGIN") elif "PAGURE_PLUGINS_CONFIG" in os.environ: plugin_config.from_envvar("PAGURE_PLUGINS_CONFIG") elif "PAGURE_PLUGINS_CONFIG" in app.config: # If the os.environ["PAGURE_PLUGINS_CONFIG"] is not set, we try to load # it from the pagure config file. plugin_config.from_pyfile(app.config.get("PAGURE_PLUGINS_CONFIG")) for blueprint in plugin_config.get("PLUGINS") or []: logger.info("Loading blueprint: %s", blueprint.name) app.register_blueprint(blueprint) themename = pagure_config.get("THEME", "default") here = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)))) themeblueprint = flask.Blueprint( "theme", __name__, static_url_path="/theme/static", static_folder=os.path.join(here, "themes", themename, "static"), ) # Jinja can be told to look for templates in different folders # That's what we do here template_folders = os.path.join( app.root_path, app.template_folder, os.path.join(here, "themes", themename, "templates"), ) import jinja2 # Jinja looks for the template in the order of the folders specified templ_loaders = [ jinja2.FileSystemLoader(template_folders), app.jinja_loader, ] app.jinja_loader = jinja2.ChoiceLoader(templ_loaders) app.register_blueprint(themeblueprint) # Setup WhiteNoise for serving static files app.wsgi_app = WhiteNoise(app.wsgi_app, root=os.path.join(here, "static"), prefix="/static") app.before_request(set_request) app.after_request(after_request) app.teardown_request(end_request) if perfrepo: # Do this at the very end, so that this after_request comes last. app.after_request(perfrepo.print_stats) app.add_url_rule("/login/", view_func=auth_login, methods=["GET", "POST"]) app.add_url_rule("/logout/", view_func=auth_logout) return app
def init_app(app: flask.Flask): app.config["SESSION_TYPE"] = "sqlalchemy" app.config["SESSION_SQLALCHEMY"] = db flask_session.Session(app)
# Copyright (C) 2020, Sardoodledom ([email protected]) # All rights reserved. # # Although you can see the source code, it is not free and is # protected by copyright. If you are interested in using it, please # contact us at: [email protected] import flask_session #from flask import Flask, session #from flask_session import Session, FileSystemSessionInterface sess = flask_session.Session()
_GET = ['GET'] _POST = ['POST'] CAPTCHA_ENABLED = False K_LOGGED_IN = 'logged_in' K_LOGGED_USER = '******' K_CIPHERKEY = 'userdata' K_AUTH_USER = '******' K_CAPTCHA = 'captcha_solution' app = flask.Flask(__name__) backend.setup_app(app) session_obj_handle = flask_session.Session(app) class WebException(Exception): pass def get_required_params(where, fields, soft_fail=False): kw = {} src = None if where == 'GET': src = flask.request.args if where == 'POST': src = flask.request.form for vn in fields: val = src.get(vn, None)