def create_app(config_object=ProdConfig): """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ beeline.init(writekey=os.environ.get('HONEYCOMB_API_KEY'), dataset="conduit", service_name="conduit", debug=True) app = Flask(__name__.split('.')[0]) HoneyMiddleware(app, db_events=True) app.url_map.strict_slashes = False app.config.from_object(config_object) register_extensions(app) register_blueprints(app) register_errorhandlers(app) register_shellcontext(app) register_commands(app) return app
def with_flask_tracing(app): # Be as lazy as possible because vercel does some forking. HoneyMiddleware(app) original_wsgi_app = app.wsgi_app def inited_app(environ, start_response): if not with_flask_tracing.beeline_inited: beeline.init( writekey=os.environ["HONEYCOMB_KEY"], dataset="IFTTT webhooks", service_name="fructify", presend_hook=presend, ) with_flask_tracing.beeline_inited = True try: return original_wsgi_app(environ, start_response) finally: # Always flush because vercel can suspend the process. beeline.get_beeline().client.flush() app.wsgi_app = inited_app return app
def create_app(test_config: Optional[Dict[str, Any]] = None) -> Flask: app = Flask(__name__, instance_path=f"{os.getcwd()}/flaskr", instance_relative_config=True) HoneyMiddleware(app, db_events=False) if test_config is None: if os.environ["FLASK_ENV"] == "production": app.config.from_pyfile("config.py", silent=True) else: app.config.from_mapping(test_config) db = create_db() db.init_app(app) try: os.makedirs(app.instance_path) except OSError: pass from flaskr.api import views app.register_blueprint(views.bp) return app
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {'/metrics': make_wsgi_app()}) single_count = Counter('single_requests', 'Requests of single passwd') multi_count = Counter('multi_requests', 'Requests of multiple passwds') str_single_count = Counter('str_single', 'Requests of string-only single passwd') str_multi_count = Counter('str_multi', 'Requests of string-only multi passwd') short_hash = str( subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']), 'utf-8').strip() valid_chars = "!@#$%^&*()_-=+,.<>/?;:{}[]|" HoneyMiddleware(app, db_events=False) @app.route('/') def hello_world(): with beeline.tracer("home"): return render_template('index.html', short_hash=short_hash) @app.route('/healthz') def healthz(): with beeline.tracer("healthz"): return Response(f"Current version: {short_hash}.", status=200) @app.route('/<int:length>')
if response_code != 200: sample_rate = 1 if _should_sample(fields.get('trace.trace_id'), sample_rate): return True, sample_rate return False, 0 app = Flask(__name__) CSRFProtect(app) app.config.update(**config) beeline.init(writekey=config['HONEYCOMB_KEY'], dataset='rws', service_name='auth', sampler_hook=sampler) HoneyMiddleware(app, db_events=True) sslify = SSLify(app, skips=['heartbeat']) if not app.debug: app.config['PREFERRED_URL_SCHEME'] = 'https' init_db(app) init_redis(app) init_login(app) init_oauth(app) init_billing(app) init_api(app) init_wizard(app) # XXX: upstream this import beeline
import requests app = Flask(__name__) with open('./config.json') as f: fw_config = json.load(f) app.config['HONEYCOMB_KEY'] = os.environ.get('HONEYCOMB_KEY', None) app.config['REBBLE_AUTH'] = os.environ['REBBLE_AUTH'] app.config['FIRMWARE_ROOT'] = os.environ.get('FIRMWARE_ROOT', 'https://binaries.rebble.io/fw') if app.config['HONEYCOMB_KEY']: beeline.init(writekey=app.config['HONEYCOMB_KEY'], dataset='rws', service_name='cohorts') HoneyMiddleware(app) # TODO: Something like this probably belongs in a common library def require_auth(fn): @wraps(fn) def wrapper(*args, **kwargs): auth = request.headers.get('Authorization') if auth is None: abort(401) result = requests.get(f"{app.config['REBBLE_AUTH']}/api/v1/me", headers={'Authorization': auth}) if result.status_code != 200: abort(401) return fn(result.json(), *args, **kwargs)
from flask import Response from flask import request from flask import render_template from helpers import * from flask import jsonify from flask import g from rabbitmq import Publisher #Honeycomb import beeline from beeline.middleware.flask import HoneyMiddleware from uwsgidecorators import postfork # Pass your Flask app to HoneyMiddleware app = Flask(__name__) HoneyMiddleware(app, db_events=False) # db_events defaults to True, set to False if not using our db middleware with Flask-SQLAlchemy app.logger.addHandler(logging.StreamHandler(sys.stderr)) app.logger.setLevel(logging.INFO) # Prometheus import prometheus_client from prometheus_client import Counter, Histogram CART = os.getenv('CART_HOST', 'cart') USER = os.getenv('USER_HOST', 'user') PAYMENT_GATEWAY = os.getenv('PAYMENT_GATEWAY', 'https://paypal.com/') # Prometheus PromMetrics = {} PromMetrics['SOLD_COUNTER'] = Counter('sold_count', 'Running count of items sold') PromMetrics['AUS'] = Histogram('units_sold', 'Avergae Unit Sale', buckets=(1, 2, 5, 10, 100))
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) HoneyMiddleware( app, db_events=True ) # db_events defaults to True, set to False if not using our db middleware with Flask-SQLAlchemy load_dotenv(verbose=True) app.config.update(os.environ) if test_config is not None: app.config.update(test_config) @app.before_request def start_session(): try: session["sid"] except KeyError: session["sid"] = urllib.parse.quote_plus(b64encode(os.urandom(10))) print("Starting with sid {}".format(session["sid"])) @app.before_first_request def register_modules(): """Import any custom modules""" # Set custom modules path sys.path.append(app.config["MODULES_PATH"]) modules = Module.query.all() print("sys.path contains: {}".format(sys.path)) for module in modules: # Assume standard python module try: print("Attempting to importing module: {}".format(module.name)) importlib.import_module(module.name) except ModuleNotFoundError: # Attempt to load module from src dest = Path(app.config["MODULES_PATH"], module.name) print("Cloning module into: {}".format(dest)) os.makedirs(str(dest), exist_ok=True) try: git.Repo.clone_from(module.src, dest) except git.exc.GitCommandError: pass # Now re-try import try: import site reload(site) importlib.import_module(module.name) except ModuleNotFoundError: print("Error: Could not import module: {}".format( module.name)) # Register modules as blueprint (if it is one) try: importedModule = importlib.import_module(module.name) if isinstance(getattr(importedModule, module.name), Blueprint): # Load any config the Blueprint declares blueprint = getattr(importedModule, module.name) blueprintConfig = "".join( [blueprint.root_path, "/", "config.py"]) app.config.from_pyfile(blueprintConfig, silent=True) # Register the Blueprint app.register_blueprint(getattr(importedModule, module.name)) print(f"Imported {module.name} as flask Blueprint") except (ModuleNotFoundError, AttributeError): print("Error: Could not import module as blueprint: {}".format( module.name)) CORS(app, resources={r"/api/*": {"origins": "*"}}) CORS(app, resources={r"/auth/jwt-login/*": {"origins": "*"}}) images = UploadSet("images", IMAGES) patch_request_class( app, int(app.config.get("MAX_CONTENT_LENGTH", 2 * 1024 * 1024))) configure_uploads(app, images) from . import auth from . import views from . import api app.register_blueprint(auth.bp) app.register_blueprint(views.bp) app.register_blueprint(api.api) from .blueprints.admin import admin from .blueprints.subscriber import subscriber from .blueprints.pages import module_pages from .blueprints.iframe import module_iframe_embed from .blueprints.style import module_style_shop from .blueprints.seo import module_seo_page_title app.register_blueprint(module_pages, url_prefix="/pages") app.register_blueprint(module_iframe_embed, url_prefix="/iframe") app.register_blueprint(module_style_shop, url_prefix="/style") app.register_blueprint(module_seo_page_title, url_prefix="/seo") app.register_blueprint(admin, url_prefix="/admin") app.register_blueprint(subscriber) app.add_url_rule("/", "index", views.__getattribute__("choose")) with app.app_context(): database.init_app(app) Migrate(app, database) try: payment_provider = PaymentProvider.query.first() if payment_provider is None: # If payment provider table not seeded, seed with blank values. payment_provider = PaymentProvider() database.session.add(payment_provider) database.session.commit() except sqlalchemy.exc.OperationalError as e: # Allow to fail until migrations run (flask upgrade requires app reboot) print(e) load_theme(app) # Handling Errors Gracefully @app.errorhandler(404) def page_not_found(e): return render_template("errors/404.html"), 404 @app.errorhandler(413) def request_entity_too_large(error): return "File Too Large", 413 @app.errorhandler(500) def page_error_500(e): return render_template("errors/500.html"), 500 @app.cli.command() def initdb(): """Initialize the database.""" click.echo("Init the db") with open("seed.sql") as fp: con = sqlite3.connect(app.config["DB_FULL_PATH"]) cur = con.cursor() # Check not already seeded cur.execute("SELECT id from user") if cur.fetchone() is None: cur.executescript(fp.read()) else: print("Database already seeded.") con.close() @app.cli.command() def alert_subscribers_make_choice(): """Alert qualifying subscribers to set their choices For all people (aka Subscribers) - Loop over their *active* subscriptions - Check if x days before their subscription.next_date - If yes, sent them an email alert """ def alert_subscriber_update_choices(subscriber: Person): email_template = str( Path(current_app.root_path + "/emails/update-choices.jinja2.html")) # App context needed for request.host (app.config["SERVER_NAME"] not set) with app.test_request_context("/"): update_options_url = ("https://" + flask.request.host + url_for("subscriber.login")) company = Company.query.first() with open(email_template) as file_: template = Template(file_.read()) html = template.render( update_options_url=update_options_url, company=company) try: mail = Mail(current_app) msg = Message() msg.subject = company.name + " " + "Update Options" msg.sender = current_app.config["EMAIL_LOGIN_FROM"] msg.recipients = [person.email] msg.html = html mail.send(msg) except Exception as e: print(e) print("Failed to send update choices email") people = Person.query.all() for person in people: for subscription in person.subscriptions: if (get_subscription_status( subscription.gocardless_subscription_id) == "active"): # Check if x days until next subscription due, make configurable today = datetime.date.today() days_until = subscription.next_date().date() - today if days_until.days == 8: print(f"Sending alert for subscriber '{person.id}' on \ plan: {subscription.plan.title}") alert_subscriber_update_choices(person) return app
) from dynamodb import JobsPersistence, ProcessGraphsPersistence, ServicesPersistence app = Flask(__name__) app.url_map.strict_slashes = False cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' # application performance monitoring: HONEYCOMP_APM_API_KEY = os.environ.get('HONEYCOMP_APM_API_KEY') if HONEYCOMP_APM_API_KEY: beeline.init(writekey=HONEYCOMP_APM_API_KEY, dataset='OpenEO - rest', service_name='OpenEO') HoneyMiddleware(app, db_events=False) # db_events: we do not use SQLAlchemy RESULTS_S3_BUCKET_NAME = os.environ.get('RESULTS_S3_BUCKET_NAME', 'com.sinergise.openeo.results') # Zappa allows setting AWS Lambda timeout, but there is CloudFront before Lambda with a default # timeout of 30 (more like 29) seconds. If we wish to react in time, we need to return in less # than that. REQUEST_TIMEOUT = 28 FAKE_AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE" FAKE_AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', FAKE_AWS_ACCESS_KEY_ID) AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', FAKE_AWS_SECRET_ACCESS_KEY) S3_LOCAL_URL = os.environ.get('DATA_AWS_S3_ENDPOINT_URL')
def init(app, service): beeline.init(service_name=service, sampler_hook=_sampler) HoneyMiddleware(app, db_events=True)