def run_server(options): api_listener = Api() gevent.spawn(api_listener.run) # # Setup flask app static_url_path = "/changed-so-it-doesnt-conflict-with-blueprint-static-path" app = Flask(__name__, static_url_path=static_url_path) app.config.from_pyfile(options["config"].name) app.register_blueprint(FrontendBlueprint()) # # JS/CSS & HTML minification in production if not app.config.get('DEBUG'): from .misc.jinja2htmlcompress import HTMLCompress app.jinja_env.add_extension(HTMLCompress) assets = Environment() assets.init_app(app) # # Run server http = WSGIServer((options['http_host'], options['http_port']), app) LOGGER.info('Listening on %s:%s', options['http_host'], options['http_port']) try: http.serve_forever() return 0 except KeyboardInterrupt: http.stop() api_listener.stop() LOGGER.info('Application Terminated') return 0
def run_server(options): api_listener = Api() gevent.spawn(api_listener.run) # # Setup flask app static_url_path = "/changed-so-it-doesnt-conflict-with-blueprint-static-path" app = Flask(__name__, static_url_path=static_url_path) app.config.from_pyfile(options["config"].name) app.register_blueprint(FrontendBlueprint()) # # JS/CSS & HTML minification in production if not app.config.get('DEBUG'): from .misc.jinja2htmlcompress import HTMLCompress app.jinja_env.add_extension(HTMLCompress) assets = Environment() assets.init_app(app) # # Run server http = WSGIServer((options['http_host'], options['http_port']), app) LOGGER.info('Listening on %s:%s', options['http_host'], options['http_port']) try: http.serve_forever() return 0 except KeyboardInterrupt: http.stop() api_listener.stop() LOGGER.info('Application Terminated') return 0
def bundle_assets(app, minify=True): js_filters = ['yui_js'] if minify else None css_filters = ['yui_css'] if minify else None js = Bundle( 'js/google_maps.js', 'js/ajax.js', filters=js_filters, output='gen/packed.js', ) css = Bundle( 'css/style.css', 'css/responsive.css', 'css/fonts.css', filters=css_filters, output='gen/packed.css', ) assets = Environment() assets.register('js', js) assets.register('css', css) app.config['ASSETS_DEBUG'] = not minify assets.init_app(app)
def register_assets(app): from flask.ext.assets import Environment, Bundle assets = Environment(app) js_common = Bundle( 'js/jquery-1.10.2.min.js', 'js/bootstrap.min.js', 'js/ripples.min.js', 'js/material.min.js', filters='jsmin', output='app.js') assets.register('js_common', js_common) css = Bundle( 'css/bootstrap.min.css', 'css/ripples.min.css', 'css/material-wfont.min.css', # 'css/common.css', filters='cssmin', output='app.css' ) assets.register('css_common', css) assets.init_app(app)
def create_app(): """创建Flask app""" app = Flask(__name__) app.config.from_object(config) # CSRF protect CsrfProtect(app) if app.debug: DebugToolbarExtension(app) else: from .utils.sentry import sentry sentry.init_app(app) # from .mails import mail # mail.init_app(app) assets = Environment() assets.init_app(app) # 注册组件 register_db(app) register_routes(app) register_jinja(app) register_error_handle(app) register_uploadsets(app) # before every request @app.before_request def before_request(): pass return app
def create_app(package_name, js_assets=None, css_assets=None, settings_override=None): """Flask app factory.""" app = Flask(package_name, instance_relative_config=True) app.config.from_pyfile('settings.cfg', silent=False) app.config.from_object(settings_override) assets = Environment(app) assets.url = '../static' common_css_assets = [ 'css/bootstrap.min.css', 'css/animations.css', 'css/superfish.css', 'css/prettyPhoto.css', 'css/style.css', 'css/colors/blue.css', 'css/theme-responsive.css', ] common_js_assets = [ 'js/jquery.min.js', 'js/bootstrap.min.js', 'js/handlebars.js', 'js/ember.js', 'js/jquery.cookie.js', 'js/jquery.ba-bbq.min.js', ] if js_assets is not None: js_assets = common_js_assets + js_assets else: js_assets = common_js_assets js_bundle = Bundle( *js_assets, filters='jsmin', output='gen/' + package_name + '.js' ) assets.register('js_all', js_bundle) if css_assets is not None: css_assets = common_css_assets + css_assets else: css_assets = common_css_assets css_bundle = Bundle( *css_assets, filters='cssmin', output='gen/' + package_name + '.css' ) assets.register('css_all', css_bundle) assets.init_app(app) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) env = Environment(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask.ext.sslify import SSLify sslify = SSLify(app) #TODO: implement config_from_pyfile / instance configs #app.config.from_pyfile('config.py') env.init_app(app) bootstrap.init_app(app) db.init_app(app) # tell flask-assets where to look env.load_path = [ os.path.join(os.path.dirname(__file__), 'bower_components'), os.path.join(os.path.dirname(__file__), 'styles'), os.path.join(os.path.dirname(__file__), 'js') ] env.register( 'style', Bundle( 'style.scss', 'player.scss', 'team.scss', filters='scss', output='style.css' ) ) env.register( 'app', Bundle( 'home.js', output='app.js' ) ) @app.template_filter('datetime') def format_gametime(value): return value.strftime('%m.%d.%Y %H:%M%p') from main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def register_assets(app): """ Register Assets to the app """ # Make Environment assets = Environment(app) # Register assets assets.register('js_common', js_common) assets.register('css_common', css_common) assets.register('css_base', css_base) assets.register('css_index', css_index) assets.register('css_product_line', css_product_line) # Init App assets.init_app(app)
class TestConfigNoAppBound: """The application is not bound to a specific app. """ def setup(self): self.env = Environment() def test_no_app_available(self): """Without an application bound, we can't do much.""" assert_raises(RuntimeError, setattr, self.env, 'debug', True) assert_raises(RuntimeError, self.env.config.get, 'debug') def test_global_defaults(self): """We may set defaults even without an application, however.""" self.env.config.setdefault('FOO', 'BAR') with Flask(__name__).test_request_context(): assert self.env.config['FOO'] == 'BAR' def test_multiple_separate_apps(self): """Each app has it's own separate configuration. """ app1 = Flask(__name__) self.env.init_app(app1) # With no app yet available... assert_raises(RuntimeError, getattr, self.env, 'url') # ...set a default self.env.config.setdefault('FOO', 'BAR') # When an app is available, the default is used with app1.test_request_context(): assert self.env.config['FOO'] == 'BAR' # If the default is overridden for this application, it # is still valid for other apps. self.env.config['FOO'] = '42' assert self.env.config['FOO'] == '42' app2 = Flask(__name__) with app2.test_request_context(): assert self.env.config['FOO'] == 'BAR' def test_key_error(self): """KeyError is raised if a config value doesn't exist. """ with Flask(__name__).test_request_context(): assert_raises(KeyError, self.env.config.__getitem__, 'YADDAYADDA') # The get() helper, on the other hand, simply returns None assert self.env.config.get('YADDAYADDA') == None
class TestConfigNoAppBound: """The application is not bound to a specific app. """ def setup(self): self.env = Environment() def test_no_app_available(self): """Without an application bound, we can't do much.""" assert_raises(RuntimeError, setattr, self.env, "debug", True) assert_raises(RuntimeError, self.env.config.get, "debug") def test_global_defaults(self): """We may set defaults even without an application, however.""" self.env.config.setdefault("FOO", "BAR") with Flask(__name__).test_request_context(): assert self.env.config["FOO"] == "BAR" def test_multiple_separate_apps(self): """Each app has it's own separate configuration. """ app1 = Flask(__name__) self.env.init_app(app1) # With no app yet available... assert_raises(RuntimeError, getattr, self.env, "url") # ...set a default self.env.config.setdefault("FOO", "BAR") # When an app is available, the default is used with app1.test_request_context(): assert self.env.config["FOO"] == "BAR" # If the default is overridden for this application, it # is still valid for other apps. self.env.config["FOO"] = "42" assert self.env.config["FOO"] == "42" app2 = Flask(__name__) with app2.test_request_context(): assert self.env.config["FOO"] == "BAR" def test_key_error(self): """KeyError is raised if a config value doesn't exist. """ with Flask(__name__).test_request_context(): assert_raises(KeyError, self.env.config.__getitem__, "YADDAYADDA") # The get() helper, on the other hand, simply returns None assert self.env.config.get("YADDAYADDA") == None
def setup_assets(app): assets = Environment(app) assets.init_app(app) css = Bundle( "css/bootstrap.css", "css/layout.css", output="css/_style.css") js = Bundle( "js/jquery.min.js", "js/jquery.router.js", "js/custom.js", output="js/_basic.js") assets.register('css_all', css) assets.register('js_all', js)
def configure_extensions(app): # flask-mail # flask-cache # flask-login # flask-openid login_manager = LoginManager() login_manager.login_view = 'user.login' login_manager.refresh_view = 'user.refresh' @login_manager.user_loader def load_user(user_id): return User.query_one({'_id': user_id}) login_manager.setup_app(app) assets = Environment() assets.init_app(app)
def configure_extensions(app): # flask-mail # flask-cache # flask-login # flask-openid login_manager = LoginManager() login_manager.login_view = 'user.login' login_manager.refresh_view = 'user.refresh' @login_manager.user_loader def load_user(user_id): return User.query_one({'_id': user_id}) login_manager.setup_app(app) assets = Environment() assets.init_app(app)
class TestUrlAndDirectoryWithInitApp(object): """[Regression] Make sure the automatic "directory" and "url" values also work if the application is initialized via "init_app()". """ def setup(self): self.app = Flask(__name__, static_path='/initapp_static') self.env = Environment() self.env.init_app(self.app) def test(self): """Make sure the "url" and "directory" config values are read from the Flask app. """ with self.app.test_request_context(): assert not 'url' in self.env.config assert Bundle('foo').urls(self.env) == ['/initapp_static/foo'] assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo']
class TestUrlAndDirectoryWithInitApp(object): """[Regression] Make sure the automatic "directory" and "url" values also work if the application is initialized via "init_app()". """ def setup(self): self.app = Flask(__name__, static_path='/initapp_static') self.env = Environment() self.env.init_app(self.app) def test(self): """Make sure the "url" and "directory" config values are read from the Flask app. """ with self.app.test_request_context(): assert not 'url' in self.env.config assert Bundle('foo', env=self.env).urls() == ['/initapp_static/foo'] assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo']
def setup_assets(app): assets = Environment(app) assets.init_app(app) css = Bundle( "stylesheets/foundation.css", "stylesheets/foundation_icons_general/" "stylesheets/general_foundicons.css", "stylesheets/app.css", output="stylesheets/_basic_style.css") js = Bundle( "javascripts/jquery.js", "javascripts/modernizr.foundation.js", "javascripts/galleria.js", "javascripts/app.js", output="javascripts/_basic.js") assets.register('css_all', css) assets.register('js_all', js)
def start_app(): app = Flask(__name__) app.config['S3_BUCKET_NAME'] = 'readsy' app.config['S3_CDN_DOMAIN'] = 'dwdhruapbuq08.cloudfront.net' app.config['S3_USE_HTTPS'] = False app.config['USE_S3_DEBUG'] = True # should be true app.config['AWS_ACCESS_KEY_ID'] = os.environ['AWS_ACCESS_KEY_ID'] app.config['AWS_SECRET_ACCESS_KEY'] = os.environ['AWS_SECRET_ACCESS_KEY'] s3 = FlaskS3() s3.init_app(app) assets = Environment() # use closure_js once i have java 7 js = Bundle('js/jquery.cookie.js', 'js/mousetrap.min.js', 'js/app.js', 'js/froala_editor.min.js', filters='rjsmin', output='gen/packed.js') css = Bundle('css/bootstrap.min.css', 'css/froala_editor.min.css', 'css/bootstrapcustom.css', filters='cssmin', output='gen/packed.css') assets.register('js_all', js) assets.register('css_all', css) app.config['ASSETS_DEBUG'] = False assets.init_app(app) app.config['FLASK_ASSETS_USE_S3'] = True #should be true return app
def start_app(): app = Flask(__name__) app.config['S3_BUCKET_NAME'] = 'readsy' app.config['S3_CDN_DOMAIN'] = 'dwdhruapbuq08.cloudfront.net' app.config['S3_USE_HTTPS'] = False app.config['USE_S3_DEBUG'] = True # should be true app.config['AWS_ACCESS_KEY_ID'] = os.environ['AWS_ACCESS_KEY_ID'] app.config['AWS_SECRET_ACCESS_KEY'] = os.environ['AWS_SECRET_ACCESS_KEY'] s3 = FlaskS3() s3.init_app(app) assets = Environment() # use closure_js once i have java 7 js = Bundle('js/jquery.cookie.js', 'js/app.js', 'js/froala_editor.min.js', 'js/sharrre.min.js', filters='rjsmin', output='gen/packed.js') css = Bundle('css/bootstrap.min.css', 'css/froala_editor.min.css', 'css/bootstrapcustom.css', 'css/sharre.css', filters='cssmin', output='gen/packed.css') assets.register('js_all', js) assets.register('css_all', css) app.config['ASSETS_DEBUG'] = False assets.init_app(app) app.config['FLASK_ASSETS_USE_S3'] = True #should be true return app
def create_app(config=None): app = Flask(__name__, static_folder='statics', template_folder='templates') app.jinja_env.trim_blocks = True app.config.from_pyfile(os.path.join(APP_CONFIG_ROOT, 'default.py')) assets = Environment() assets.init_app(app) babel = Babel(app) app.register_blueprint(index.blueprint, url_prefix='') @app.template_filter('format_datetime') def format_datetime_filter(value, format = "yyyy-mm-dd HH:mm"): return format_datetime(value, format) # @app.before_request # def redirect_rhcloud(): # urlparts = urlparse(request.url) # if urlparts.netloc == 'localhost:5000': # return redirect("http://share-donkey.rhcloud.com/", code=301) return app
def register_assets(app): from flask.ext.assets import Environment, Bundle assets = Environment(app) js_common = Bundle('js/jquery-1.10.2.min.js', 'js/bootstrap.min.js', 'js/ripples.min.js', 'js/material.min.js', filters='jsmin', output='app.js') assets.register('js_common', js_common) css = Bundle( 'css/bootstrap.min.css', 'css/ripples.min.css', 'css/material-wfont.min.css', # 'css/common.css', filters='cssmin', output='app.css') assets.register('css_common', css) assets.init_app(app)
CsrfProtect(app) mongo = PyMongo(app) login_manager = LoginManager() login_manager.init_app(app) eve_db = sqlalchemy.create_engine(app.config['EVE_STATIC_DUMP']) oauth = OAuth(app) hr_oauth = oauth.remote_app( 'j4hr2', app_key='J4OAUTH' ) rQueue = Queue(connection=redis.StrictRedis(app.config['REDIS'])) api_oauth = requests.Session() api_oauth.headers.update({ 'x-oauth-key': app.config['J4OAUTH']['consumer_key'], 'x-oauth-secret': app.config['J4OAUTH']['consumer_secret']}) # Register asset bundles assets_env = Environment() assets_env.init_app(app) assets_loader = PythonLoader(assets) for name, bundle in assets_loader.load_bundles().iteritems(): assets_env.register(name, bundle)
def create_app(config=None, app_name=None, modules=None): if app_name is None: app_name = DEFAULT_APP_NAME if modules is None: modules = DEFAULT_MODULES app = Flask(app_name,static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False) handler = XMLRPCHandler('sale') handler.connect(app, '/sale') @handler.register def hello(name="world"): if not name: raise Fault("unknown_recipient", "I need someone to greet!") return "Hello, %s!" % name app.config.from_pyfile('config.cfg',silent=True) app.debug = True app.config['SECRET_KEY'] = "zuSAyu3XRqGRvAg0HxsKX12Nrvf6Hk3AgZCWg1S1j9Y=" for module in modules: app.register_blueprint(module) def url(): pass app.add_url_rule('/url','url',url) def before(): print 'Before-first-request' #app.before_first_request_funcs = [before] @app.errorhandler(414) def page_not_found(error): return 'This page does not exist', 414 app.error_handler_spec[None][414] = page_not_found admin = Admin(app,name='Maiden',index_view=MyHomeView()) admin.add_view(FileAdmin(path, '/static/', name='Static Files')) admin.add_view(UserAdmin(db.session)) admin.add_view(ProductsAdmin(db.session)) #DebugToolbarExtension(app) login.login_view = "login_view.fun_login" class Anonymous(AnonymousUser): name = u"Anonymous" login.anonymous_user = Anonymous login.login_message = u"请登录." login.refresh_view = "users.reauth" login.setup_app(app) configure_logging(app) configure_errorhandlers(app) configure_extensions(app) configure_template_filters(app) assets = Environment() assets.ASSETS_DEBUG = True assets.init_app(app) mail = Mail(app) principals = Principal(app) return app
from flask import Flask from flask.ext.assets import Environment from webassets.loaders import PythonLoader from . import auth from . import database from . import controllers from . import models __all__ = ["application", "database", "controllers", "models"] application = Flask(__name__.split(".")[0], template_folder="views") application.config.from_pyfile("../settings.cfg") # Auth init auth.login_manager.init_app(application) # Database init database.sqlalchemy.init_app(application) # Assets init asset_env = Environment() asset_mod_name = __name__.split(".")[0] + ".assets" for name, bundle in PythonLoader(asset_mod_name).load_bundles().iteritems(): asset_env.register(name, bundle) asset_env.init_app(application) # Routing init for route in controllers.routes: application.add_url_rule(route[0], route[1], route[2], methods=route[3])
from config import config, LANGUAGES from decorators import crossdomain from metrics import StatsdClient # set up flask app = Flask(__name__) app.config.from_object(__name__) app.config["STATIC_URL"] = 'static' app.config["STATIC_ROOT"] = 'static' app.config["PROPAGATE_EXCEPTIONS"] = False babel = Babel(app) # flask-assets assets = Environment(app) assets.cache = "/tmp/" assets.init_app(app) # logger logger = logging.getLogger('kilink.kilink') # metrics metrics = StatsdClient("linkode") def nocache(f): """Decorator to make a page un-cacheable.""" def new_func(*args, **kwargs): """The new function.""" resp = make_response(f(*args, **kwargs)) resp.headers['Cache-Control'] = 'public, max-age=0' return resp
from mailguntools import MailGunTools app = Flask(__name__) # The environment variable, either 'prod' or 'dev' env = os.environ.get("J4HR_ENV", "dev") # Use the appropriate environment-specific settings app.config.from_object('j4hr.settings.{env}Config' .format(env=env.capitalize())) app.config['ENV'] = env db = SQLAlchemy(app) babel = Babel(app) login_manager = LoginManager() login_manager.init_app(app) ldaptools = LDAPTools(app.config) mailgun = MailGunTools(domain=app.config['DOMAIN'], api_key=app.config['MAILGUN_API_KEY'], root=app.config['APP_DIR']) # Register asset bundles assets_env = Environment() assets_env.init_app(app) assets_loader = PythonLoader(assets) for name, bundle in assets_loader.load_bundles().iteritems(): assets_env.register(name, bundle) file_handler = RotatingFileHandler(app.config['LOG_FILE']) file_handler.setLevel(logging.INFO) file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) app.logger.addHandler(file_handler)
from flask import ( Flask, jsonify, request, url_for, render_template, ) from jsonschema import validate from flask.ext.assets import Environment IS_DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true' app = Flask(__name__) app.config['ASSETS_DEBUG'] = IS_DEBUG assets = Environment() assets.init_app(app) class FlightService(object): '''Data access layer extracts data from internal API. This can be extended for external APIs in the future''' def __init__(self, filename): with open(filename) as f: self.flights = json.loads(f.read())['flights'] # index the json for quick lookups self.flights_index = {} for index, flight in enumerate(self.flights): self.flights_index[flight['number']] = index def get(self, number):