def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello # @app.route('/hello') # def hello(): # return 'Hello, World!' # @app.route('/') # def index(): # return 'Index Page' from . import db db.init_app(app) from . import auth app.register_blueprint(auth.bp) from . import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index') from . import attd app.register_blueprint(attd.bp) from . import event app.register_blueprint(event.bp) from . import alliswell app.register_blueprint(alliswell.bp) from . import profile app.register_blueprint(profile.bp) def strftime_to_localtime(t): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t.timestamp() + 28800)) app.add_template_global(strftime_to_localtime) with app.app_context(): from . import daily app.register_blueprint(daily.bp) return app
def create_app(config_name): # 创建app实例对象 app = Flask(__name__) # 加载配置 app.config.from_object(config.get(config_name) or 'default') # 执行额外的初始化 config.get(config_name).init_app(app) # 注册蓝图路由 from app.view.admin import admin as admin_blueprint from app.view.home import home as home_blueprint from app.view.tool import tool as tool_blueprint app.register_blueprint(home_blueprint, url_prefix='/') app.register_blueprint(admin_blueprint, url_prefix="/admin") app.register_blueprint(tool_blueprint, url_prefix="/tool") # 设置debug=True,让toolbar生效 # app.debug=True # 加载数据库 db.init_app(app) migrate.init_app(app, db) # 加载邮件插件 mail.init_app(app) # 加载用户登录插件 login_manager.init_app(app) # 定义全局函数 from app.function.redis import get_explore_post_count app.add_template_global(get_explore_post_count, 'get_explore_post_count') # 返回app实例对象 app.app_context().push() return app
def create_app(init=False): app = Flask(__name__, static_url_path="/elegon/static", template_folder="templates") app.config.from_object("elegon.config") app.secret_key = "c534d51a57638e8a8a51c36d4a4128b89f8beb22" for ext in (db, openid2): ext.init_app(app) for bp in blueprints: import_name = "%s.ui.%s:bp" % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs, enumerate): app.add_template_global(fl) with app.app_context(): db.create_all() @app.before_request def init_global_vars(): user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}")) g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None g.start = request.args.get("start", type=int, default=0) g.limit = request.args.get("limit", type=int, default=20) init_logging() if init: init_scheduler() start_scheduler() signal.signal(signal.SIGTERM, stop_scheduler) signal.signal(signal.SIGHUP, stop_scheduler) return app
def create_app(): app = Flask(__name__, static_url_path='/argonath/static') app.config.from_object('argonath.config') app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True) app.secret_key = 'wolegeca' logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO) for ext in (db, ): ext.init_app(app) for bp in blueprints: import_name = '%s.views.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs): app.add_template_global(fl) @app.before_request def init_global_vars(): g.user = '******' in session and User.get(session['id']) or None g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) return app
def create_app(config_state): app = Flask(__name__) # Creating the app configurations app.config.from_object(config_options[config_state]) # Initializing flask extensions bootstrap.init_app(app) db.init_app(app) mail.init_app(app) csrf.init_app(app) login_manager.init_app(app) # Registering the blueprint from .main import main as main_blueprint app.register_blueprint(main_blueprint) # from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint) app.add_template_global(reversed, name='reversed') # Configure UploadSet configure_uploads(app,photos) return app
def create_app(environment='development'): app = Flask(__name__, static_url_path='/', static_folder='templates') app.config['ENV'] = environment env = app.config.get('ENV') if env == 'production': app.config.from_object('app.config.setting.ProductionConfig') app.config.from_object('app.config.secure.ProductionSecure') elif env == 'development': app.config.from_object('app.config.setting.DevelopmentConfig') app.config.from_object('app.config.secure.DevelopmentSecure') app.config.from_object('app.config.log') from app.libs.Helper import Helper app.add_template_global(Helper) register_extensions(app) register_commands(app) register_shell_context(app) register_blueprints(app) register_errors(app) register_before_request(app) register_after_request(app) mount_router(app) return app
def create_app(): app = Flask(__name__, static_url_path='/neptulon/static') app.config.from_object('neptulon.config') app.secret_key = app.config['SECRET_KEY'] logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO) db.init_app(app) mail.init_app(app) oauth.init_app(app) for bp in blueprints: import_name = '%s.views.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs): app.add_template_global(fl) @app.before_request def init_global_vars(): g.user = None if 'id' in session: g.user = User.get(session['id']) g.redir = request.args.get('redirect', '') g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) return app
def create_app(): """application factory""" app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or os.urandom(32) app.config['DYNAMO_TABLES'] = [{ 'TableName': TABLE_NAME, 'KeySchema': [{ 'AttributeName': 'id', 'KeyType': 'HASH' }], 'AttributeDefinitions': [{ 'AttributeName': 'id', 'AttributeType': 'S' }], 'ProvisionedThroughput': { 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } }] dynamo.init_app(app) login_manager.init_app(app) login_manager.login_view = 'app.login_route' login_manager.login_message = 'Not logged in' login_manager.login_message_category = 'error' app.register_blueprint(blueprint, url_prefix='/') # least intrusive way to pass token into every view without enforcing csrf on all routes app.add_template_global(name='csrf_token', f=generate_csrf) return app
def create_app(config=Config): app = Flask(__name__) app.config.from_object(config) db.init_app(app) migrate.init_app(app, db) login.init_app(app) jwt.init_app(app) ma.init_app(app) register_blueprints(app) def include_asset(asset, type): static_path = app.static_folder manifest_file = os.path.join(static_path, 'assets', 'manifest.json') try: with open(manifest_file) as f: manifest = json.loads(f.read()) except IOError: raise IOError('Manifest not found') bp, asset_name = asset.split('/') if type == 'js': asset_key = '/'.join([bp, asset_name, f'{asset_name}.js']) asset_hash = manifest.get(asset_key) return f'<script src="static/assets/{asset_hash}"></script>' if type == 'css': asset_key = '/'.join([bp, asset_name, f'{asset_name}.css']) asset_hash = manifest.get(asset_key) return f'<link rel="stylesheet" href="static/assets/{asset_hash}">' app.add_template_global(include_asset) return app
def create_app(): app = Flask(__name__, static_url_path='/argonath/static') app.config.from_object('argonath.config') app.secret_key = 'wolegeca' logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO) for ext in (db, openid2): ext.init_app(app) for bp in blueprints: import_name = '%s.views.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs): app.add_template_global(fl) @app.before_request def init_global_vars(): user_dict = json.loads(request.cookies.get(app.config['OPENID2_PROFILE_COOKIE_NAME'], '{}')) g.user = user_dict and User.get_or_create(user_dict['username'], user_dict['email']) or None g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) return app
def configured_app(): # web framework # web application # __main__ app = Flask(__name__) # 设置 secret_key 来使用 flask 自带的 session # 这个字符串随便你设置什么内容都可以 app.secret_key = secret.secret_key app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:{}@localhost/bbs?charset=utf8mb4'.format( secret.database_password) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) admin = Admin(app, name='frostW', template_mode='bootstrap3') mv = UserModelView(User, db.session) admin.add_view(mv) mv = ModelView(Board, db.session, endpoint="Board") admin.add_view(mv) admin.add_view(ModelView(Mail, db.session, endpoint="Mail")) admin.add_view(ModelView(Topic, db.session, endpoint="Topic")) admin.add_view(ModelView(Reply, db.session, endpoint="Reply")) admin.add_view(ModelView(Update, db.session, endpoint="Update")) app.add_template_global(current_user, 'current_user') app.add_template_global(get_time, 'get_time') register_routes(app) return app
def create_app(): app = Flask(__name__, static_url_path='/huhuran/static') app.config.from_object('huhuran.config') app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True) app.secret_key = app.config['SECRET_KEY'] logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.INFO) for ext in (db, ): ext.init_app(app) for bp in blueprints: import_name = '%s.views.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min): app.add_template_global(fl) @app.before_request def init_global_vars(): g.user = '******' in session and get_user(sso.get('me').data) or None g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) return app
def create_app(): # 初始化项目实例 app = Flask(__name__, template_folder=BASE_TEMPLATE_FOLDER, static_folder=os.path.join(BASE_DIR, 'frontend', 'static')) app.secret_key = app.config['SECRET_KEY'] # 导入配置项 app.config.from_object(config) # 注册路由 register(app) # 注册数据库 db.init_app(app) # 第二课增加内容 # 注册登录组件 login_manager.init_app(app) # 第三课增加内容 # 将变量注册到jinja全局变量 app.add_template_global(app.config['PROJECTNAME'], 'PROJECTNAME') app.add_template_global(app.config['STATIC_URL'], 'STATIC_URL') # 钩子 在请求执行之前 @app.before_request def before_request(): pass @app.route("/") # 默认主页 def index(): # return "Hello python!" return render_template("/account/login.html") @app.route("/index") def index2(): return render_template("/account/login.html") return app
def init(app: flask.Flask): banner() db.init() app.secret_key = config.SECRET_KEY app.permanent_session_lifetime = config.SESSION_TTL app.config['TEMPLATES_AUTO_RELOAD'] = True def static_url_for(path: str) -> str: return config.STATIC_BASEURL + path app.add_template_global(static_url_for) try: install_service_assets() apply_middlewares(app) attach_routes(app) start_background_tasks() except Exception as err: print(err) print('!' * 80, 'Initialization failed', err, '!' * 80, sep='\n\n', file=sys.stderr, flush=True) exit(4) # Tell gunicorn not to infinitely respawn
def create_app(**config_overrides): app = Flask(__name__) # Load config app.config.from_pyfile('settings.py') # Apply config overrides for test app.config.update(**config_overrides) # Initialize db db.init_app(app) Migrate(app, db) login_manager.init_app(app) # Import Blueprints from .auth.views import auth_app from .users.views import users_app # Register Blueprints app.register_blueprint(auth_app) app.register_blueprint(users_app) app.add_template_global(has_error, name='has_error') return app
def create_app(): #初始化项目实例 app = Flask(__name__, template_folder=BASE_TEMPLATE_FOLDER, static_folder=os.path.join(BASE_DIR, 'frontend', 'static')) app.secret_key = app.config['SECRET_KEY'] #导入配置项 app.config.from_object(config) # 注册路由 register(app) # 注册数据库 db.init_app(app) #第二课增加内容 #注册登录组件 login_manager.init_app(app) #第三课增加内容 # 将变量注册到jinja全局变量 app.add_template_global(app.config['PROJECTNAME'], 'PROJECTNAME') # 钩子 在请求执行之前 @app.before_request def before_request(): print(current_user.username) #print('hi') return app
def create_app(config_name): """ To creat a application instance, introduct a name of the config object which locates in the config.py file. """ app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bcrypt.init_app(app) db.init_app(app) login_manager.init_app(app) mail.init_app(app) moment.init_app(app) principal.init_app(app) pagedown.init_app(app) search.init_app(app) from .controller import main as main_blueprint app.register_blueprint(main_blueprint, template_folder="../templates/main") from .controller import auth as auth_blueprint app.register_blueprint(auth_blueprint, template_folder="../templates/auth") from .controller import api_bp as api_blueprint app.register_blueprint(api_blueprint) @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, "id"): identity.provides.add(UserNeed(current_user.id)) if hasattr(current_user, "permissions"): for pm in current_user.permissions.all(): identity.provides.add(need(pm.name)) from .extensions import need def has_permission(name): """Used by template to judge whether the user has some permissions.""" if Permission(need(name)).can(): return True else: return False app.add_template_global(has_permission, "has_permission") if app.config.get('FLASK_CONFIG', 'development') == 'productive': # Build the post index only for the productive environment. with app.app_context(): search.create_index(update=True) return app
def create_app(): # Create a Flask instance. qflask = Flask(__name__) csrf = CSRFProtect() csrf.init_app(qflask) # Retrieve QRadar app id. qradar_app_id = qpylib.get_app_id() # Create unique session cookie name for this app. qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id) secret_key = "" try: # Read in secret key secret_key_store = Encryption({'name': 'secret_key', 'user': '******'}) secret_key = secret_key_store.decrypt() except EncryptionError: # If secret key file doesn't exist/fail to decrypt it, # generate a new random password for it and encrypt it secret_key = secrets.token_urlsafe(64) secret_key_store = Encryption({'name': 'secret_key', 'user': '******'}) secret_key_store.encrypt(secret_key) qflask.config["SECRET_KEY"] = secret_key # Hide server details in endpoint responses. # pylint: disable=unused-variable @qflask.after_request def obscure_server_header(resp): resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id) return resp # Register q_url_for function for use with Jinja2 templates. qflask.add_template_global(qpylib.q_url_for, 'q_url_for') # Initialize logging. qpylib.create_log() # To enable app health checking, the QRadar App Framework # requires every Flask app to define a /debug endpoint. # The endpoint function should contain a trivial implementation # that returns a simple confirmation response message. @qflask.route('/debug') def debug(): return 'Pong!' # Import additional endpoints. # For more information see: # https://flask.palletsprojects.com/en/1.1.x/tutorial/views from . import views qflask.register_blueprint(views.viewsbp) return qflask
def app_factory(**kwargs): app = Flask(__name__) app.config.from_object(config_combined) db.init_app(app) DebugToolbarExtension(app) app.add_template_global(string_isinstance, name='string_isinstance') login_manager = LoginManager(app) @login_manager.user_loader def load_user(user_id): return User() @app.route('/') def index(): return render_template('index.html') @app.route('/login/', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if form.validate_on_submit(): if (form.username.data == app.config['ADMIN_USERNAME'] and form.password.data == app.config['ADMIN_PASSWORD']): user = User() login_user(user) return redirect(url_for('index')) else: form.username.errors.append('Invalid Username...') form.password.errors.append('...or Password') return render_template('login.html', form=form) @app.route('/logout/') def logout(): logout_user() return redirect(url_for('login')) @app.route('/content/') @login_required def content(): return render_template('content.html') @app.errorhandler(404) def err404(e): return render_template('404.html'), 404 @app.errorhandler(500) def err500(e): return render_template('500.html'), 500 return app
def create_app(): # Create a Flask instance. qflask = Flask(__name__) # Retrieve QRadar app id. qradar_app_id = qpylib.get_app_id() # Create unique session cookie name for this app. qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id) # Hide server details in endpoint responses. # pylint: disable=unused-variable @qflask.after_request def obscure_server_header(resp): resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id) return resp # Register q_url_for function for use with Jinja2 templates. qflask.add_template_global(qpylib.q_url_for, 'q_url_for') # Initialize logging. qpylib.create_log() # To enable app health checking, the QRadar App Framework # requires every Flask app to define a /debug endpoint. # The endpoint function should contain a trivial implementation # that returns a simple confirmation response message. @qflask.route('/debug') def debug(): return 'Pong!' # Flask-Babel is an extension to Flask that adds i18n and l10n support # to any Flask application with the help of babel, pytz and speaklater. babel = Babel(qflask) # Try to select the language from the user accept header the browser transmits. # We support en/es/fr in this example. # The best match wins. @babel.localeselector def get_locale(): return request.accept_languages.best_match(LANGUAGES.keys()) # Import additional endpoints. # For more information see: # https://flask.palletsprojects.com/en/1.1.x/tutorial/views from . import views qflask.register_blueprint(views.viewsbp) return qflask
def create_app(config_name='development', p_db=db, p_bcrypt=bcrypt, p_login_manager=login_manager): new_app = Flask(__name__) config_app(config_name, new_app) p_db.init_app(new_app) p_bcrypt.init_app(new_app) p_login_manager.init_app(new_app) p_login_manager.login_view = 'register' db.init_app(new_app) init_models_module(db, p_bcrypt, new_app) # Add translator utilities. new_app.add_template_global(translator.translate) return new_app
def create_app(config_file=None): app = Flask(__name__) app = change_jinja_templates(app) if config_file: app.config.from_pyfile(config_file) else: app.config.from_envvar("CLA_PUBLIC_CONFIG") if app.config.get("SENTRY_DSN"): app.sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN"), logging=True, level=logging.ERROR) app.babel = Babel(app) app.babel.localeselector(get_locale) app.cache = Cache(app) app.mail = Mail(app) for extension in app.config["EXTENSIONS"]: extension.init_app(app) app.session_interface = CheckerSessionInterface() app.json_encoder = CustomJSONEncoder register_error_handlers(app) app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name") app.register_blueprint(base) app.register_blueprint(geocoder) app.register_blueprint(contact) app.register_blueprint(scope) if not app.config.get("CONTACT_ONLY"): app.register_blueprint(checker) logging.config.dictConfig(app.config["LOGGING"]) # quiet markdown module logging.getLogger("MARKDOWN").setLevel(logging.WARNING) if app.debug: from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) return app
def create_app(object_name): scheduler = APScheduler() api_server = Api_Server() app = Flask(__name__) app.config.from_object(DevConfig) # create_admin(app) login_manager.session_protection = 'strong' login_manager.login_view = '/' login_manager.init_app(app) principals.init_app(app) db.init_app(app) scheduler.init_app(app) scheduler.start() #模块注册 app.register_blueprint(stock_blueprint) app.register_blueprint(stocksolo_blueprint) app.register_blueprint(stockgroup_blueprint) app.register_blueprint(globalindustry_blueprint) app.register_blueprint(industryanalysis_blueprint) app.register_blueprint(investenv_blueprint) app.register_blueprint(api_blueprint) app.register_blueprint(main_view) app.register_blueprint(main_api) app.register_blueprint(stock_group_view) app.register_blueprint(stock_group_api) app.register_blueprint(quant_view) app.register_blueprint(quant_api) app.register_blueprint(industry_analysis_view) app.register_blueprint(industry_analysis_api) app.register_blueprint(message_view) app.register_blueprint(message_api) # app.register_blueprint(visitor_view) #添加jinjia2全局变量 app.add_template_global(api_server.get_server_address(), 'Api_Server') @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): identity.user = current_user if hasattr(current_user, "username"): identity.provides.add(UserNeed(current_user.username)) if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) return app
def create_app(config_file=None, config_object=None): """ Application bootstrapper. """ app = Flask(__name__, static_folder='public') app.config.from_object('eveauth.settings.BaseConfig') app.environment = os.getenv('eveauth_ENV', 'dev') if config_file: file_ext = os.path.splitext(config_file)[1] if file_ext == '.yml': with open(config_file) as f: config_yaml = yaml.load(f) app.config.update(**config_yaml) elif file_ext == '.py': app.config.from_pyfile(config_file) else: raise Exception('Unsupported config file format: {}, expecting Yaml or Python'.format(file_ext)) if config_object: app.config.update(**config_object) if app.environment != 'test': csrf.init_app(app) from eveauth.api import api_manager api_manager.init_app(app) from eveauth.models import db, migrate, ma db.init_app(app) migrate.init_app(app, db) ma.init_app(app) from eveauth.controllers import MetaView MetaView.register(app) from eveauth.services import sso_service sso_service.init_app(app) app.add_template_global(app.config, 'config') return app
def create_app(): app = Flask(__name__) src = os.path.abspath(os.path.join('app', './config.json')) config = {} with open(src, 'r') as f: config = json.load(f) labels = ['global', 'mongodb', 'redis', 'mysql', 'secret_key'] for index in range(len(labels)): key = labels[index] app.config[key] = config[key] pass app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.add_template_global(app.config.get('global'), 'config') return app
def create_app(): app = Flask(__name__, template_folder='./templates') mode = app.env Config = load_config(mode) app.config.from_object(Config) app.add_template_global(name='momentjs', f=momentjs) from .db import db db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'nonAuth.login' login_manager.init_app(app) from .models.users import User from .models.task_types import TaskType from .models.tasks import Task @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass with app.app_context(): # import non auth routes from .non_auth_routes.non_auth import nonAuth as non_auth_blueprint app.register_blueprint(non_auth_blueprint) # import auth routes from .auth_routes.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) db.create_all() return app
def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get( 'SECRET_KEY') or 'hard to guess string' app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN') app.config['FLASKY_POSTS_PER_PAGE'] = 20 app.config['FLASKY_FOLLOWERS_PER_PAGE'] = 50 app.config['FLASKY_COMMENTS_PER_PAGE'] = 30 from .auth.models import current_user app.add_template_global(current_user, 'current_user') # CORS(app, supports_credentials=True) moment.init_app(app) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) db.init_app(app) csrf.init_app(app) login_manager.init_app(app) moment.init_app(app) Markdown(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint) app.add_template_global(get_curYear, 'get_curYear') app.add_template_global(set_curYear, 'set_curYear') app.add_template_global(get_curMonth, 'get_curMonth') app.add_template_global(set_curMonth, 'set_curMonth') app.add_template_global(get_left, 'get_left') app.add_template_global(set_left, 'set_left') return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) os.makedirs(app.config['STORAGE'], exist_ok=True) db.init_app(app) humanize = Humanize(app) migrate.init_app(app, db) login.init_app(app) app.hashids = Hashids(alphabet=app.config['HASHIDS_ALPHABET'], min_length=app.config['HASHIDS_MIN_LEN'], salt=app.config['HASHIDS_SALT']) from app.auth import bp as auth_bp # noqa: E402 app.register_blueprint(auth_bp, url_prefix='/auth') from app.misc_routes import bp as misc_routes_bp # noqa: E402 app.register_blueprint(misc_routes_bp) from app.profile import bp as profile_bp # noqa: E402 app.register_blueprint(profile_bp, url_prefix='/profile') from app.file import bp as file_bp # noqa: E402 app.register_blueprint(file_bp, url_prefix='/file') from app.auth import uid_str app.add_template_global(name='uid_str', f=uid_str) app.add_template_global(name='humanize', f=humanize) app.add_template_global(name='hashids_encode', f=app.hashids.encode) return app
def __init(): from flask import Flask from conf.config import FLASK_SQLALCHEMY_DATABASE_URI, FLASK_UPLOAD_FOLDER, FLASK_SECRET_KEY app = Flask(__name__) # 初始化session app.secret_key = FLASK_SECRET_KEY # 文件上传目录 app.config['UPLOAD_FOLDER'] = FLASK_UPLOAD_FOLDER # 数据库初始化 app.config['SQLALCHEMY_DATABASE_URI'] = FLASK_SQLALCHEMY_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True from web.model.pojo import db db.init_app(app) db.create_all(app=app) # 注册蓝图 from web.view.ts_view import main app.register_blueprint(main) from web.view.demo_view import demo app.register_blueprint(demo, url_prefix='/demo') app.add_template_global(type, "type") app.add_template_global(len, "len") app.add_template_global(list, "list") return app
def create_app(config_name): # 初始化app对象 set_log(config_name) app = Flask(__name__) # 加载配置 app.config.from_object(config[config_name]) # 汉化 babel = Babel(app) CSRFProtect(app) # 初始化数据库对象 db.init_app(app) # 初始化admin对象 blog_admin.init_app(app) from blog.admin.article import AddArticleView blog_admin.add_view(AddArticleView(name='发布文章', endpoint='add_article')) # 导入admin配置 from blog.admin import admin # 注册蓝图 from blog.modules.page import page_blu app.register_blueprint(page_blu) from blog.modules.admin import admin_blu app.register_blueprint(admin_blu) from blog.modules.article import article_blu app.register_blueprint(article_blu) # 注册函数 from blog.modules.page import blog_tag app.add_template_global(blog_tag) # 返回app对象 return app
def configured_app(): app = Flask(__name__) # 设置 secret_key 来使用 flask 自带的 session # 这个字符串随便设置什么内容都可以 app.secret_key = secret.secret_key # 数据返回顺序 # mysql -> pymysql -> sqlalchemy -> route # 初始化顺序 # app -> flask-sqlalchemy -> sqlalchemy -> pymysql -> mysql app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:{}@localhost/Anfield?charset=utf8mb4'.format( secret.database_password) db.init_app(app) app.register_blueprint(index_routes) app.register_blueprint(topic_routes, url_prefix='/topic') app.register_blueprint(reply_routes, url_prefix='/reply') app.register_blueprint(homepage_routes, url_prefix='/homepage') app.register_blueprint(personal_routes, url_prefix='/personal') app.register_blueprint(mail_routes, url_prefix='/mail') app.register_blueprint(reset_routes, url_prefix='/reset') log('url map', app.url_map) app.template_filter()(count) app.template_filter()(format_time) app.errorhandler(404)(not_found) app.add_template_global(current_user, 'current_user') admin = Admin(app, name='Anfield', template_mode='bootstrap3') admin.add_view(UserModelView(User, db.session)) admin.add_view(UserModelView(Topic, db.session)) admin.add_view(UserModelView(Reply, db.session)) admin.add_view(UserModelView(Messages, db.session)) mv = UserModelView(Board, db.session) admin.add_view(mv) # Add administrative views here return app
def create_app(init=False): app = Flask(__name__, static_url_path='/elegon/static', template_folder='templates') app.config.from_object('elegon.config') app.secret_key = 'c534d51a57638e8a8a51c36d4a4128b89f8beb22' for ext in (db, openid2): ext.init_app(app) for bp in blueprints: import_name = '%s.ui.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs, enumerate): app.add_template_global(fl) with app.app_context(): db.create_all() @app.before_request def init_global_vars(): user_dict = json.loads( request.cookies.get(app.config['OPENID2_PROFILE_COOKIE_NAME'], '{}')) g.user = user_dict and User.get_or_create(user_dict['username'], user_dict['email']) or None g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) init_logging() if init: init_scheduler() start_scheduler() signal.signal(signal.SIGTERM, stop_scheduler) signal.signal(signal.SIGHUP, stop_scheduler) return app
def create_app(): from flask import Flask from flask_cors import CORS from app.web import bp_api, bp_web, bp_ws from app.core.lib import ScanThread from app.conf.conf import cors_origin init() app = Flask(__name__) app.secret_key = secret_key CORS(bp_api, supports_credentials=True, origins=cors_origin) CORS(bp_ws, supports_credentials=True, origins=cors_origin) app.register_blueprint(bp_api) app.register_blueprint(bp_web) app.register_blueprint(bp_ws) # jinja2 function app.add_template_global(system_types, 'system_types') app.add_template_global(workspace_status, 'workspace_status') app.add_template_global(func_account, 'func_account') app.add_template_global(is_manager, 'is_manager') app.add_template_global(time_now, 'time_now') app.add_template_filter(time_show, 'time_show') app.add_template_filter(ws_roles, 'ws_roles') app.add_template_filter(format_json, 'json_show') app.add_template_filter(format_request, 'request_show') app.add_template_filter(format_response, 'response_show') app.add_template_filter(str_show, 'str_show') app.add_template_filter(request_num, 'request_num') # 开启扫描任务 ScanThread().start() return app
def create_app(): # Create a Flask instance. qflask = Flask(__name__) # Retrieve QRadar app id. qradar_app_id = qpylib.get_app_id() # Create unique session cookie name for this app. qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id) # Hide server details in endpoint responses. # pylint: disable=unused-variable @qflask.after_request def obscure_server_header(resp): resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id) return resp # Register q_url_for function for use with Jinja2 templates. qflask.add_template_global(qpylib.q_url_for, 'q_url_for') # Initialize logging. qpylib.create_log() # To enable app health checking, the QRadar App Framework # requires every Flask app to define a /debug endpoint. # The endpoint function should contain a trivial implementation # that returns a simple confirmation response message. @qflask.route('/debug') def debug(): return 'Pong!' # Import additional endpoints. # For more information see: # https://flask.palletsprojects.com/en/1.1.x/tutorial/views from . import views qflask.register_blueprint(views.viewsbp) return qflask
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'todo.db'), TEMPLATES_AUTO_RELOAD=True) app.add_template_global(generate_timestamp, name='timestamp') if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config) try: os.makedirs(app.instance_path) except OSError: pass with app.app_context(): from todo_list import api, views return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) AppName = config[config_name].AppName app.add_template_global(AppName, 'AppName') #moment.init_app(app) db.init_app(app) mail.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api') return app
def create_app(): app = Flask('Ainur', static_url_path='/static') app.config.from_object('config') app.secret_key = app.config['SECRET'] db.init_app(app) db.app = app db.create_all() rds.init_app(app) for bp in blueprints: import_name = '%s.%s:bp' % (__package__, bp) app.register_blueprint(import_string(import_name)) for fl in (max, min, paginator_kwargs, login_url): app.add_template_global(fl) @app.before_request def init_global_vars(): g.page = request.args.get('page', type=int, default=0) g.start = request.args.get('start', type=int, default=g.page * 20) g.limit = request.args.get('limit', type=int, default=20) if request.path == '/user/login_from_openid/' or request.path.startswith('/ajax'): return if 'uid' not in session: abort(401) g.user = User.get_by_uid(session['uid']) @app.errorhandler(403) @app.errorhandler(401) def error_handler(e): return render_template('errors/%s.html' % e.code), e.code return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) moment.init_app(app) login_manager.init_app(app) login_manager.login_view = 'auth.login' db.init_app(app) from .main import main from .auth import auth from .manager import manager app.register_blueprint(main) app.register_blueprint(auth) app.register_blueprint(manager) configure_uploads(app, photos) patch_request_class(app) from .models import Message, User, Post, Praise, Comment, Collection app.add_template_global(Message, 'Message') app.add_template_global(User, 'User') app.add_template_global(Post, 'Post') app.add_template_global(Comment, 'Comment') return app
@app.template_global() def static_url(**values): """Return a static url with an mtime query string for cache busting.""" filename = values.get('filename', None) if not filename: return url_for('static', **values) file_path = os.path.join(app.static_folder, filename) if os.path.exists(file_path): values['mtime'] = int(os.stat(file_path).st_mtime) return url_for('static', **values) app.add_template_global(datetime.date.today, 'today') CACHED_URL_FOR = functools.lru_cache(2048)(flask.url_for) @app.template_global() def url_for(endpoint, **values): """A wrapper around flask.url_for that uses a cache.""" _inject_filters(endpoint, values) return CACHED_URL_FOR(endpoint, **values) @app.template_global() def url_for_current(**kwargs): """URL for current page with updated request args.""" if not kwargs: return url_for(request.endpoint, **request.view_args)
## Flask-Bootstrap Bootstrap(app) ## Flask-Assets assets = Environment(app) js = Bundle('js/selectize.min.js', 'js/main.js', output='assets/all.js') css = Bundle('css/selectize.bootstrap3.css', 'css/style.css', output='assets/all.css') assets.register('js', js) assets.register('css', css) def all_roles(): return select(r for r in Role).order_by(Role.name) app.add_template_global(all_roles, name='all_roles') app.add_template_global(arrow.now, name='now') @app.route('/') @db_session def index(): return render_template('index.html') @app.route('/roles.json', methods=['POST']) @db_session def roles_create(): name = request.form['name'] role = Role(name=name) commit() return jsonify(result=role.to_dict())
import inspect import logging from datetime import datetime import ucam_webauth import raven import raven.demoserver import raven.flask_glue from flask import Flask, request, render_template, redirect, \ url_for, abort, session, flash app = Flask(__name__) app.config["SECRET_KEY"] = os.urandom(16) app.add_template_global(repr, name="repr") app.add_template_global(getattr, name="getattr") modules = {"ucam_webauth": ucam_webauth, "raven": raven, "raven.demoserver": raven.demoserver} auth_decorator = raven.flask_glue.AuthDecorator() @app.route("/") def home(): return render_template("home.html") @app.route("/decorated") @auth_decorator def decorated(): return render_template("decorated.html", a=auth_decorator)
def create_app(config_name): """Create a Flask instance based on a Config subclass. Args: config_name (str): The config mode we want to load. Options for this are enumerated in the CONFIG dictionary in ``/config.py``. Returns: app (Flask): A Flask application instance with the config options specified by the Config subclass specified by ``CONFIG[config_name]``. """ app = Flask(__name__) app.config.from_object(CONFIG[config_name]) CONFIG[config_name].init_app(app) db.init_app(app) login_manager.init_app(app) mail.init_app(app) from .auth import auth as auth_blueprint from .seeds import seeds as seeds_blueprint from .shop import shop as shop_blueprint from .shop.models import Order app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(seeds_blueprint) app.register_blueprint(shop_blueprint, url_prefix='/shop') stripe.api_key = app.config.get('STRIPE_SECRET_KEY') ship_date = format_ship_date(get_ship_date()) # Add redirects rdf = RedirectsFile(app.config.get('REDIRECTS_FILE')) if rdf.exists(): rdf.load() rdf.add_all_to_app(app) # Clear pending changes messages pending = Pending(app.config.get('PENDING_FILE')) if pending.has_content(): # pragma: no cover pending.clear() pending.save() def sum_cart_items(): o = Order.load(current_user) try: return o.number_of_items except: return 0 # Make things available to Jinja app.add_template_global(ship_date, 'ship_date') app.add_template_global(Permission, 'Permission') app.add_template_global(pluralize, 'pluralize') app.add_template_global(load_nav_data, 'load_nav_data') app.add_template_global(slugify, 'slugify') app.add_template_global(sum_cart_items, 'sum_cart_items') # Error pages @app.errorhandler(404) def page_not_found(e): # TODO: Change this to use a logger. print('404 not found: {}'.format(request.url)) return render_template('errors/404.html'), 404 return app
def app_factory(**kwargs): app = Flask(__name__) ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) config_combined.UPLOAD_DIR = os.path.join( ROOT_DIR, config_combined.UPLOAD_DIR) app.config.from_object(config_combined) db.init_app(app) Babel(app) DebugToolbarExtension(app) app.add_template_global(string_isinstance, name='string_isinstance') login_manager = LoginManager(app) @login_manager.user_loader def load_user(user_id): return User() @app.route('/') def index(): recipes = Recipe.query.order_by(Recipe.posted_on.desc()).all() return render_template('index.html', recipes=recipes) @app.route('/photo/<int:recipe_id>/<string:tag>') def show_photo(recipe_id, tag): p = Photo.query.filter_by(recipe_id=recipe_id, tag=tag).first_or_404() return send_from_directory(app.config['UPLOAD_DIR'], p.saved_filename) @app.route('/login/', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if form.validate_on_submit(): if (form.username.data == app.config['ADMIN_USERNAME'] and form.password.data == app.config['ADMIN_PASSWORD']): user = User() login_user(user) return redirect(url_for('index')) else: form.username.errors.append('Invalid Username...') form.password.errors.append('...or Password') return render_template('login.html', form=form) @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index')) @app.errorhandler(404) def err404(e): return render_template('404.html'), 404 @app.errorhandler(500) def err500(e): return render_template('500.html'), 500 from .manage_bp import bp_factory as manage_factory app.register_blueprint(manage_factory()) return app
def create_app(): app = Flask(__name__) app.config.from_object('radar.default_settings') app.config.from_object('radar.web.default_settings') app.config.from_envvar('RADAR_SETTINGS') db.init_app(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.user_loader(load_user) login_manager.login_view = 'auth.login' Markdown(app) mail.init_app(app) app.register_blueprint(radar_bp) app.register_blueprint(auth_bp) app.register_blueprint(disease_groups_bp, url_prefix='/disease-groups') app.register_blueprint(units_bp, url_prefix='/units') app.register_blueprint(users_bp, url_prefix='/users') app.register_blueprint(patients_bp, url_prefix='/patients') app.register_blueprint(recruit_bp, url_prefix='/patients') app.register_blueprint(news_bp, url_prefix='/news') app.register_blueprint(stats_bp, url_prefix='/stats') patient_blueprints = [ (diagnosis_bp, '/diagnosis'), (dialysis_bp, '/dialysis'), (genetics_bp, '/genetics'), (hospitalisations_bp, '/hospitalisations'), (results_bp, '/results'), (medications_bp, '/medications'), (pathology_bp, '/pathology'), (plasmapheresis_bp, '/plasmapheresis'), (renal_imaging_bp, '/renal-imaging'), (salt_wasting_bp, '/salt-wasting'), (transplants_bp, '/transplants'), ] patient_base = '/patients/<int:patient_id>' for bp, url_prefix in patient_blueprints: app.register_blueprint(bp, url_prefix=patient_base + url_prefix) app.before_request(require_login) app.before_request(force_password_change) # Register template filters app.add_template_filter(strftime) app.add_template_filter(year_format) app.add_template_filter(date_format) app.add_template_filter(datetime_format) app.add_template_filter(nl2br) app.add_template_filter(missing) app.add_template_filter(yn) app.add_template_filter(number_format) # Register template globals/functions app.add_template_global(url_for_order_by) app.add_template_global(url_for_page) app.add_template_global(url_for_per_page) # Register context processors (data available in all templates) app.context_processor(inject_navigation) app.context_processor(inject_delete_form) # Register error handlers app.register_error_handler(403, forbidden) app.register_error_handler(404, page_not_found) app.register_error_handler(500, internal_server_error) # Automatically set the created_user and modified_user event.listen(SignallingSession, 'before_flush', before_flush_set_created_listener) event.listen(SignallingSession, 'before_flush', before_flush_set_modified_listener) return app
response.headers['X-Frame-Options'] = 'SAMEORIGIN' response.headers['X-XSS-Protection'] = '1; mode=block' # Todo: activate Content-Security-Policy after removal of every inline CSS and JavaScript # response.headers['Content-Security-Policy'] = "default-src 'self'" return response @app.teardown_request def teardown_request(exception): if hasattr(g, 'db'): g.db.close() @app.context_processor def inject_search_form(): return dict(search_form=GlobalSearchForm(prefix="global")) app.register_blueprint(filters.blueprint) app.add_template_global(debug_model, 'debug_model') @app.context_processor def inject_debug(): return dict(debug=app.debug) if __name__ == "__main__": # pragma: no cover app.run()
if request.method == 'POST': newCategory = Category( name=request.form['name'], user_id=login_session['user_id']) session.add(newCategory) flash('New Category %s Successfully Created' % newCategory.name) session.commit() return redirect(url_for('showCatalog')) else: return render_template('newCategory.html') def get_category(item): category = session.query(Category).filter_by(id=item.category_id).one() return category app.add_template_global(get_category, name='get_category') def is_logged_in(): return 'username' in login_session app.add_template_global(is_logged_in, name='is_logged_in') def get_count(q): count_q = q.statement.with_only_columns([func.count()]).order_by(None) count = q.session.execute(count_q).scalar() return count # Show a category
from flask import Flask, render_template, url_for, jsonify import json def fix_name(name): return name.replace(" ","_") data = json.load(open('report.json')) app = Flask(__name__) app.add_template_global(fix_name) @app.route("/") def report(): total_demand = data['demand']['Total Demand'] disaggregation_results = data['disaggregate'] reportdata = {k:v for k,v in data['demand'].iteritems() if k not in ["Demand Data", "Total Demand"]} return render_template("index.html", total_demand=total_demand, demand=reportdata, disaggregation_results=disaggregation_results, zones=data['zones']) @app.route("/demanddata") def demanddata(): return jsonify({'data': [{'date': k,'value': v} for k,v in data['demand']['Demand Data'].iteritems()]}) @app.route("/zonedata/<key>/<zone>") def zonedata(key, zone): """ key: "Min Daily Avg Demand" from report.demand_report zone: zone name like "DOSA" """ key = key.replace("_"," ") ret = {} for ts, dd in data['demand'][key]['Data'][zone].iteritems(): ret[ts] = [{'date': k, 'value': v} for k,v in dd.iteritems()]
flatpages = FlatPages(app) freezer = Freezer(app) moment = Moment(app) app.config['SECRET_KEY'] = 'Hard to guess String' def get_brow_info(): getinfo={} user_agent = request.headers.get('User-Agent') referer = request.headers.get('Referer') ip,user = request.remote_addr,request.remote_user getinfo['user_agent'] = user_agent getinfo['referer'] = referer getinfo['ip'] = ip getinfo['user'] = user return getinfo app.add_template_global(get_brow_info,'visinfo') @app.context_processor def url(): return dict(BASE_URL=BASE_URL) class SecForm(Form): password = StringField('Input Code',validators=[DataRequired()]) submit = SubmitField('Done') #@app.route('/pygments.css') #def py_css(): # return pygments_style_defs('monokai'), 200, {'Content-Type': 'text/css'} @app.route('/')
def create_app(): basedir = getcwd() instance = split(split(abspath(__file__))[0])[0] app = Flask(__name__, instance_path=instance) app.config.from_object('glask.config') file_handler = FileHandler(app.config['LOGFILE']) app.logger.addHandler(file_handler) if not app.config['DEBUG']: file_handler.setLevel(logging.WARNING) else: file_handler.setLevel(logging.DEBUG) if not GEXIV_SUPPORT: app.logger.warn('GExiv2 is not available, metadata and automatic image rotation disabled') app.config['GEXIV_SUPPORT'] = GEXIV_SUPPORT app.config['FREEZER_DESTINATION'] = abspath(app.config['FREEZER_DESTINATION']) assert isdir(app.config['PICS_DIR']), 'Pictures directory not found' assert isdir(app.config['SUBS_DIR']), 'Subsamples directory not found' config.PICS_EXTENSIONS = app.config['PICS_EXTENSIONS'] SUBSAMPLES_SIZES = app.config['SUBSAMPLES_GEOM'].keys() if app.config['LINK_ORIGINALS']: SUBSAMPLES_SIZES.append('original') app.add_template_global(join) @app.route('/') @app.route('/<path:path>/') def tree(path=u''): if is_picture(path): if app.config['USE_FANCYBOX']: return redirect(url_for('picture', size='hi', path=path)) else: return redirect(url_for('view', path=path)) fixed_path = _sanitize_path(path) fixed_path = join(app.config['PICS_DIR'], fixed_path) relative_path = relpath(fixed_path, start=app.config['PICS_DIR']) if relative_path == '.': relative_path = '' app.logger.debug('relative_path: ' + relative_path) tree = walk(fixed_path) try: (cdir, dirs, files) = tree.next() except: abort(404) finally: tree.close() pics = filter_pics(files) pics.sort() pic_titles = _index_view_titles(relative_path, pics) dirs.sort(cmp=app.config['ALBUMS_SORT_FUNC']) samples = {} for d in dirs: s = _album_samples(relative_path, d, n=app.config['SAMPLES_COUNT']) if len(s) == 0: dirs.remove(d) else: samples[d] = s return render_template('index.html', dirs=dirs[::-1], pics=pics, pic_titles=pic_titles, samples=samples, prefix=relative_path) if not app.config['USE_FANCYBOX']: @app.route('/<path:path>/view/') def view(path): fixed_path = _sanitize_path(path) if not is_picture(fixed_path) or not isfile(join(app.config['PICS_DIR'], fixed_path)): abort(404) (prefix, pic) = split(fixed_path) prefix += '/' return _render_pic_view(prefix, pic) @app.route('/<path:path>/raw/<size>.jpg') def picture(size='hi', path=''): fixed_path = _sanitize_path(path) extension = splitext(fixed_path)[1] if not extension in app.config['PICS_EXTENSIONS'] or not size in SUBSAMPLES_SIZES: abort(404) (prefix, pic) = split(fixed_path) if not prefix == '': prefix += '/' if size == 'original': if app.config['USE_SENDFILE']: return send_from_directory(join(app.instance_path, app.config['PICS_DIR'], prefix), pic, mimetype='image/jpeg') else: response = make_response() response.headers['Content-Type'] = 'image/jpeg' internal_url = quote(join(app.config['XACCEL_ORIGINAL'], prefix, pic).encode('utf-8')) response.headers['X-Accel-Redirect'] = internal_url return response else: return _serve_subsample(prefix, pic, size) if app.config['SERVE_ALBUMS_ARCHIVE']: @app.route('/download') @app.route('/<path:path>/download') def download(path=''): fixed_path = _sanitize_path(path) prefix, directory = split(join(app.config['PICS_DIR'], path)) if directory == '': prefix = basedir directory = app.config['PICS_DIR'] sent_filename = u'{0}.zip'.format(directory).encode('utf-8') archive_name = '{0}.zip'.format(punymd5(directory)) archive_path = join(app.config['SUBS_DIR'], archive_name) if not isfile(archive_path): zip = zipfile.ZipFile(archive_path, 'w') try: chdir(prefix) for root, dirs, files in walk(path): pics = filter_pics(files) for p in pics: zip.write(join(root, p)) finally: chdir(basedir) zip.close() return send_from_directory(join(app.instance_path, app.config['SUBS_DIR']), archive_name, as_attachment=True, attachment_filename=sent_filename) @app.route('/dynamic.css') def dynamic_css(): response = make_response() response.headers['Content-Type'] = 'text/css' response.data = render_template('dynamic.css') return response @app.template_filter('tobc') def path_to_breadcrumbs(path): if path == '': return '' p = normpath(path) dirs = p.split('/') part_path = '' p = u'' for d in dirs: part_path = join(part_path, d) p += u' › <a href="{0}">{1}</a>'.format( escape(url_for('tree', path=part_path)), escape(d)) return Markup(p) def _sanitize_path(path): fixed_path = normpath(u'/'+path)[1:] if fixed_path != path: abort(403) return fixed_path def _index_view_titles(relative_path, pics): prefix = join(app.config['PICS_DIR'], relative_path) pic_titles = {} for p in pics: title = "" if GEXIV_SUPPORT: src_file = join(prefix, p) meta = extract_base_meta(src_file, as_dict=True, as_string=True) fnumber = meta.get('fnumber') and 'f/{0}'.format(meta['fnumber']) expo = meta.get('expo') and ' {0}s'.format(meta['expo']) focal = meta.get('focal') and ' {0}mm'.format(meta['focal']) time = meta.get('time') and ' @ {0}'.format(meta['time']) title = u'{0}{1}{2}{3}'.format(fnumber, expo, focal, time) pic_titles[p] = title return pic_titles def _album_samples(relative_path, dir, n=10): samples = [] walk_root = join(app.config['PICS_DIR'], relative_path, dir) tree = walk(walk_root) try: while True: (cdir, dirs, files) = tree.next() if len(files) > 0: pics = filter_pics(files) shuffle(pics) for i in range(len(pics)): pics[i] = relpath(join(cdir, pics[i]), start=app.config['PICS_DIR']) samples.extend(pics[:(n-len(samples))]) if len(samples) == n: break shuffle(dirs) except Exception, e: pass finally:
# s3 options app.config['FLASKS3_ACTIVE'] = cfg.aws app.config['FLASKS3_BUCKET_NAME'] = cfg.S3_BUCKET app.config['FLASKS3_BUCKET_DOMAIN'] = cfg.S3_BUCKET_DOMAIN # app.config['AWS_ACCESS_KEY_ID'] = cfg.S3_ACCESS_KEY # app.config['AWS_SECRET_ACCESS_KEY'] = cfg.S3_SECRET_KEY s3 = FlaskS3(app) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 app.jinja_env.line_statement_prefix = '#' # enables jinja2 line mode app.jinja_env.line_comment_prefix = '##' # enables jinja2 line mode app.secret_key = 'Bd\xf2\x14\xbbi\x01Gq\xc6\x87\x10BVc\x9c\xa4\x08\xdbk%\xfa*\xe3' # os.urandom(24) # makes our config available to all jinja templates app.add_template_global(cfg, 'cfg') # @app.before_first_request # def load_tables(): # """ collects all the metadata as soon as the app boots up # well, only acts when the first request comes in but whatever""" # db._fetch_metadata(database) @app.before_request def assign_session_params(): """ Makes sure the user has basic needs satisfied password: password to sign off posts with myposts: list of pids posted by the user update-myposts: at min once every two days, replace myposts with a list of postids that still exist in the db. """
def app_factory(**kwargs): app = Flask(__name__) app.config.from_object(config_combined) db.init_app(app) DebugToolbarExtension(app) app.add_template_global(string_isinstance, name='string_isinstance') login_manager = LoginManager(app) @login_manager.user_loader def load_user(user_id): return User() @app.route('/') def index(): return render_template('index.html') @app.route('/login/', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if form.validate_on_submit(): if (form.username.data == app.config['ADMIN_USERNAME'] and form.password.data == app.config['ADMIN_PASSWORD']): user = User() login_user(user) return redirect(url_for('index')) else: form.username.errors.append('Invalid Username...') form.password.errors.append('...or Password') return render_template('login.html', form=form) @app.route('/logout/') def logout(): logout_user() return redirect(url_for('login')) @app.route('/content/') @login_required def content(): return render_template('content.html') @app.errorhandler(404) def err404(e): return render_template('404.html'), 404 @app.errorhandler(500) def err500(e): return render_template('500.html'), 500 @app.route('/all-tables/') def all_tables(): class TableTable(HTMLTable): name = LinkCol('Name', 'data_bp.view', attr='name', url_kwargs=dict(table='name')) add_col = LinkCol('Add Col', 'table_bp.add_col', url_kwargs=dict(table='name')) t = TableTable(get_all_tables(app.config['SQLALCHEMY_DATABASE_URI'])) return render_template('all_tables.html', t=t) # use: http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html ## db manipulations @app.route('/create/') def create(): from .data_types import str_data_factory from .sql import create col_options = [('name', 'string'), ('date', 'date'), ('description', 'string')] cols = [(name, str_data_factory(t)) for name, t in col_options] name = 'test2' sql = create(name, cols) run_sql(sql, app.config['SQLALCHEMY_DATABASE_URI']) return redirect(url_for('all_tables')) @app.route('/delete/') def delete(): run_sql( 'DROP TABLE %s;', app.config['SQLALCHEMY_DATABASE_URI'], ('test',)) return redirect(url_for('all_tables')) from .data_bp import bp_factory as data_bp_factory app.register_blueprint(data_bp_factory(), url_prefix='/data') from .table_bp import bp_factory as table_bp_factory app.register_blueprint(table_bp_factory(), url_prefix='/table') return app
app.wsgi_app = SassMiddleware(app.wsgi_app, { 'soran.web': ('static/sass', 'static/css', '/static/css') }) def import_python(module_name: str): modules = module_name.split(':') if len(modules) != 2: return None try: return getattr(__import__(modules[0]), modules[1]) except (ImportError, AttributeError): return None app.add_template_global(import_python, 'import_python') app.add_template_global(isinstance, 'isinstance') app.url_map.converters.update( youtube=YoutubeConverter ) app.register_blueprint(user.bp) app.register_blueprint(youtube.bp) @app.route('/', methods=['GET']) def hello(): """메인 핸들러
def create_app(config=None, **kwargs): """Create the WSGI application that is this app. In addition to the arguments documented below, this function accepts as a keyword agument all agruments to :py:class:`flask.Flask` except `import_name`, which is set to 'evesrp'. Additionally, the value of `instance_relative_config` has a default value of `True`. If the `config` argument isn't specified, the app will attempt to use the file 'config.py' in the instance folder if it exists, and will then fall back to using the value of the EVESRP_SETTINGS environment variable as a path to a config file. :param config: The app configuration file. Can be a Python :py:class:`dict`, a path to a configuration file, or an importable module name containing the configuration. :type config: str, dict """ # Default instance_relative_config to True to let the config fallback work kwargs.setdefault('instance_relative_config', True) app = Flask('evesrp', **kwargs) app.request_class = AcceptRequest app.config.from_object('evesrp.default_config') # Push the instance folder path onto sys.path to allow importing from there sys.path.insert(0, app.instance_path) # Check in config is a dict, python config file, or importable object name, # in that order. Finally, check the EVESRP_SETTINGS environment variable # as a last resort. if isinstance(config, dict): app.config.update(config) elif isinstance(config, six.string_types): if config.endswith(('.txt', '.py', '.cfg')): app.config.from_pyfile(config) else: app.config.from_object(config) elif config is None: try: app.config.from_pyfile('config.py') except OSError: app.config.from_envvar('EVESRP_SETTINGS') # Register SQLAlchemy monitoring before the DB is connected app.before_request(sqlalchemy_before) db.init_app(app) from .views.login import login_manager login_manager.init_app(app) before_csrf = list(app.before_request_funcs[None]) csrf.init_app(app) # Remove the context processor that checks CSRF values. All it is used for # is the template function. app.before_request_funcs[None] = before_csrf # Hook up OAuth oauth.init_app(app) # Connect views from .views import index, error_page, update_navbar, divisions, login,\ requests, api app.add_url_rule(rule=u'/', view_func=index) for error_code in (400, 403, 404, 500): app.register_error_handler(error_code, error_page) app.after_request(update_navbar) app.register_blueprint(divisions.blueprint, url_prefix='/division') app.register_blueprint(login.blueprint) app.register_blueprint(requests.blueprint, url_prefix='/request') app.register_blueprint(api.api, url_prefix='/api') app.register_blueprint(api.filters, url_prefix='/api/filter') from .views import request_count app.add_template_global(request_count) from .json import SRPEncoder app.json_encoder=SRPEncoder # Configure the Jinja context # Inject variables into the context from .auth import PermissionType @app.context_processor def inject_enums(): return { 'ActionType': models.ActionType, 'PermissionType': PermissionType, 'app_version': __version__, 'site_name': app.config['SRP_SITE_NAME'], 'url_for_page': requests.url_for_page, } # Auto-trim whitespace app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True init_app(app) return app
# Register modules app.register_blueprint(content_blueprint, url_prefix='/content') app.register_blueprint(contacts_blueprint, url_prefix='/contacts') app.register_blueprint(feed_blueprint, url_prefix='/feed') app.register_blueprint(posts_blueprint, url_prefix='/posts') app.register_blueprint(roster_blueprint, url_prefix='/roster') app.register_blueprint(tags_blueprint, url_prefix='/tags') app.register_blueprint(users_blueprint, url_prefix='/users') app.register_blueprint(diaspora_blueprint) # Diaspora has certain fixed URLs # Global template utility functions try: app.add_template_filter(templates.nl2br, name='nl2br') app.add_template_filter(templates.since, name='since') app.add_template_global( templates.chunk_url_params, name='chunk_url_params' ) except: app.jinja_env.filters['nl2br'] = templates.nl2br app.jinja_env.filters['since'] = templates.since app.jinja_env.globals['chunk_url_params'] = templates.chunk_url_params def init_db(): db.create_all() @app.route('/setup') def setup(): init_db() return "OK"
def jsonify(*args, **kwargs): response = flask_jsonify(*args, **kwargs) if not response.data.endswith(b'\n'): response.data += b'\n' return response # Prevent WSGI from correcting the casing of the Location header BaseResponse.autocorrect_location_header = False # Find the correct template folder when running from a different location tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) app.debug = bool(os.environ.get('DEBUG')) app.add_template_global('HTTPBIN_TRACKING' in os.environ, name='tracking_enabled') app.config['SWAGGER'] = { 'title': 'httpbin.org', 'uiversion': 3 } template = { "swagger": "2.0", "info": { "title": "httpbin.org", "description": ( "A simple HTTP Request & Response Service." "<br/> <br/> <b>Run locally: </b> <code>$ docker run -p 80:80 kennethreitz/httpbin</code>" ), "contact": {
def create_app(config={}): app = Flask(__name__, instance_relative_config=True) app.config.update(DEFAULT_CONFIG) app.config.from_pyfile('settings.py', silent=True) app.config.update(config) babel = Babel(app) @babel.localeselector def get_locale(): return getattr(g, 'language', 'en') assets_env.init_app(app) db.init_app(app) app.register_blueprint(admin) app.register_blueprint(auth) app.register_blueprint(meetings) app.add_template_filter(activity_map) app.add_template_filter(countries) app.add_template_filter(country_in) app.add_template_filter(region_in) app.add_template_filter(crop) app.add_template_filter(nl2br) app.add_template_filter(convert_to_dict, name='dict') app.add_template_filter(no_image_cache) app.add_template_filter(pluralize) app.add_template_filter(slugify) app.add_template_filter(sort_by_tuple_element) app.add_template_filter(clean_html) app.add_template_global(active) app.add_template_global(date_processor) app.add_template_global(inject_static_file) app.add_template_global(inject_badge_context) app.add_template_global(has_perm) app.add_template_global(Logo, name='get_logo') @app.context_processor def inject_context(): return { 'CustomField': { 'TEXT': CustomField.TEXT, 'IMAGE': CustomField.IMAGE, 'EMAIL': CustomField.EMAIL, 'CHECKBOX': CustomField.CHECKBOX, 'SELECT': CustomField.SELECT, 'COUNTRY': CustomField.COUNTRY, 'LANGUAGE': CustomField.LANGUAGE, 'CATEGORY': CustomField.CATEGORY, 'EVENT': CustomField.EVENT, }, 'Participant': { 'PARTICIPANT': Participant.PARTICIPANT, 'MEDIA': Participant.MEDIA, 'DEFAULT': Participant.DEFAULT, 'DEFAULT_MEDIA': Participant.DEFAULT_MEDIA, }, } login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'auth.login' login_manager.login_message_category = 'warning' mail.init_app(app) redis_store.init_app(app, strict=True) if app.config.get('SENTRY_DSN'): sentry.init_app(app) _configure_uploads(app) _configure_logging(app) app.config['REPRESENTING_TEMPLATES'] = ( path('meetings/participant/representing')) _translations = app.config['TRANSLATIONS'] if _DEFAULT_LANG not in _translations: _translations = [_DEFAULT_LANG] + _translations app.config['TRANSLATIONS'] = _translations @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) @app.route('/') def index(): return redirect(url_for('meetings.home')) @app.errorhandler(413) def file_too_large(error): mb = 1024 * 1024 max_size = app.config.get('UPLOAD_SIZE', mb) / mb return render_template('_file_too_large.html', max_size=max_size, url=request.url), 413 return app
import logging import os from flask import Flask, render_template from flask_upstatic import Upstatic logger = logging.getLogger('flask_upstatic') logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) if __name__ == '__main__': app = Flask(__name__) app.config.update( UPSTATIC_S3_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID'), UPSTATIC_S3_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY'), UPSTATIC_S3_BUCKET_NAME='flask_upstatic_example', ) upstatic = Upstatic(app) upstatic.upload() app.add_template_global(upstatic.url_for) @app.route('/') def index(): return render_template('index.html') app.run(host='0.0.0.0')