def app(): app = Flask(__name__) app.jinja_loader = FunctionLoader(load_template) Obscurity(app) return app
def app(): """Flask application fixture.""" app = Flask('testapp') app.config.update( TESTING=True, SEARCH_UI_SEARCH_API='api', BASE_TEMPLATE='invenio_search_ui/base.html', HEADER_TEMPLATE='invenio_search_ui/base_header.html', ) Babel(app) InvenioAssets(app) InvenioSearchUI(app) @app.route('/api') def api(): return {} app.register_blueprint(blueprint) # add extra test templates to the search app blueprint, to fake the # existence of `invenio-theme` base templates. test_templates_path = os.path.join(os.path.dirname(__file__), "templates") enhanced_jinja_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(test_templates_path), ]) # override default app jinja_loader to add the new path app.jinja_loader = enhanced_jinja_loader return app
def app_error_handler(request): """Flask app error handler fixture.""" app = Flask('myapp') # Creation of a fake theme error template file. temp_dir = tempfile.mkdtemp() invenio_theme_dir = os.path.join(temp_dir, 'invenio_theme') os.mkdir(invenio_theme_dir) fake_file = open(os.path.join(invenio_theme_dir, 'fake.html'), 'w+') fake_file.write("{# -*- coding: utf-8 -*- -#}" "<!DOCTYPE html>{% block message %}" "{% endblock message %}") fake_file.close() # Adding the temporal path to jinja engine. app.jinja_loader = jinja2.ChoiceLoader( [jinja2.FileSystemLoader(temp_dir), app.jinja_loader]) # Setting by default fake.html as a THEME_ERROR_TEMPLATE app.config['THEME_ERROR_TEMPLATE'] = 'invenio_theme/fake.html' # Tear down method to clean the temp directory. def tear_down(): shutil.rmtree(temp_dir) request.addfinalizer(tear_down) app.testing = True Babel(app) InvenioTheme(app) return app
def makeApp(rootpath, configFileName='webgenerator.yaml'): # If configFileName is unusable for any reason we want this to fail # the point of this method is to bootstrap app from configFile with open(os.path.join(rootpath, configFileName), 'r') as configFile: config = yaml.load(configFile) app = Flask(__name__) # Todo, this should be possible as a list, so we could include # external templates as well if 'template_folder' in config: # load templates first from the directory defined by the repository, then # by the default loader i.e. from the app. jinja2_loader = jinja2.ChoiceLoader([ # first local jinja2.FileSystemLoader(os.path.join(rootpath, config['template_folder'])), # then the default app.jinja_loader ]) app.jinja_loader = jinja2_loader app.config['rootpath'] = rootpath targets = buildRoutes(app, config) timezone = pytz.timezone(config.get('timezone', 'UTC')) app.config['fileDataCache'] = FileDataCache( tz=timezone ) menu = Menu(app, targets) app.config['menu'] = menu app.config['generator_config'] = config return app, menu
def create_app(config_name): app = Flask(__name__, static_folder='../static/dist/static') CORS(app) app.config.from_object(config[config_name]) config[config_name].init_app(app) template_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('./static/dist'), ]) app.jinja_loader = template_loader jwt = JWTManager(app) db.init_app(app) if app.config['SSL_REDIRECT']: from flask_sslify import SSLify sslify = SSLify(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api/v1') return app
def get_flask_app(template_folder: str) -> Flask: app = Flask('T-Quiz Bot', template_folder=template_folder) app.secret_key = 'quizbot cool secret key' template_loader = jinja2.FileSystemLoader([template_folder]) app.jinja_loader = jinja2.ChoiceLoader([app.jinja_loader, template_loader]) # type: ignore return app
def create_app(package_name='ticketting_system'): """Returns a :class:`Flask` application instance configured with common functionality for the korath platform. :param package_name: application package name :param package_path: application package path :param config_name: can have one of [production, development, testing] """ global app, admin app = Flask(package_name, instance_relative_config=True) config_name = os.environ.get('ticketting_system_CONFIG_NAME', 'Production') app.config.from_object('configurations.%s'%config_name.title()) app.jinja_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('ticketting_system/templates/'), ]) db.init_app(app) admin = Admin(app, 'Ticketing System Admin Panel') from . import views from views import api_blueprint app.register_blueprint(api_blueprint) from . import models # for admin panel from . import admin_panel return app
def create_app(templates_folders_list=templates_folders, modules=modules_list): application = Flask(__name__) blueprint = Blueprint('api', __name__, url_prefix='/api') api.init_app(blueprint) configure_api_route(api) configure_web_route(application) application.config['SECRET_KEY'] = EnvironmentConfig.SECRET_KEY application.config['TESTING'] = True application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False application.config['SWAGGER_UI_DOC_EXPANSION'] = 'list' application.config['RESTPLUS_VALIDATE'] = True application.config['RESTPLUS_MASK_SWAGGER'] = False application.config['ERROR_404_HELP'] = False application.config.update( SQLALCHEMY_DATABASE_URI=EnvironmentConfig.DATABASE) custom_loader = jinja2.ChoiceLoader([ application.jinja_loader, jinja2.FileSystemLoader(templates_folders_list) ]) application.register_blueprint(blueprint) FlaskInjector(app=application, modules=modules) application.jinja_loader = custom_loader return application
def app_error_handler(request): """Flask app error handler fixture.""" app = Flask('myapp') # Creation of a fake theme error template file. temp_dir = tempfile.mkdtemp() invenio_theme_dir = os.path.join(temp_dir, 'invenio_theme') os.mkdir(invenio_theme_dir) fake_file = open(os.path.join(invenio_theme_dir, 'fake.html'), 'w+') fake_file.write("{# -*- coding: utf-8 -*- -#}" "<!DOCTYPE html>{% block message %}" "{% endblock message %}") fake_file.close() # Adding the temporal path to jinja engine. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(temp_dir), app.jinja_loader ]) # Setting by default fake.html as a THEME_ERROR_TEMPLATE app.config['THEME_ERROR_TEMPLATE'] = 'invenio_theme/fake.html' # Tear down method to clean the temp directory. def tear_down(): shutil.rmtree(temp_dir) request.addfinalizer(tear_down) app.testing = True Babel(app) InvenioI18N(app) InvenioTheme(app) return app
def create_app(templates_folders_list=templates_folders, modules=modules_list): application = Flask(__name__) register_extensions(application) application.config['SECRET_KEY'] = EnvironmentConfig.SECRET_KEY cors = CORS(application) application.config['CORS_HEADERS'] = 'Content-Type' application.config['TESTING'] = False application.config['MAIL_SERVER'] = EnvironmentConfig.MAIL_SERVER application.config['MAIL_PORT'] = EnvironmentConfig.MAIL_PORT application.config['MAIL_USE_TLS'] = EnvironmentConfig.MAIL_USE_TLS application.config['MAIL_USE_SSL'] = EnvironmentConfig.MAIL_USE_SSL application.config['MAIL_USERNAME'] = EnvironmentConfig.MAIL_USERNAME application.config['MAIL_PASSWORD'] = EnvironmentConfig.MAIL_PASSWORD application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False application.config.update( SQLALCHEMY_DATABASE_URI=EnvironmentConfig.DATABASE) for routing in ROUTING_MODULES: routing(application) custom_loader = jinja2.ChoiceLoader([ application.jinja_loader, jinja2.FileSystemLoader(templates_folders_list) ]) FlaskInjector(app=application, modules=modules) application.jinja_loader = custom_loader return application
def subdomain(directory): app = Flask(__name__, static_folder=directory + "/static") set_secret_key(app) loader = [app.jinja_loader, jinja2.FileSystemLoader(directory + "/templates")] app.jinja_loader = jinja2.ChoiceLoader(loader) app.wsgi_app = ProxyFix(app.wsgi_app) return app
def create_app(interface_app=False): if not interface_app: connexion_app = _app = connexion.App(__name__, specification_dir='../api/', options={'swagger_ui': False}) _app = connexion_app.app else: _app = Flask(__name__) _app.jinja_loader = FileSystemLoader(['walkoff/templates']) _app.config.from_object(walkoff.config.Config) try: db.init_app(_app) except Exception as e: logger.error( "Error initializing walkoff database. Please make sure all settings are properly configured in the" "config file, and that all necessary environment variables are set correctly." "Error message: {}".format(str(e))) os._exit(1) if not interface_app: jwt.init_app(_app) connexion_app.add_api('composed_api.yaml') _app.running_context = context.Context() register_blueprints(_app, walkoff.config.Config.SEPARATE_INTERFACES) register_swagger_blueprint(_app) else: _app.running_context = context.Context(executor=False) __register_all_app_blueprints(_app) add_health_check(_app) return _app
def app_error_handler(request): """Flask app error handler fixture.""" app = Flask("myapp") # Creation of a fake theme error template file. temp_dir = make_fake_template("{# -*- coding: utf-8 -*- -#}" "<!DOCTYPE html>{% block message %}" "{% endblock message %}") # Adding the temporal path to jinja engine. app.jinja_loader = jinja2.ChoiceLoader( [jinja2.FileSystemLoader(temp_dir), app.jinja_loader]) # Setting by default fake.html as a THEME_ERROR_TEMPLATE app.config["THEME_ERROR_TEMPLATE"] = "invenio_theme/fake.html" # Tear down method to clean the temp directory. def tear_down(): shutil.rmtree(temp_dir) request.addfinalizer(tear_down) app.testing = True Babel(app) InvenioI18N(app) InvenioTheme(app) return app
def create_app(config_name): # Register app and config app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) braintree.Configuration.configure(app.config['BT_ENVIRONMENT'], app.config['BT_MERCHANT_ID'], app.config['BT_PUBLIC_KEY'], app.config['BT_PRIVATE_KEY']) my_loader = jinja2.ChoiceLoader( [app.jinja_loader, jinja2.FileSystemLoader('app/static')]) app.jinja_loader = my_loader db.init_app(app) loginmanager.init_app(app) mail.init_app(app) # Register Blueprint 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 before_request_global import before_request_global as global_blueprint app.register_blueprint(global_blueprint) from payment import payment as payment_blueprint app.register_blueprint(payment_blueprint) return app
def create_app(): """ Flask application factory. """ app = Flask(__name__) app.config.update( SECRET_KEY=config.ODP.UI.DAP.FLASK_KEY, SESSION_COOKIE_SECURE=True, SESSION_COOKIE_SAMESITE='Lax', CLIENT_ID=config.ODP.UI.DAP.CLIENT_ID, CLIENT_SECRET=config.ODP.UI.DAP.CLIENT_SECRET, CLIENT_SCOPE=[HydraScope.OPENID, HydraScope.OFFLINE_ACCESS], ) ui_dir = Path(__file__).parent.parent app.jinja_loader = ChoiceLoader([ FileSystemLoader(ui_dir / 'dap' / 'templates'), FileSystemLoader(ui_dir / 'templates'), ]) app.static_folder = ui_dir / 'static' db.init_app(app) auth.init_app(app) views.init_app(app) # trust the X-Forwarded-* headers set by the proxy server app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_prefix=1) return app
def create_app(): app = Flask(__name__) Bootstrap(app) my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('./effect/templates'), jinja2.FileSystemLoader('./auth/templates'), jinja2.FileSystemLoader('./album/templates') ]) app.jinja_loader = my_loader app.config['BOOTSTRAP_SERVE_LOCAL'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@localhost/ierg4080' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['CACHE'] = 'redis://localhost' app.secret_key = 'super secret key' app.config.update( CELERY_BROKER_URL='amqp://guest@localhost//', CELERY_RESULT_BACKEND='redis://localhost', CELERY_BACKEND='redis://localhost' ) CsrfProtect(app) app.config['UPLOAD_FOLDER'] = '/tmp/images' app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg']) return app
def create_app(): """ Creates the Flask app instance @return: Flask app @rtype: flask.Flask """ from flask import Flask app = Flask(__name__) # set debug to true so we see error dumps in the browser app.debug = settings.APP_DEBUG app.secret_key = settings.APP_SECRET_KEY app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE[env]['uri'] app.config['BASE_URL'] = settings.BASE_URL app.config['SQLALCHEMY_ECHO'] = settings.DATABASE[env]['echo'] app.config['RECAPTCHA_PUBLIC_KEY'] = settings.RECAPTCHA_PUBLIC_KEY app.config['RECAPTCHA_PRIVATE_KEY'] = settings.RECAPTCHA_PRIVATE_KEY app.config['SERVER_NAME'] = settings.BASE_URL app.jinja_options['extensions'].append('jinja2.ext.loopcontrols') my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader([os.path.dirname(os.path.abspath(__file__)) + '/static']), ]) app.jinja_loader = my_loader return app
def app_frontpage_handler(request): """Flask app error handler fixture.""" app = Flask('myapp') # Creation of a fake theme error template file. temp_dir = make_fake_template( "{% extends 'invenio_theme/page.html' %}" "{% block css %}{% endblock %}" "{% block javascript %}{% endblock %}" ) # Adding the temporal path to jinja engine. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(temp_dir), app.jinja_loader ]) # Setting by default fake.html as a BASE_TEMPLATE app.config['BASE_TEMPLATE'] = 'invenio_theme/fake.html' app.config['THEME_FRONTPAGE'] = True # Tear down method to clean the temp directory. def tear_down(): shutil.rmtree(temp_dir) request.addfinalizer(tear_down) app.testing = True Babel(app) InvenioI18N(app) InvenioTheme(app) InvenioAssets(app) return app
def create_app(config='CTFd.config'): app = Flask(__name__) with app.app_context(): app.config.from_object(config) app.jinja_loader = ThemeLoader(os.path.join(app.root_path, app.template_folder), followlinks=True) from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking url = make_url(app.config['SQLALCHEMY_DATABASE_URI']) if url.drivername == 'postgres': url.drivername = 'postgresql' db.init_app(app) try: if not (url.drivername.startswith('sqlite') or database_exists(url)): create_database(url) db.create_all() except OperationalError: db.create_all() except ProgrammingError: ## Database already exists pass else: db.create_all() app.db = db cache.init_app(app) app.cache = cache if not get_config('ctf_theme'): set_config('ctf_theme', 'original') #Session(app) from CTFd.views import views from CTFd.challenges import challenges from CTFd.scoreboard import scoreboard from CTFd.auth import auth from CTFd.admin import admin from CTFd.utils import init_utils, init_errors, init_logs init_utils(app) init_errors(app) init_logs(app) app.register_blueprint(views) app.register_blueprint(challenges) app.register_blueprint(scoreboard) app.register_blueprint(auth) app.register_blueprint(admin) from CTFd.plugins import init_plugins init_plugins(app) return app
def make_app(self): app = Flask('clay', static_folder=None, template_folder=self.source_dir) app.jinja_loader = self.get_jinja_loader() app.jinja_options = self.get_jinja_options() app.debug = True self.set_template_context_processors(app) self.set_urls(app) return app
def create_app(): """Create the Flask app.""" app = Flask("modelconvert", static_folder=None) app.config.from_object('modelconvert.settings') app.config.from_envvar('MODELCONVERT_SETTINGS', silent=True) # configure custom static path for serving files during # development app.static_folder = app.config['STATIC_PATH'] app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=app.send_static_file) # custom template path, fall back to default jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']), app.jinja_loader, ]) app.jinja_loader = jinja_loader configure_logging(app) app.register_blueprint(frontend) app.register_blueprint(api, url_prefix='/api') celery.add_defaults(app.config) # configure error handlers @app.errorhandler(403) def forbidden_page(error): return render_template("403.html"), 403 # FIXME adapt this for json requests http://flask.pocoo.org/snippets/83/ @app.errorhandler(404) def page_not_found(error): if request.headers['Content-Type'] == 'application/json': message = { 'status': 404, 'detail': 'Not Found: ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp else: return render_template("404.html"), 404 @app.errorhandler(500) def server_error_page(error): return render_template("500.html"), 500 if app.config['DEBUG']: from werkzeug.wsgi import SharedDataMiddleware app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/preview': app.config["DOWNLOAD_PATH"]}) return app
def init_flaskadmin(urlprefix="",secret="fKY7kJ2xSrbPC5yieEjV",override_admin=None,override_flaskadminapp=None): global flaskadminapp, admin if not override_flaskadminapp: flaskadminapp = Flask(__name__) flaskadminapp.debug=True flaskadminapp.secret_key = secret flaskadminapp.config.update(dict( PREFERRED_URL_SCHEME = 'https' )) else: flaskadminapp = override_flaskadminapp # lets add our template directory my_loader = jinja2.ChoiceLoader([ flaskadminapp.jinja_loader, jinja2.FileSystemLoader(resole_uri("gengine:templates")), ]) flaskadminapp.jinja_loader = my_loader flaskadminapp.add_url_rule('/static_gengine/<path:filename>', endpoint='static_gengine', view_func=get_static_view('gengine:flask_static',flaskadminapp)) @flaskadminapp.context_processor def inject_version(): return { "gamification_engine_version" : pkg_resources.get_distribution("gamification-engine").version } if not override_admin: admin = Admin(flaskadminapp, name="Gamification Engine - Admin Control Panel", base_template='admin_layout.html', url=urlprefix+"/admin" ) else: admin = override_admin admin.add_view(ModelViewAchievement(DBSession, category="Rules")) admin.add_view(ModelViewGoal(DBSession, category="Rules")) admin.add_view(ModelView(AchievementAchievementProperty, DBSession, category="Rules", name="Achievement Property Values")) admin.add_view(ModelView(AchievementReward, DBSession, category="Rules", name="Achievement Reward Values")) admin.add_view(ModelView(GoalGoalProperty, DBSession, category="Rules", name="Goal Property Values")) admin.add_view(ModelViewTranslationVariable(DBSession, category="Rules")) admin.add_view(ModelView(Translation,DBSession, category="Rules")) admin.add_view(ModelViewAchievementCategory(DBSession, category="Settings")) admin.add_view(ModelViewVariable(DBSession, category="Settings")) admin.add_view(ModelViewAchievementProperty(DBSession, category="Settings", name="Achievement Property Types")) admin.add_view(ModelViewReward(DBSession, category="Settings", name="Achievement Reward Types")) admin.add_view(ModelViewGoalProperty(DBSession, category="Settings", name="Goal Property Types")) admin.add_view(ModelView(Language, DBSession, category="Settings")) admin.add_view(MaintenanceView(name="Maintenance", category="Settings", url="maintenance")) admin.add_view(ModelViewValue(DBSession, category="Debug")) admin.add_view(ModelViewGoalEvaluationCache(DBSession, category="Debug")) admin.add_view(ModelViewUser(DBSession, category="Debug")) admin.add_view(ModelView(AchievementUser, DBSession, category="Debug"))
def create_app(conf): """ A factory function for creating Flask apps given a configuration dictionary. The factory will initialise all Flask plugins, as well as change the template directory and load all blueprints. The factory function also sets up logging and adds the `wiki` variable to the template globals. """ app = Flask(__name__) app.config.update(conf) # Tell flask to get all templates from our template dir my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(conf['TEMPLATE_DIR']), ]) app.jinja_loader = my_loader bootstrap.init_app(app) mail.init_app(app) db.init_app(app) login_manager.init_app(app) # Attach routes and custom error pages 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 .pages import pages as pages_blueprint app.register_blueprint(pages_blueprint, url_prefix='/pages') import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler( app.config.get('LOG_FILE'), maxBytes=1024 * 1024 * 100, backupCount=20) file_handler.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s: %(message)s", datefmt='%Y/%m/%d %I:%M:%S %p') file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # Catch the requests behind the scenes from werkzeug logger = logging.getLogger('werkzeug') logger.addHandler(file_handler) # Inject the app metadata into all our templates app.jinja_env.globals['wiki'] = conf['METADATA'] return app
def _create_app(self): app = Flask(__name__) app.debug = self.conf.FLASK_DEBUG if not self.conf.STATIC_RESOURCE: raise Exception('STATIC_RESOURCE setting not configured.') if not self.conf.TEMPLATE_RESOURCE: raise Exception('TEMPLATE_RESOURCE setting not configured.') app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/': self.conf.STATIC_RESOURCE }) if type(self.conf.TEMPLATE_RESOURCE) == tuple: # package, not filepath app.jinja_loader = PackageLoader(*self.conf.TEMPLATE_RESOURCE) else: app.jinja_loader = FileSystemLoader(self.conf.TEMPLATE_RESOURCE) if self.conf.ALLOW_DEFERREDS: self._enable_deferreds(app) return app
def get_app(module_name): """ if more than one loaders are required, use this: loader_config = [ app.jinja_loader, jinja2.FileSystemLoader('/home/chenyu/project/pinche/'), ] my_loader = jinja2.ChoiceLoader(loader_config) """ app = Flask(__name__) app.jinja_loader = my_loader return app
def get_flask_app(template_folder: str) -> Flask: app = Flask("admin", template_folder=template_folder) app.secret_key = "overhave cool secret key" app.config.update({ "FLASK_ADMIN_SWATCH": "united", "FLASK_ADMIN_FLUID_LAYOUT": True }) login_template_loader = jinja2.FileSystemLoader([template_folder]) app.jinja_loader = jinja2.ChoiceLoader( [app.jinja_loader, login_template_loader]) return app
def create_app(config='settings'): app = Flask(__name__) with app.app_context(): app.config.from_object(config) app.jinja_loader = ThemeLoader(os.path.join(app.root_path, app.template_folder), followlinks=True) app.debug = app.config['DEBUG'] app.secret_key = app.config['SECRET_KEY'] from qa_app.models import db # sqlite database creation is relative to the script which causes issues with serve.py if not database_exists(app.config['SQLALCHEMY_DATABASE_URI']) and not \ app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'): create_database(app.config['SQLALCHEMY_DATABASE_URI']) db.init_app(app) db.create_all() app.db = db oauth = OAuth() global google, lm lm.init_app(app) lm.login_view = 'auth.login' google = oauth.remote_app('google', base_url='https://www.google.com/accounts/', authorize_url='https://accounts.google.com/o/oauth2/auth', request_token_url=None, request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email', 'response_type': 'code'}, access_token_url='https://accounts.google.com/o/oauth2/token', access_token_method='POST', access_token_params={'grant_type': 'authorization_code'}, consumer_key=app.config['GOOGLE_CLIENT_ID'], consumer_secret=app.config['GOOGLE_CLIENT_SECRET']) from qa_app import utils from qa_app import exceptions from qa_app.views import views from qa_app.auth import auth from qa_app.scoreboard import scoreboard from qa_app.challenges import challenges utils.init_utils(app) app.register_blueprint(views) app.register_blueprint(auth) app.register_blueprint(scoreboard) app.register_blueprint(challenges) return app
def create_app(): """Create the Flask app.""" app = Flask("modelconvert", static_folder=None) app.config.from_object('modelconvert.settings') app.config.from_envvar('MODELCONVERT_SETTINGS', silent=True) # configure custom static path for serving files during # development app.static_folder = app.config['STATIC_PATH'] app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=app.send_static_file) # custom template path, fall back to default jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']), app.jinja_loader, ]) app.jinja_loader = jinja_loader configure_logging(app) app.register_blueprint(frontend) app.register_blueprint(api, url_prefix='/api') celery.add_defaults(app.config) # configure error handlers @app.errorhandler(403) def forbidden_page(error): return render_template("403.html"), 403 @app.errorhandler(404) def page_not_found(error): return render_template("404.html"), 404 @app.errorhandler(500) def server_error_page(error): return render_template("500.html"), 500 if app.config['DEBUG']: from werkzeug.wsgi import SharedDataMiddleware app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/preview': app.config["DOWNLOAD_PATH"] }) return app
def create_app(config_name): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('../config.py') db.init_app(app) login_manager.init_app(app) login_manager.login_message = "Logeo necesario." login_manager.login_view = "auth.login" # setup templates config my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader([ '%s/flaskps/app/administration/templates/' % BASE_DIR, '%s/flaskps/app/auth/templates/' % BASE_DIR, '%s/flaskps/app/configurations/templates/' % BASE_DIR, '%s/flaskps/app/students/templates/' % BASE_DIR, '%s/flaskps/app/home/templates/' % BASE_DIR, '%s/flaskps/app/users/templates/' % BASE_DIR, '%s/flaskps/app/teachers/templates/' % BASE_DIR, '%s/flaskps/app/instruments/templates/' % BASE_DIR, ]), ]) app.jinja_loader = my_loader from flaskps.app.students import students as students_blueprint app.register_blueprint(students_blueprint) from flaskps.app.configurations import configurations as configurations_blueprint app.register_blueprint(configurations_blueprint) from flaskps.app.teachers import teachers as teachers_blueprint app.register_blueprint(teachers_blueprint) from flaskps.app.home import home as home_blueprint app.register_blueprint(home_blueprint) from flaskps.app.users import users as users_blueprint app.register_blueprint(users_blueprint) from flaskps.app.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .app.instruments import instruments as instruments_blueprint app.register_blueprint(instruments_blueprint) from flaskps.app.administration import administration as administration_blueprint app.register_blueprint(administration_blueprint) return app
def create_app(config='app.config.Config'): app = Flask(__name__) with app.app_context(): app.config.from_object(config) theme_loader = ThemeLoader(os.path.join(app.root_path, 'html'), followlinks=True) app.jinja_loader = theme_loader init_utils(app) app.register_blueprint(views) app.register_blueprint(api) return app
def create_app(object_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: object_name: the python path of the config object, e.g. appname.settings.ProdConfig """ app = Flask(__name__) app.config.from_object(object_name) if os.environ.get('KAKU_SETTINGS', None) is not None: app.config.from_envvar('KAKU_SETTINGS') if not app.debug: handler = logging.handlers.RotatingFileHandler(app.config['LOG_FILE'], maxBytes=100000000, backupCount=9) formatter = logging.Formatter( '%(asctime)s %(levelname)s %(pathname)s:%(lineno)d -- %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) app.logger.setLevel(logging.DEBUG) wzlog = logging.getLogger('werkzeug') wzlog.setLevel(logging.DEBUG) wzlog.addHandler(handler) if app.config['SITE_TEMPLATES'] is not None: app.jinja_loader = jinja2.FileSystemLoader( app.config['SITE_TEMPLATES']) # initialize the cache cache.init_app(app) # initialize the debug tool bar debug_toolbar.init_app(app) app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app) # register our blueprints app.register_blueprint(main) app.register_blueprint(auth) app.logger.info('Flask app [%s] created' % __name__) return app
def create_app(config=None): """ 工厂方法创建配置app实例 :param config: 配置是文件或者config 对象 :return: """ app = Flask('unp') # 指定jinjia2 template目录位置 tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app.jinja_loader = jinja2.FileSystemLoader(tmpl_dir) configure_app(app, config) configure_blueprints(app) configure_extensions(app) configure_errorhandlers(app) return app
def create_app(): # Create the app app = Flask(__name__, static_url_path='/static') # Import config after the dotenv from .config import Config app.config.from_object(Config) lm.init_app(app) # This view will be the one which users will be returned to when they try to access a protected route lm.login_view = 'auth.login' lm.login_message = u'你沒有權限進入這個頁面' from .main import main from .auth import auth from .announcements import announcements from .columns import columns from .errors import errors # register blueprint app.register_blueprint(main) app.register_blueprint(auth) app.register_blueprint(announcements) app.register_blueprint(errors) app.register_blueprint(columns) my_loader = jinja2.ChoiceLoader([ app.jinja_loader, # Load templates from app/template, so all html files can use relative path to refet to each other jinja2.FileSystemLoader(['/app/template/']), ]) app.jinja_loader = my_loader def concat_lists(a, b): return [*a, *b] # Add customed filters by adding our functions to DEFAULT_FILTERS object jinja2.environment.DEFAULT_FILTERS['concat_lists'] = concat_lists # Import static assets from .assets import create_assets create_assets(app) # Enable gzip by using flask-compress Compress(app) return app
def webapp(templates): ''' Create a WSGI Flask app ''' app = Flask("Adata") app.secret_key = os.urandom(24) #Set custom templates folder loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader([templates]), app.jinja_loader, ]) app.jinja_loader = loader @app.route('/') def index(): echo("Request index") name = escape(session['username']) if 'username' in session else "?" return render_template('index.html', name=name) @app.route('/remote') @app.route('/remote/<name>') def remote(name=None): echo("Request remote") title = "Adata remote" return render_template('remote.html', title=title) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) return app
def create_app(config_filename='application.config_dev'): # Definition of app app = Flask(__name__, static_url_path="/static", static_folder=str(Path(__file__).parent.parent) + "/static") app.register_blueprint(bp) app.register_blueprint(oauth_bp) app.register_blueprint(db_bp) app.config.from_object(config_filename) #db = SQLAlchemy(app) temp_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(['templates']), ]) app.jinja_loader = temp_loader # Error handlers @app.errorhandler(werkzeug.exceptions.InternalServerError) def internal_error(error): #db_session.rollback() return render_template('errors/500.html', previous=session["previous"]), 500 @app.errorhandler(werkzeug.exceptions.NotFound) def not_found_error(error): return render_template('errors/404.html', previous=session["previous"]), 404 # logger if not app.debug: file_handler = FileHandler('error.log') file_handler.setFormatter( Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('errors') return app
def serve(py_exec=None): log_set_up(DEBUG) parser = argparse.ArgumentParser() parser.add_argument("--python", default="python2") args = parser.parse_args() py_exec = args.python app = Flask("touchandgo") template_path = join(dirname(__file__), "templates") app.jinja_loader = FileSystemLoader(template_path) def get_torrent(name, season=None, episode=None): interface = get_interface() settings = get_settings() path = abspath(__file__) dir_path = dirname(path) exec_ = join(dir_path, "..", "main.py") command = '%s %s \"%s\" ' % (py_exec, exec_, name) if season is not None: command += "%s %s " % (season, episode) lock = Lock(LOCK_FILE) if lock.is_same_file(name, season, episode) and \ is_process_running(lock.get_pid()): data = lock._get_file_data() port = data[4] else: if settings.force_ts_proxy_port: port = settings.ts_proxy_port else: port = get_free_port() command += "--daemon --port %s " % port log.info(command) process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT) sleep(1) redirect_url = "http://%s:%s" % (interface, port) serving = False while not serving: try: req = requests.get("%s/status" % redirect_url) serving = True except requests.ConnectionError, e: sleep(1) log.info("redirecting to %s" % redirect_url) return redirect(redirect_url)
def create_app(object_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: object_name: the python path of the config object, e.g. appname.settings.ProdConfig """ app = Flask(__name__) app.config.from_object(object_name) if os.environ.get('KAKU_SETTINGS', None) is not None: app.config.from_envvar('KAKU_SETTINGS') if not app.debug: handler = logging.handlers.RotatingFileHandler(app.config['LOG_FILE'], maxBytes=100000000, backupCount=9) formatter = logging.Formatter('%(asctime)s %(levelname)s %(pathname)s:%(lineno)d -- %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) app.logger.setLevel(logging.DEBUG) wzlog = logging.getLogger('werkzeug') wzlog.setLevel(logging.DEBUG) wzlog.addHandler(handler) if app.config['SITE_TEMPLATES'] is not None: app.jinja_loader = jinja2.FileSystemLoader(app.config['SITE_TEMPLATES']) # initialize the cache cache.init_app(app) # initialize the debug tool bar debug_toolbar.init_app(app) app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app) # register our blueprints app.register_blueprint(main) app.register_blueprint(auth) app.logger.info('Flask app [%s] created' % __name__) return app
def __init__(self, server, debug=False, address='127.0.0.1', port=3855, enabled=True, **kwargs): """ Handles implementing default configurations """ logger = server.register_logger('monitor') wsgi_logger = server.register_logger('monitor_wsgi') if not enabled: logger.info("HTTP monitor not enabled, not starting up...") return else: logger.info("HTTP monitor enabled, starting up...") app = Flask('monitor') app = Flask('monitor', static_folder='../static', static_url_path='/static') # set our template path and configs app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates')) app.config.update(kwargs) app.config['DEBUG'] = debug app.register_blueprint(main) # Monkey patch the wsgi logger Logger.logger = wsgi_logger app.real_logger = logger @app.template_filter('duration') def time_format(seconds): # microseconds if seconds > 3600: return "{}".format(timedelta(seconds=seconds)) if seconds > 60: return "{:,.2f} mins".format(seconds / 60.0) if seconds <= 1.0e-3: return "{:,.4f} us".format(seconds * 1000000.0) if seconds <= 1.0: return "{:,.4f} ms".format(seconds * 1000.0) return "{:,.4f} sec".format(seconds) # setup localproxy refs app.server = server WSGIServer.__init__(self, (address, port), app, log=Logger()) @app.template_filter('datetime') def jinja_format_datetime(value, fmt='medium'): if fmt == 'full': fmt = "EEEE, MMMM d y 'at' HH:mm" elif fmt == 'medium': fmt = "EE MM/dd/y HH:mm" return value.strftime(fmt)
def create_app(): app = Flask(__name__) app.jinja_loader = jinja2.FileSystemLoader('/flask/rest/resources') app.config['JSON_AS_ASCII'] = False app.json_encoder = ISODateJSONEncoder app.scheduler = BackgroundScheduler() config = Config() setup_resources(app) setup_db(config) setup_bridge_dao(app, config) setup_kafka(config) CORS(app) app.scheduler.start() atexit.register(lambda: app.scheduler.shutdown()) return app
def create_app(): application = Flask(__name__, static_folder=EG_STATIC_FOLDER) my_loader = jinja2.ChoiceLoader([application.jinja_loader, jinja2.FileSystemLoader(EG_SYSTEM_TEMPLATE_FOLDER)]) application.jinja_loader = my_loader application.secret_key = APP_SECRET_KEY application.config.from_object('config') application.jinja_env.filters['date'] = datetime_filter # Initialize Babel Babel(application) application.config['BABEL_DEFAULT_LOCALE'] = BABEL_DEFAULT_LOCALE # Initialize database from therm.models import db db.init_app(application) return application
def serve(py_exec=None): log_set_up(True) parser = argparse.ArgumentParser() parser.add_argument("--python", default="python") args = parser.parse_args() py_exec = args.python app = Flask("touchandgo") template_path = join(dirname(__file__), "templates") app.jinja_loader = FileSystemLoader(template_path) def get_torrent(name, season=None, episode=None): interface = get_interface() path = abspath(__file__) dir_path = dirname(path) exec_ = join(dir_path, "__init__.py") command = '%s %s \"%s\" ' % (py_exec, exec_, name) if season is not None: command += "%s %s " % (season, episode) lock = Lock(LOCKFILE) if lock.is_same_file(name, season, episode) and \ is_process_running(lock.get_pid()): data = lock._get_file_data() port = data[4] else: port = get_free_port() command += "--daemon --port %s " % port log.debug(command) process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT) sleep(1) redirect_url = "http://%s:%s" % (interface, port) serving = False while not serving: try: req = requests.get("%s/status" % redirect_url) serving = True except requests.ConnectionError, e: sleep(1) log.info("redirecting to %s" % redirect_url) return redirect(redirect_url)
def init(cfg): from yaml import load as yaml_load from jinja2 import FileSystemLoader from os.path import join as path_join, exists from hicode import setting from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles if exists(cfg): users = yaml_load(file(cfg).read()) setting.update(users) setting['styles'] = list(get_all_styles()) setting['langs'] = dict(map(lambda x: (x[0], x[1]), get_all_lexers())) app = Flask('hicode') app.jinja_loader = FileSystemLoader(setting['template_directory']) app.debug = setting['debug'] return app
def create_app(config='QATrainingFrontend.config'): app = Flask(__name__) with app.app_context(): app.config.from_object(config) app.jinja_loader = ThemeLoader(os.path.join(app.root_path, app.template_folder), followlinks=True) from QATrainingFrontend.models import db, Users, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking ## sqlite database creation is relative to the script which causes issues with serve.py if not database_exists(app.config['SQLALCHEMY_DATABASE_URI']) and not app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'): create_database(app.config['SQLALCHEMY_DATABASE_URI']) db.init_app(app) db.create_all() app.db = db if not get_config('ctf_theme'): set_config('ctf_theme', 'original') #Session(app) from QATrainingFrontend.views import views from QATrainingFrontend.challenges import challenges from QATrainingFrontend.scoreboard import scoreboard from QATrainingFrontend.auth import auth from QATrainingFrontend.admin import admin from QATrainingFrontend.utils import init_utils, init_errors, init_logs init_utils(app) init_errors(app) init_logs(app) app.register_blueprint(views) app.register_blueprint(challenges) app.register_blueprint(scoreboard) app.register_blueprint(auth) app.register_blueprint(admin) return app
def app(self): """ derive flask app based on the combination of command-line options and the contents of the .ini files """ ## set flask specific things that are non-optional error = lambda k: 'Fatal: You need to specify a "flask" section ' + \ 'with an entry like "'+k+'=..." in your .ini file' try: app_name = self['flask.app'] except KeyError: raise SystemExit(error('app')) try: secret_key = self['flask.secret_key'] except KeyError: raise SystemExit(error('secret_key')) app = Flask(app_name) app.secret_key = secret_key ## set flask specific things that are optional if 'flask.template_path' in self: app.jinja_loader = FileSystemLoader(self['template_path']) if 'flask.before_request' in self: before_request = self['flask.before_request'] before_request = namedAny(before_request) app.before_request(before_request) if 'flask.after_request' in self: after_request = self['flask.after_request'] after_request = namedAny(after_request) app.after_request(after_request) ## setup views try: view_holder = self['corkscrew.views'] except KeyError: error = 'Fatal: could not "view=<dotpath>" entry in your .ini file' raise SystemExit(error) else: view_list = namedAny(view_holder) [ v(app=app, settings=self) for v in view_list] return app
def create_app(package_name='mordor', config_name='Development'): """Returns a :class:`Flask` application instance configured with common functionality for the mordor platform. :param package_name: application package name :param package_path: application package path :param config_name: can have one of [production, development, testing] """ app = Flask(package_name, instance_relative_config=True) if os.environ.get('mordor_CONFIG_NAME') == 'Production': config_name = 'Production' app.config.from_object('configurations.%s'%config_name.title()) app.jinja_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('mordor/templates/'), ]) db.init_app(app) rc.init_app(app) es.init_app(app) admin.init_app(app) rscripts.init_app(app, rc) from views import main as main_blueprint app.register_blueprint(main_blueprint) mail_handler = SMTPHandler((app.config['MAIL_SERVER'], app.config['MAIL_PORT']), '*****@*****.**', app.config['ADMINS'], '[mordor] phat gaya', (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']),(None, None)) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) return app
# Create Flask instance from flask import Flask app = Flask(__name__) # If frozen, we need define static and template paths if check_frozen(): app.root_path = rundir app.static_path = '/static' app.add_url_rule( app.static_path + '/<path:filename>', endpoint='static', view_func=app.send_static_file ) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(rundir, 'templates')) def import_modules(): """All modules that are available in Maraschino are at this point imported.""" import modules.applications import modules.controls import modules.couchpotato import modules.currently_playing import modules.diskspace import modules.headphones import modules.index import modules.library import modules.log import modules.nzbget import modules.recently_added
CORS(app, resources=r'/developmentcontrol/*', allowed_headers=['Content-Type', 'X-Requested-With']) # Configure logging to stderr log_handler = StreamHandler() log_handler.setLevel(logging.INFO) app.logger.addHandler(log_handler) # Add the to the template search path so that we can treat our built hubmap.js # as a template without having to manually copy it to the standard template # directory DIST_DIR = os.path.join(app.static_folder, 'hubmap/dist') template_loader = ChoiceLoader([ app.jinja_loader, FileSystemLoader([DIST_DIR]) ]) app.jinja_loader = template_loader # Expose additional functions in templates app.jinja_env.globals.update(url_unquote_plus=url_unquote_plus) if 'CONNECTION_STRING' in os.environ: app.config['CONNECTION_STRING'] = os.environ['CONNECTION_STRING'] def sql_in(s): return ', '.join(map(str, map(psycopg2.extensions.adapt, s))) def sql_date_range(val): token_to_days = {'last_7_days': 6, 'last_14_days': 13, 'last_30_days': 29, 'last_90_days': 89} val = datetime.now() - timedelta(days=token_to_days.get(val[0]))
# encoding: utf-8 from flask import Flask, render_template, jsonify, request from jinja2 import FileSystemLoader import os from utils.decorators import stacktraceable from utils.marshall import dumps from datetime import * ROOT_PATH = os.path.dirname(__file__) template_path = 'templates' app = Flask(__name__) app.jinja_loader = FileSystemLoader(os.path.join(ROOT_PATH, template_path)) # Base de datos import models # Test purposue from random import seed, randrange seed(os.getpid()) from utils.datatable import parseparams #-------------------------------------------------------------------- # Contex processors y cosas para los temapltes #-------------------------------------------------------------------- @app.context_processor def static_url(): return dict(STATIC_URL = '/static/') @app.context_processor
import os import jinja2 from flask import Flask from flask_sockets import Sockets CURRENT_DIRECTORY = os.path.dirname(__file__) STATIC_FOLDER = os.path.join("twidder", "static") MEDIA_FOLDER = os.path.join("twidder", "media") ALLOWED_MEDIA = {"jpg", "png", "mp4", "mp3", "wav"} app = Flask(__name__, static_url_path='', static_folder=STATIC_FOLDER) app.config["SECRET_KEY"] = os.urandom(24) app.config['UPLOAD_FOLDER'] = MEDIA_FOLDER app.root_path = os.getcwd() app.jinja_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(os.path.join(CURRENT_DIRECTORY, "static")) ]) sockets = Sockets(app) from . import twidder
from flask import Flask, render_template, request from jinja2 import FileSystemLoader from .utils import curry from .services import Service from exceptions import ImportError import os, sys # Setup the app and load the settings app = Flask(__name__) app.config.from_envvar('NARCISSIST_SETTINGS') app.root_path = app.config["ROOT_PATH"] main_template_path = os.path.join(app.root_path, "themes") app.jinja_loader = FileSystemLoader(main_template_path) # We will hold the mapped URLS in config so we can access them in the templates app.config["URLS"] = [] def _endpoint(service): """ Helper for XHR requests. If the request is XHR, omit the layout. """ if request.is_xhr: return self.service.render() else: return render_template(app.config["THEME"] + "/main.html", content = service.render(), title = app.config["TITLE"], sub_title = app.config["SUB_TITLE"], urls = app.config["URLS"])
import os import xbmcaddon from flask import Flask __addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path") app = Flask(__name__) app.root_path = __addonpath__ app.static_path = "/static" app.static_folder = os.path.join(__addonpath__, "resources", "static") app.template_folder = os.path.join(__addonpath__, "resources", "templates") app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))
from flaskext.markdown import Markdown import jinja2 from datetime import datetime app = Flask(__name__) app.config.from_object('config') # Include docs folder in templates my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(['sni/templates/', 'sni/templates/blog/', 'sni/templates/docs/', 'sni/templates/podcast/']), ]) app.jinja_loader = my_loader db = SQLAlchemy(app) migrate = Migrate(app, db) Markdown(app) manager = Manager(app) manager.add_command('db', MigrateCommand) cache = Cache(app,config={'CACHE_TYPE': 'simple'}) from models import DonationAddress @app.context_processor def utility_processor():
UPDATE_RATE = 1. / 30 # seconds MAX_SAFE_PID_DISTANCE = 0.25 # how far off do we really think the loop time is before we just give up? - avoid weird edges and reset logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s) %(message)s', level=logging.DEBUG) _logger = logging.getLogger(__file__) app = Flask(__name__) app.config['SECRET_KEY'] = '8f86c03170811938fd9f798a60ad9ed4d4eed080' socketio = SocketIO(app, debug=False) app_path = os.path.join(os.path.dirname(os.path.abspath(__file__))) static_path = os.path.join(app_path, 'static') # make flask load from 'static/' instead of 'templates/' app.jinja_loader = jinja2.FileSystemLoader(static_path) app.network_state = None @app.route('/') def index(): return render_template('flask_graph.html') @app.route('/sim') def sim_index(): return render_template('flask_sim.html') @socketio.on('connect') def handle_connect(): _logger.info('connected')
import os from flask import Flask import jinja2 app=Flask(__name__) app.config.from_pyfile("../settings.cfg") app.jinja_loader = jinja2.FileSystemLoader([app.config["TEMPLATES_PATH"], '/work/QA/', app.config["STATIC_PATH"], ]) from app import views
from flask.ext import restful from flask.ext.pymongo import PyMongo from flask.ext.assets import Environment, Bundle from bson.json_util import dumps import jinja2 # basic paths MONGO_URL = "mongodb://localhost:27017/violence" ASSETS_DIR=os.path.join(os.path.dirname(os.path.abspath(__file__)), '../static') # app app = Flask(__name__) app._static_folder = ASSETS_DIR app.config['SECRET_KEY'] = 'secret!' app.debug = True app.jinja_loader=jinja2.FileSystemLoader('templates') # compass config assets = Environment(app) main_scss = Bundle('scss/style.scss', 'scss/media.scss', filters='compass', output='css/style.css') assets.register('main_scss', main_scss) # mongo db app.config['MONGO_URI'] = MONGO_URL mongo = PyMongo(app) def output_json(obj, code, headers=None): resp = make_response(dumps(obj), code) resp.headers.extend(headers or {}) return resp
app.config.update( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", DEBUG=True, SEARCH_UI_SEARCH_API='http://localhost:5000/records', SEARCH_UI_BASE_TEMPLATE='invenio_theme/page.html', ) FlaskCLI(app) Babel(app) # Set jinja loader to first grab templates from the app's folder. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(join(dirname(__file__), "templates")), app.jinja_loader ]) InvenioDB(app) InvenioTheme(app) InvenioRecords(app) InvenioRecordsUI(app) search = InvenioSearch(app) search.register_mappings('records', 'data') InvenioSearchUI(app) InvenioIndexer(app) InvenioPIDStore(app) InvenioRecordsREST(app) assets = InvenioAssets(app)
from flask import Flask, render_template, request, session, Response import jinja2 import json import os import time app = Flask(__name__) loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader('/root/discord/templates'), ]) app.jinja_loader = loader queue = {} @app.route("/queue", methods=["POST"]) def q(): if all(x in request.form for x in ('id', 'channel_id', 'message', 'key', 'embed')) and len(request.form) == 5: try: if request.form['key'] != '': return render_template("index.html", RESPONSE='heck off') key = str(request.form['id']) channel_id = str(request.form['channel_id']) utc = int(time.time()) msg = str(request.form['message']) embed = str(request.form['embed']) queue.update({key:[channel_id, msg, utc, embed]}) return render_template("index.html", RESPONSE='added') except Exception as e: print(e)