def test_get_config(): # Test debug os.environ["FLASK_DEBUG"] = "1" assert get_config() == DevConfig # Test production os.environ["FLASK_DEBUG"] = "0" assert get_config() == ProdConfig del os.environ["FLASK_DEBUG"] assert get_config() == ProdConfig
def create_app(config="app.config.Config"): app = Flask(__name__) # Set Config app.config.from_object(config) with app.app_context(): # Create Database(if it doesn't created) url = create_database() # Set MySQL's charset to utf8mb4 forcely app.config["SQLALCHEMY_DATABASE_URI"] = str(url) # Set Redis Session app.session_interface = redis.RedisSessionInterface() # Register Database db.init_app(app) # Create DB Session & Engine (if db is not defined, create db too.) db.create_all() # Set ReCaptcha if is_setup(): app.config["RECAPTCHA_SITE_KEY"] = get_config("recaptcha_site_key") app.config["RECAPTCHA_SECRET_KEY"] = get_config( "recaptcha_secret_key") recaptcha.init_app(app) # Initialization init_template_globals(app) init_request_processors(app) # Cache Initialization cache.init_app(app) app.cache = cache from app.admin import admin from app.handler import page_not_found, forbidden, general_error, gateway_error, too_many_requests app.register_blueprint(admin) # Error Handler app.register_error_handler(403, forbidden) app.register_error_handler(404, page_not_found) app.register_error_handler(429, too_many_requests) app.register_error_handler(500, general_error) app.register_error_handler(502, gateway_error) return app
def min_max_for_all(): """Logic for sending min/max mail""" config = get_config() for recipient in config['recipients']: for transaction in recipient['transactions']: print('\n' + '-' * 50 + '\n') sv = StockValue(symbol=transaction['symbol'], config=config) bankier = sv.get_bankier() current_value, bankier_time = sv.get_values(bankier) hm = HistoryManager() global_min = hm.get_min(transaction['symbol'], recipient['address']) global_max = hm.get_max(transaction['symbol'], recipient['address']) calculator = Calculator(transaction['buy_quantity'], transaction['buy_price'], transaction['buy_quantity'], current_value) if transaction['min_max_mail'] == 'yes': prepare_min_max_email(recipient['address'], transaction['symbol'], current_value, global_min, global_max, config, calculator) hm.update_history(current_value, transaction['symbol'], recipient['address'], bankier_time, now())
def get_source(self, environment, template): if template.startswith('admin/'): return super(BlogthemeLoader, self).get_source(environment, template) theme = get_config('blog_theme') template = "/".join([theme, template]) return super(BlogthemeLoader, self).get_source(environment, template)
def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.products.views import products_api connexion_app = connexion.FlaskApp(__name__, specification_dir='openapi/', **kwargs) app = connexion_app.app try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') connexion_app.add_api('products-api-docs.yaml', resolver=RestyResolver('products')) app.register_blueprint(products_api, url_prefix='/v1.0/api/products/') managet = CouchDBManager() managet.add_document(Products) managet.setup(app) flask_injector.FlaskInjector(app=app, modules=INJECTOR_DEFAULT_MODULES.values()) app.run(port=8080) return app
async def main_consumer(count): config = get_config() aws = [] for _ in range(count): consumer = ConsumerMQ(config) aws.append(consumer.run()) await asyncio.gather(*aws)
def run_min_max_scheduler(): """Check current prices and compare it with global minimum/maximum. If the price exceeds one of extremes, the mail is sent.""" config = get_config() interval_in_minutes = config['min_max_interval_minutes'] scheduler = BackgroundScheduler() # todo: change hours. GPW works 9-17, mon-fri scheduler.add_job(func=min_max_for_all, trigger="interval", minutes=interval_in_minutes) scheduler.start() atexit.register(lambda: scheduler.shutdown())
def configure_app(app: Flask, config: MetaFlaskEnv = None): assert isinstance(app, Flask) if config is not None: assert type(config) == MetaFlaskEnv assert issubclass(config, Config) if config is None: config = get_config() app.config.from_object(config) return config
def init_app(argv=None): app = web.Application(middlewares=[ web.normalize_path_middleware(append_slash=True, merge_slashes=True), ]) app['config'] = get_config(argv) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('app/templates/')) app.add_routes(routes) setup_static_routes(app) return app
def create_app(config_name=None, **kwargs): FLASK_RUN_PORT = os.environ['SERVE_PORT'] os.environ['FLASK_RUN_PORT'] = FLASK_RUN_PORT if FLASK_RUN_PORT: app = Flask(__name__, **kwargs) try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') app.register_blueprint(happy_birthday, url_prefix='/hello') init_db(app) else: print('SERVE_PORT not defined') raise Exception return app
def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.database import init_db from app.contacts.views import contacts_api app = Flask(__name__, **kwargs) try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') app.register_blueprint(contacts_api, url_prefix='/api/contacts/') init_db(app) return app
def regular_for_all(): config = get_config() print("dupes") for recipient in config['recipients']: if recipient['daily_mail'].lower() == 'yes': stocks_to_send = {} calculators = [] for transaction in recipient['transactions']: sv = StockValue(symbol=transaction['symbol'], config=config) bankier = sv.get_bankier() current_value, bankier_time = sv.get_values(bankier) stocks_to_send[transaction['symbol']] = current_value calculators.append( Calculator(transaction['buy_quantity'], transaction['buy_price'], transaction['buy_quantity'], current_value)) prepare_daily_email(recipient['address'], stocks_to_send, calculators, config)
from celery import Celery from flask import Flask from app.utils import get_config Config = get_config() celery = Celery(__name__, broker=Config.CELERY_BROKER_URL) def create_app(config_name=None, **kwargs): """ Entry point to the Flask RESTful Server application. """ from app.database import init_db from app.contacts.views import contacts_api app = Flask(__name__, **kwargs) try: app.config.from_object(get_config(config_name)) except ImportError: raise Exception('Invalid Config') app.register_blueprint(contacts_api, url_prefix='/api/contacts/') init_db(app) return app from app.contacts import models
class Config(object): """Parent configuration class.""" DEBUG = get_config('DEBUG') CSRF_ENABLED = get_config('CSRF_ENABLED') SECRET = get_config('SECRET') SQLALCHEMY_DATABASE_URI = get_config('DATABASE_URL')
def create_app(config="app.config"): app = Flask(__name__) with app.app_context(): app.config.from_object(config) app.jinja_loader = BlogthemeLoader(os.path.join( app.root_path, app.template_folder), followlinks=True) from app.models import db, Users 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() else: db.create_all() app.db = db cache.init_app(app) app.cache = cache app.debug = False configure_uploads(app, photos) redis_store = FlaskRedis() redis_store.init_app(app) login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.oauth' login_manager.init_app(app) toolbar = DebugToolbarExtension(app) #toolbar.DEBUG_TB_INTERCEPT_REDIRECTS = False md = Misaka() md.init_app(app) Analytics(app) app.config['ANALYTICS']['GAUGES']['SITE_ID'] = 'XXXXXXXXXXXXX' if not get_config('blog_theme'): set_config('blog_theme', 'blog') from app.views import views from app.utils import init_errors, init_utils, init_logs from app.post import blog from app.auth import auth from app.admin import admin from app.status import web #from app.api import init_errors(app) init_utils(app) init_logs(app) app.register_blueprint(views) app.register_blueprint(blog) app.register_blueprint(auth) app.register_blueprint(admin) app.register_blueprint(web) @login_manager.user_loader def load_user(user_id): try: return Users.query.get(int(user_id)) except Users.DoesNotExist: return None return app
from app.utils import get_config from app import create_app # Blueprints from api import urls config_name = get_config('APP_SETTINGS') # config_name = "development" app = create_app(config_name) app.register_blueprint(urls) if __name__ == '__main__': app.run()
async def main_producer(): config = get_config() producer_a = ProducerA(config) producer_b = ProducerB(config) await asyncio.gather(producer_a.run(), producer_b.run())
"CREATE TABLE log_data (" \ "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT," \ "user_id INT NOT NULL," \ "email VARCHAR(100)," \ "type VARCHAR(20) NOT NUlL," \ "action VARCHAR(256) NOT NUlL," \ "url VARCHAR(512)," \ "created_at TIMESTAMP NOT NULL" \ ");" ] async def create_db(commands, config, loop): pool = await aiomysql.create_pool(user=config['mysql']['user'], password=config['mysql']['password'], host=config['mysql']['host'], port=config['mysql']['port'], loop=loop) async with pool.acquire() as conn: async with conn.cursor() as cursor: await cursor.execute("".join(commands)) await conn.commit() pool.close() await pool.wait_closed() config = get_config(sys.argv[1:]) loop = asyncio.get_event_loop() loop.run_until_complete(create_db(commands, config, loop))
def is_setup(): return bool(get_config("setup")) is True
from flask import Flask import argparse, requests from cassandra.cqlengine import connection from cassandra.cqlengine.models import Model from cassandra.cqlengine.management import sync_table, drop_keyspace, create_keyspace_network_topology import inspect from app import models, materialized_views, elastic, utils as ut from app.plugins.cassandra_cqlengine import db_connection_setup, create_materialized_view import time DEFAULT = '__DEFAULT__' config = ut.get_config() app = Flask(__name__) app.config.from_object(config) with app.app_context(): db_connection_setup([config.DB_HOST], config.DB_KEYSPACE, lazy_connect=True) parser = argparse.ArgumentParser() parser.add_argument('--recreate', nargs='?', default=DEFAULT) parser.add_argument('--elastic', nargs='?', default=DEFAULT) parser.add_argument('--seed', nargs='?', default=DEFAULT) # get args and ignore unknown args, unknown = parser.parse_known_args() if args.recreate != DEFAULT: print('recreate start') drop_keyspace(config.DB_KEYSPACE) create_keyspace_network_topology(config.DB_KEYSPACE, {'DC1': 3}) # sync_tables def is_model(model, name):
import os from flask_script import Manager # class for handling a set of commands from flask_migrate import Migrate, MigrateCommand from app import db, create_app from app import models from app.utils import get_config app = create_app(config_name=get_config('APP_SETTINGS')) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
def test_xml_read_write(self): xml_content = utils.get_config(self.test_file) utils.update_config(self.test_file, xml_content) new_xml_tree = self.get_xml_tree() # pass element to xml_compare, not ElementTree self.assertEqual(True, xml_compare(self.old_xml_tree, new_xml_tree))
from app.postgres.db import * from app.utils import BASE_DIR, get_config DSN = "postgresql://{user}:{password}@{host}:{port}/{database}" ADMIN_DB_URL = DSN.format(user='******', password='******', database='postgres', host='postgres', port=5432) admin_engine = create_engine(ADMIN_DB_URL, isolation_level='AUTOCOMMIT') USER_CONFIG_PATH = BASE_DIR / 'config' / 'config.yaml' USER_CONFIG = get_config(['-c', USER_CONFIG_PATH.as_posix()]) USER_DB_URL = DSN.format(**USER_CONFIG['postgres']) user_engine = create_engine(USER_DB_URL) def setup_db(config): db_name = config['database'] db_user = config['user'] db_pass = config['password'] conn = admin_engine.connect() conn.execute("DROP DATABASE IF EXISTS %s" % db_name) conn.execute("DROP ROLE IF EXISTS %s" % db_user) conn.execute("CREATE USER %s WITH PASSWORD '%s'" % (db_user, db_pass)) conn.execute("CREATE DATABASE %s ENCODING 'UTF8'" % db_name) conn.execute("GRANT ALL PRIVILEGES ON DATABASE %s TO %s" %
def domain_check(): if get_config('domain_check'): if url_parse(request.host_url).host != get_config('wol_domain'): return ""