def init_logging(app): location_log_config = app.config['LOGGING_CONFIG_LOCATION'] if os.path.isfile(location_log_config): logging.config.fileConfig(location_log_config, disable_existing_loggers=True) logger.info('Loaded logging configuration file "%s"', location_log_config) else: logger.warning('Error loading configuration file "%s"', location_log_config) if app.config['SENTRY_DSN']: # This could not be done in the default .ini because the # handler has to be passed to `raven.setup_logging`. # the following adds itself to app.extensions['sentry'] sentry = Sentry() sentry.init_app(app, dsn=app.config['SENTRY_DSN']) handler = SentryHandler(app.extensions['sentry'].client) handler.level = logging.NOTSET setup_logging(handler) logger.debug("Sentry DSN: {}".format(app.config['SENTRY_DSN'])) else: logger.debug("No sentry DSN specified")
def get_wsgi_app(config): app = Flask("PROJECT") app.config.from_object(config) # register blueprint blueprints = (bp_hello, ) for bp in blueprints: app.register_blueprint(bp) # orm and redis, default not open # app.sa_engine = engine_from_config(app.config["SQLALCHEMY_OPTIONS"], # prefix="") # app.DBSession = scoped_session(sessionmaker(bind=app.sa_engine), # scopefunc=_app_ctx_stack.__ident_func__) # app.redis_client = StrictRedis(**app.config["REDIS_CONFIG"]) # @app.before_request # def before_request(): # g.rds = current_app.redis_client # g.db = current_app.DBSession() # @app.teardown_request # def teardown_request(exception): # g.db.close() # init thrall sentry if (not app.debug) and app.config.get("SENTRY_ON", False): from raven.contrib.flask import Sentry sentry = Sentry(dsn=app.config["SENTRY_DSN"], logging=True, level=logging.ERROR) app.config['SENTRY_NAME'] = app.config["SENTRY_IDENTIFY"] sentry.init_app(app) return app
def create_app(): app = Flask(__name__) app.debug = os.getenv('DEBUG') == 'True' if os.getenv('SENTRY_DSN'): sentry = Sentry() sentry.init_app(app) return app
def create_app(): app = Moxie(__name__) configurator = Configurator(app) cfg_path = path.join(app.root_path, 'default_settings.yaml') configurator.from_yaml(cfg_path) configurator.from_envvar('MOXIE_SETTINGS', silent=True) # logging configuration for Raven/Sentry if raven_available and 'SENTRY_DSN' in app.config: sentry = Sentry(dsn=app.config['SENTRY_DSN']) # capture uncaught exceptions within Flask sentry.init_app(app) handler = SentryHandler(app.config['SENTRY_DSN'], level=logging.getLevelName( app.config.get('SENTRY_LEVEL', 'WARNING'))) setup_logging(handler) statsd.init_app(app) cache.init_app(app) db.init_app(app) # Static URL Route for API Health checks app.add_url_rule('/_health', view_func=check_services) app.add_url_rule('/', view_func=RootView.as_view('root')) return app
def before_request(self, *args, **kwargs): Sentry.before_request(self, *args, **kwargs) self.client.extra_context({ "commit": head, "dirty": dirty, }) self.client.tags_context({"isDirty": len(dirty) > 0})
def create_app(configuration=None, app_name=None, blueprints=None): """Create the main Flask app.""" if app_name is None: app_name = config.DefaultConfig.APP_NAME if blueprints is None: blueprints = DEFAULT_BLUEPRINTS app = Flask(app_name) # configure app from object or environment configure_app(app, configuration) # set production security headers if app.config['ENVIRONMENT'] == "Production": # append media-src to include flask-store domain store_domain = urlparse.urlparse(app.config['STORE_DOMAIN']).netloc, CALLPOWER_CSP['media-src'].extend(store_domain) talisman.init_app(app, force_https=True, content_security_policy=CALLPOWER_CSP ) if app.config.get('SENTRY_DSN'): from raven.contrib.flask import Sentry sentry = Sentry() sentry.init_app(app, dsn=app.config['SENTRY_DSN']) sentry_report_uri = 'https://sentry.io/api/%s/csp-report/?sentry_key=%s' % ( sentry.client.remote.project, sentry.client.remote.public_key ) talisman.content_security_policy_report_uri = sentry_report_uri # init extensions once we have app context init_extensions(app) # then blueprints, for url/view routing register_blueprints(app, blueprints) configure_logging(app) configure_error_pages(app) # then extension specific configurations configure_babel(app) configure_login(app) configure_assets(app) configure_restless(app) # finally instance specific configurations context_processors(app) instance_defaults(app) app.logger.info('Call Power started') return app
def init_app(app): if 'SENTRY_DSN' in app.config: try: from raven.contrib.celery import ( register_signal, register_logger_signal ) from raven.contrib.flask import Sentry except: log.error('raven[flask] is required to use sentry') return sentry = Sentry() tags = app.config['SENTRY_TAGS'] = app.config.get('SENTRY_TAGS', {}) app.config.setdefault('SENTRY_USER_ATTRS', ['slug', 'email', 'fullname']) app.config.setdefault('SENTRY_LOGGING', 'WARNING') log_level_name = app.config.get('SENTRY_LOGGING') if log_level_name: log_level = getattr(logging, log_level_name.upper()) if log_level: sentry.logging = True sentry.level = log_level # Do not send HTTPExceptions exceptions = app.config.get('RAVEN_IGNORE_EXCEPTIONS', []) if HTTPException not in exceptions: exceptions.append(HTTPException) if PermissionDenied not in exceptions: exceptions.append(PermissionDenied) app.config['RAVEN_IGNORE_EXCEPTIONS'] = exceptions app.config['SENTRY_PUBLIC_DSN'] = public_dsn(app.config['SENTRY_DSN']) # Versions Management: uData and plugins versions as tags. packages = ['udata'] packages += ['udata_{0}'.format(p) for p in app.config['PLUGINS']] for package in packages: version = pkg_resources.get_distribution(package).version if version: tags[package] = version sentry.init_app(app) # register a custom filter to filter out duplicate logs register_logger_signal(sentry.client, loglevel=sentry.level) # hook into the Celery error handler register_signal(sentry.client)
def create_app(name=None): app = Flask(name) if os.environ.get('PRODUCTION'): app.config.from_object(ProductionConfig) print "running with ProductionConfig" else: app.config.from_object(DefaultConfig) print "running with DefaultConfig" # sentry if app.config.get('SENTRY_DSN'): sentry = Sentry() sentry.init_app(app) app.sentry = sentry # assets assets = Environment(app) assets.url = app.static_url_path scss_bundle = Bundle('css/*.scss', 'css/*.css', filters=['scss', 'cssmin'], depends='css/*.scss', output='css/all.css') assets.register('scss_all', scss_bundle) js_bundle = Bundle('js/*.js', filters='rjsmin', output='js/all.js') assets.register('js_all', js_bundle) Compress(app) # cache if app.config['DEBUG']: cache_type = 'null' else: cache_type = 'simple' cache = Cache(config={'CACHE_TYPE': cache_type}) cache.init_app(app) app.cache = cache # CDN cdn = CDN() cdn.init_app(app) # workaround flask-assets / flask-cdn integration if app.config.get('CDN_HTTPS'): cdn_scheme = 'https' else: cdn_scheme = 'http' if app.config.get('FLASK_ASSETS_USE_CDN') and app.config.get('CDN_DOMAIN'): app.jinja_env.globals['FLASK_CDN'] = '%s://%s' % (cdn_scheme, app.config['CDN_DOMAIN']) return app
def create_app(config=None): app = Flask(__name__) config = get_config() app.config.from_object(config) db.init_app(app) app = register_endpoints(app) @app.errorhandler(404) def page_not_found(e): import urllib output = "" for rule in app.url_map.iter_rules(): options = {} for arg in rule.arguments: options[arg] = "[{0}]".format(arg) methods = ','.join(rule.methods) url = url_for(rule.endpoint, **options) line = urllib.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url)) line = "<strong>%s</strong> %s %s" % (rule.endpoint, methods, urllib.unquote(url)) output += "<li>" + line + "</li>" return """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p> <h3>Current routes:</h3> <ul> %s </ul> """ % output, 404 if 'LOGGING' in app.config: configure_logging(app.config['LOGGING']) if 'SENTRY_DSN' in app.config: sentry = Sentry(dsn=app.config['SENTRY_DSN'], logging=True, level=logging.ERROR) sentry.init_app(app) app.wsgi = SentryMiddleware(app.wsgi_app, sentry.client) return app
class SuperdeskSentry(): """Sentry proxy that will do nothing in case sentry is not configured.""" def __init__(self, app): if app.config.get('SENTRY_DSN'): app.config.setdefault('SENTRY_NAME', app.config.get('SERVER_NAME')) self.sentry = Sentry(app, register_signal=False, wrap_wsgi=False) else: self.sentry = None def captureException(self, exc_info=None, **kwargs): if self.sentry: self.sentry.captureException(exc_info, **kwargs) def captureMessage(self, message, **kwargs): if self.sentry: self.sentry.captureMessage(message, **kwargs)
def __init__(self, app): if app.config.get('SENTRY_DSN'): app.config.setdefault('SENTRY_NAME', app.config.get('SERVER_NAME')) self.sentry = Sentry(app, register_signal=False, wrap_wsgi=False, logging=True, level=logging.WARNING) register_logger_signal(self.sentry.client) register_signal(self.sentry.client) else: self.sentry = None
def config(): logging.basicConfig(level=logging.DEBUG) # load captcha defaults app_flask.config.from_object("flask.ext.captcha.settings") app_flask.config.from_object("settings") app.config_from_object("settings") settings_file = os.environ.get('AGORA_ELECTION_SETTINGS', None) if settings_file is not None: if not os.path.isabs(settings_file): os.environ['AGORA_ELECTION_SETTINGS'] = os.path.abspath(settings_file) logging.debug("AGORA_ELECTION_SETTINGS " "= %s" % os.environ['AGORA_ELECTION_SETTINGS']) app_flask.config.from_envvar('AGORA_ELECTION_SETTINGS', silent=False) # an optimization election_url = app_flask.config['AGORA_ELECTION_DATA_URL'] if election_url.startswith("http"): import requests bauth = app_flask.config.get('AGORA_ELECTION_DATA_BASIC_AUTH', None) election_json = requests.get(election_url, verify=False, auth=bauth).json() extra_data_json = requests.get(election_url + "extra_data/", verify=False, auth=bauth).json() else: with open(election_url, 'r', encoding="utf-8") as f: election_json = json.loads(f.read()) # NOTE: do not support extra_data in this mode extra_data_json = dict() edata = app_flask.config.get('AGORA_ELECTION_DATA', {}) edata['election'] = election_json edata['election_extra_data'] = extra_data_json app_flask.config['AGORA_ELECTION_DATA_STR'] = Markup(json.dumps( app_flask.config.get('AGORA_ELECTION_DATA', {}))) # config captcha app_captcha.init_app(app_flask) app_mail.init_app(app_flask) sentry = Sentry() sentry.init_app(app=app_flask) app_captcha.init_app(app_flask)
def init_app(app): if app.config['SENTRY_DSN']: try: from raven.contrib.celery import ( register_signal, register_logger_signal ) from raven.contrib.flask import Sentry except ImportError: log.error('raven is required to use Sentry') return sentry = Sentry() tags = app.config['SENTRY_TAGS'] log_level_name = app.config['SENTRY_LOGGING'] if log_level_name: log_level = getattr(logging, log_level_name.upper()) if log_level: sentry.logging = True sentry.level = log_level # Do not send HTTPExceptions exceptions = set(app.config['SENTRY_IGNORE_EXCEPTIONS']) for exception in IGNORED_EXCEPTIONS: exceptions.add(exception) app.config['SENTRY_IGNORE_EXCEPTIONS'] = list(exceptions) app.config['SENTRY_PUBLIC_DSN'] = public_dsn(app.config['SENTRY_DSN']) # Versions Management: uData and plugins versions as tags. for dist in entrypoints.get_plugins_dists(app): if dist.version: tags[dist.project_name] = dist.version # Do not forget udata itself tags['udata'] = pkg_resources.get_distribution('udata').version sentry.init_app(app) # register a custom filter to filter out duplicate logs register_logger_signal(sentry.client, loglevel=sentry.level) # hook into the Celery error handler register_signal(sentry.client)
def init_logging(app): """Initialize the app's logging mechanisms - Configure the sentry client, if a DSN is given - Apply the default config dict (`defaults.DEFAULT_CONFIG`) - If given and existent, apply the additional config file """ # Configure Sentry client (raven) if app.config['SENTRY_DSN']: logger.debug("Sentry DSN: %s", app.config['SENTRY_DSN']) sentry = Sentry() sentry.init_app(app, dsn=app.config['SENTRY_DSN']) def register_sentry_handler(): handler = SentryHandler() handler.client = app.extensions['sentry'].client setup_logging(handler) return handler else: logger.debug("No sentry DSN specified") def register_sentry_handler(): return logging.NullHandler() # Apply default config dict config = replace_empty_handler_callables(DEFAULT_CONFIG, register_sentry_handler) logging.config.dictConfig(config) if app.config.get('LOG_CONFIG') is not None: config = replace_empty_handler_callables(app.config['LOG_CONFIG'], register_sentry_handler) logging.config.dictConfig(config) logger.debug('Initialized logging', extra={'data': { 'DEFAULT_CONFIG': DEFAULT_CONFIG, 'EXTRA_CONFIG': app.config.get('LOG_CONFIG') }})
def init_app(app): if 'SENTRY_DSN' in app.config: try: from raven.contrib.celery import ( register_signal, register_logger_signal ) from raven.contrib.flask import Sentry except: log.error('raven[flask] is required to use sentry') return sentry = Sentry() app.config.setdefault('SENTRY_USER_ATTRS', ['slug', 'email', 'fullname']) app.config.setdefault('SENTRY_LOGGING', 'WARNING') log_level_name = app.config.get('SENTRY_LOGGING') if log_level_name: log_level = getattr(logging, log_level_name.upper()) if log_level: sentry.logging = True sentry.level = log_level # Do not send HTTPExceptions exceptions = app.config.get('RAVEN_IGNORE_EXCEPTIONS', []) if HTTPException not in exceptions: exceptions.append(HTTPException) if PermissionDenied not in exceptions: exceptions.append(PermissionDenied) app.config['RAVEN_IGNORE_EXCEPTIONS'] = exceptions app.config['SENTRY_PUBLIC_DSN'] = public_dsn(app.config['SENTRY_DSN']) sentry.init_app(app) # register a custom filter to filter out duplicate logs register_logger_signal(sentry.client, loglevel=sentry.level) # hook into the Celery error handler register_signal(sentry.client)
def make_application(): from flask import Flask from cronq.config import Config import cronq.web import os flask_app = Flask(__name__, static_url_path='/static') if Config.BUGSNAG_API_KEY: import bugsnag from bugsnag.flask import handle_exceptions bugsnag.configure(api_key=Config.BUGSNAG_API_KEY) handle_exceptions(flask_app) elif Config.SENTRY_DSN: from raven.contrib.flask import Sentry sentry = Sentry() sentry.init_app(flask_app, dsn=Config.SENTRY_DSN) flask_app.config.from_object('cronq.config.Config') flask_app.register_blueprint(cronq.web.blueprint_http) cronq.web.blueprint_http.config = flask_app.config return flask_app
from app import app from raven.contrib.flask import Sentry sentry = Sentry( app, dsn= 'https://*****:*****@sentry.io/235185' ) app.run(host='0.0.0.0', port=80) #app.run(debug=True,port=5007)
def instance(app): """:rtype: Sentry""" sentry = Sentry() if not app.debug and not app.testing: sentry.init_app(app, **app.config['SENTRY_IO']['flask']) return sentry
from flask_alembic import Alembic from flask_sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry from zeus.utils.celery import Celery from zeus.utils.redis import Redis import os ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) alembic = Alembic() celery = Celery() db = SQLAlchemy() redis = Redis() sentry = Sentry(logging=True, level=logging.WARN, wrap_wsgi=True) def force_ssl(app): def middleware(environ, start_response): environ['wsgi.url_scheme'] = 'https' return app(environ, start_response) return middleware def create_app(_read_config=True, **config): app = Flask( __name__, static_folder=os.path.join(ROOT, 'static'), template_folder=os.path.join(ROOT, 'templates'),
# TODO, figure out how to load gevent monkey patch cleanly in production try: from gevent.monkey import patch_all patch_all() import gevent_psycopg2 gevent_psycopg2.monkey_patch() except ImportError: print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import create_app from extensions import assets assets._named_bundles = {} application = create_app() # requires application context assets.auto_build = False if os.environ.get('SENTRY_DSN'): from raven.contrib.flask import Sentry sentry = Sentry() sentry.init_app(application) application.wsgi_app = ProxyFix(application.wsgi_app)
from flask import Flask, request, current_app from bot import Osmbot from configobj import ConfigObj import os from raven.contrib.flask import Sentry import telegram application = Flask(__name__) application.debug = True Osmbot(application, '') config = ConfigObj('bot.conf') token = config['token'] telegram_api = telegram.Bot(config['token']) if 'sentry_dsn' in config: application.config['sentry_dsn'] = config['sentry_dsn'] sentry = Sentry(application, dsn=config['sentry_dsn']) sentry.captureMessage('OSMBot started', level=logging.INFO) application.sentry = sentry webhook = os.path.join(config['webhook'], config['token']) application.logger.debug('webhook:%s', config['webhook']) result = telegram_api.setWebhook(webhook) if result: application.logger.debug('Webhook set') if __name__ == '__main__': application.run(host='0.0.0.0', debug=True)
from flask import Flask, abort, render_template, request from raven.contrib.flask import Sentry from sparkpost import SparkPost from summarize import summarize_page # Flask application app = Flask(__name__) # Configuration app.config.from_object('settings') app.config.from_envvar('SETTINGS_MODULE', silent=True) app.config.from_pyfile('settings_local.py', silent=True) # Email sparkpost = SparkPost(app.config['SPARKPOST_API_KEY']) # Error logging sentry = Sentry(app) if app.config['SENTRY_DSN'] != 'disabled' else None # Views @app.route('/') def index(): return render_template('index.html') @app.route('/admin') def admin(): if not bool(app.config['DEBUG']): abort(404) return render_template('admin.html')
import os.path from raven.conf import setup_logging from raven.contrib.flask import Sentry from raven.handlers.logging import SentryHandler # Load configuration config = ConfigParser.ConfigParser() current_dir = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(os.path.dirname(current_dir)) config.read(os.path.join(base_dir, 'app.config')) logger = logging.getLogger(__name__) # the mediameter logger # setup logging sentry = Sentry(dsn=config.get('sentry', 'dsn')) handler = SentryHandler(config.get('sentry', 'dsn')) setup_logging(handler) logging.basicConfig(level=logging.INFO) mc_logger = logging.getLogger('mediacloud') requests_logger = logging.getLogger('requests') logger.info("---------------------------------------------------------------------------------------") # Flask app flapp = flask.Flask(__name__) sentry.init_app(flapp) flapp.secret_key = 'put secret key here' assets = Environment(flapp) # Create media cloud api
from raven.contrib.flask import Sentry from config import ORG_ID, CHANNEL_MAP, SENTRY_DSN, BOTNAME, BOTPW, TRAVIS_MAP from utils import parseException app = Flask(__name__) try: flow = Flow(BOTNAME) except flow.FlowError: flow = Flow() flow.create_device(BOTNAME, BOTPW) app.logger.info('Device for bot {} created'.format(BOTNAME)) if SENTRY_DSN: sentry = Sentry(app, dsn=SENTRY_DSN) @app.route('/') def index(): channel_id = CHANNEL_MAP['semabot'] flow.send_message(ORG_ID, channel_id, 'botbotbot') return 'foo' @app.route('/error/') def error(): return 1 / 0 @app.route('/pong/')
from flask import Flask from flask_restful import Api from raven.contrib.flask import Sentry import postgraas_server from postgraas_server.backends import get_backend from postgraas_server.configuration import get_application_config, get_meta_db_config_path from postgraas_server.management_resources import DBInstanceResource, DBInstanceCollectionResource, db INT_OPTIONS = [ 'SQLALCHEMY_POOL_RECYCLE', 'SQLALCHEMY_POOL_SIZE', 'SQLALCHEMY_POOL_TIMEOUT', 'SQLALCHEMY_MAX_OVERFLOW' ] sentry = Sentry(logging=True, level=logging.WARN, wrap_wsgi=True, logging_exclusions=()) def create_app(config): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['BUNDLE_ERRORS'] = True app_config = get_application_config(config) for key in app_config: app.config[key.upper()] = int(app_config[key]) if key.upper() in INT_OPTIONS else app_config[key] app.config['SENTRY_INCLUDE_PATHS'] = [ 'postgraas_server', ]
db = SQLAlchemy(app) # Create database if it doesn't already exist. # The server will crash on the first run, probably because # of a side effect of create_database # from sqlalchemy_utils import database_exists, create_database # if not database_exists(DB_URL): # create_database(DB_URL) # Create the queues. # from psycopg2 import connect # from pq import PQ # conn = connect('dbname=test108 user=postgres') # pq.create() # pq = PQ(conn) sentry = Sentry(app) conn = connect(DB_URL) pq = PQ(conn) class Task(db.Model): """A task to be completed by a judicious participant.""" __tablename__ = "task" id = db.Column(UUID, primary_key=True, nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.now) last_queued_at = db.Column(db.DateTime) type = db.Column(db.String(64), nullable=False) parameters = db.Column(db.JSON)
import cv2 import numpy as np from auth import token_required from lib.detection_model import load_net, detect SESSION_TTL_SECONDS = 60 * 2 app = flask.Flask(__name__) # SECURITY WARNING: don't run with debug turned on in production! app.config['DEBUG'] = environ.get('DEBUG') == 'True' # Sentry if environ.get('SENTRY_DSN'): sentry = Sentry(app, dsn=environ.get('SENTRY_DSN')) model_dir = path.join(path.dirname(path.realpath(__file__)), 'model') net_main, meta_main = load_net(path.join(model_dir, 'model.cfg'), path.join(model_dir, 'model.weights'), path.join(model_dir, 'model.meta')) @app.route('/p', methods=['GET']) @token_required def get_p(): if 'img' in request.args: resp = urllib.request.urlopen(request.args['img']) img_array = np.array(bytearray(resp.read()), dtype=np.uint8) img = cv2.imdecode(img_array, -1) detections = detect(net_main, meta_main, img, thresh=0.25)
# coding=utf-8 from flask import Flask from raven.contrib.flask import Sentry app = Flask(__name__) sentry = Sentry( app, dsn= 'http://*****:*****@localhost:5000/2' ) # noqa @app.route('/error') def error(): try: 1 / 0 except ZeroDivisionError: sentry.captureException() return 'error' @app.route('/raise') def auto_raise(): raise IndexError @app.route('/log') def log(): sentry.captureMessage('hello, world!') return 'logging'
from flask import Flask from dikhao import __version__ from raven.contrib.flask import Sentry app = Flask(__name__) redis_handler = dikhao.database.redis_handler.RedisHandler( host=config.REDIS_HOST, port=config.REDIS_PORT_NO, password=config.REDIS_PASSWORD, timeout=config.REDIS_TIMEOUT, max_connections=config.REDIS_MAX_CONNECTIONS, ) if config.SENTRY_DSN: app.config['SENTRY_DSN'] = config.SENTRY_DSN Sentry(app) @app.route("/") def status(): """ Returns the status page """ return 'Ok - Version: %s' % __version__ def sync_everything(): try: redis_handler.close_extra_connections() thread_list = [] if not config.NO_ROUTE53:
logHandler = TimedRotatingFileHandler('logs/app.log', when='D', backupCount=7) logHandler.setFormatter(formatter) # set the log handler level app.logger.setLevel(logging.INFO) app.logger.addHandler(logHandler) app.logger.info("Starting up...") config = os.environ.get('TR_CONFIG', 'config.DevelopmentConfig') app.config.from_object(config) mail = Mail(app) if app.config['SENTRY_DSN']: from raven.contrib.flask import Sentry sentry = Sentry(app, dsn=app.config['SENTRY_DSN']) db = SQLAlchemy(metadata=metadata) migrate = Migrate(app, db) db.init_app(app) @app.before_request def before_request(): try: db.engine.execute('SELECT 1 from users') except exc.SQLAlchemyError as e: return f"Song Delivery is unavailable at the moment: {e}", 503
def make_client_and_raven(self, *args, **kwargs): app = create_app(*args, **kwargs) raven = InMemoryClient() Sentry(app, client=raven) return app.test_client(), raven, app
new_app = Flask(config.APP_NAME) new_app.config.from_object('src.config') CORS(new_app) new_app.register_blueprint(api_v1) return new_app def setup_logging(flask_app): """Perform the setup of logging for this application.""" if not flask_app.debug: handler = logging.StreamHandler() handler.setFormatter( logging.Formatter( '[%(asctime)s] %(levelname)s in %(module)s: %(message)s')) log_level = os.environ.get('FLASK_LOGGING_LEVEL', logging.getLevelName(logging.WARNING)) handler.setLevel(log_level) flask_app.logger.addHandler(handler) flask_app.config['LOGGER_HANDLER_POLICY'] = 'never' flask_app.logger.setLevel(logging.DEBUG) app = create_app() setup_logging(app) app.wsgi_app = ProxyFix(app.wsgi_app) sentry = Sentry(app, dsn=config.SENTRY_DSN, logging=True, level=logging.ERROR) if __name__ == "__main__": app.run()
def setup_app(app): """Setup Sentry extension.""" app.config.setdefault('SENTRY_DSN', None) # Sanitize data more app.config.setdefault('SENTRY_PROCESSORS', ( 'raven.processors.SanitizePasswordsProcessor', 'invenio.ext.logging.backends.sentry.InvenioSanitizeProcessor', )) # When a user is logged in, also include the user info in the log message. app.config.setdefault('SENTRY_USER_ATTRS', ['info', ]) # Defaults to only reporting errors and warnings. app.config.setdefault('LOGGING_SENTRY_LEVEL', 'WARNING') # Send warnings to Sentry? app.config.setdefault('LOGGING_SENTRY_INCLUDE_WARNINGS', True) # Send Celery log messages to Sentry? app.config.setdefault('LOGGING_SENTRY_CELERY', True) # Transport mechanism for Celery. Defaults to synchronous transport. # See http://raven.readthedocs.org/en/latest/transports/index.html app.config.setdefault('LOGGING_SENTRY_CELERY_TRANSPORT', 'sync') if app.config['SENTRY_DSN']: # Detect Invenio requirements and add to Sentry include paths so # version information about them is added to the log message. app.config.setdefault('SENTRY_INCLUDE_PATHS', sentry_include_paths()) # Fix-up known version problems getting version information # Patch submitted to raven-python, if accepted the following lines # can be removed: # https://github.com/getsentry/raven-python/pull/452 from raven.utils import _VERSION_CACHE import numpy import webassets import setuptools _VERSION_CACHE['invenio'] = invenio.__version__ _VERSION_CACHE['numpy'] = numpy.__version__ _VERSION_CACHE['webassets'] = webassets.__version__ _VERSION_CACHE['setuptools'] = setuptools.__version__ # Modify Sentry transport for Celery - must be called prior to client # creation. celery_dsn_fix(app) # Installs sentry in app.extensions['sentry'] s = Sentry( app, logging=True, level=getattr(logging, app.config['LOGGING_SENTRY_LEVEL']) ) # Replace method with more robust version s.add_sentry_id_header = add_sentry_id_header # Add extra tags information to sentry. s.client.extra_context({'version': invenio.__version__}) # Capture warnings from warnings module if app.config['LOGGING_SENTRY_INCLUDE_WARNINGS']: setup_warnings(s) # Setup Celery logging to Sentry if app.config['LOGGING_SENTRY_CELERY']: # Setup Celery loggers after_setup_task_logger.connect( partial(celery_logger_setup, app=app), weak=False ) after_setup_logger.connect( partial(celery_logger_setup, app=app), weak=False ) # Werkzeug only adds a stream handler if there's no other handlers # defined, so when Sentry adds a log handler no output is # received from Werkzeug unless we install a console handler here on # the werkzeug logger. if app.debug: logger = logging.getLogger('werkzeug') logger.setLevel(logging.INFO) handler = logging.StreamHandler() logger.addHandler(handler)
""" Created: 19.03.2015 @author: Dennis Ligtenberg Runs the Flask app locally """ import os from webservice import app if __name__ == "__main__": from raven.contrib.flask import Sentry sentry = Sentry() # automatically reads 'SENTRY_DSN' if set sentry.init_app(app) app.run(port=8080, host="0.0.0.0", debug=bool(os.environ.get("DEBUG")))
from raven.contrib.flask import Sentry from rsa import generate_key from core import SlashpassCMD from environ import BIP39, DATABASE_URL, REDIS_HOST, SENTRY_DSN secret_key = generate_key(BIP39) private_key = secret_key.exportKey("PEM") public_key = secret_key.publickey().exportKey("PEM") server = Flask(__name__) server.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL server.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False cache = redis.StrictRedis(host=REDIS_HOST, port=6379) sentry = Sentry(server, dsn=SENTRY_DSN) cmd = SlashpassCMD(cache, private_key) db = SQLAlchemy(server) class Team(db.Model): id = db.Column(db.Integer, primary_key=True) slack_id = db.Column(db.String, unique=True) name = db.Column(db.String, unique=True) url = db.Column(db.String, nullable=True) public_key = db.Column(db.Text, nullable=True) created = db.Column(db.DateTime) def register_server(self, url): self.url = url
# Prevent WSGI from correcting the casing of the Location header BaseResponse.autocorrect_location_header = False # Find the correct template folder when running from a different location tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) app.debug = bool(os.environ.get('DEBUG')) # Setup Flask-Common. common = Common(app) # Send app errors to Sentry. if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) # Set up Bugsnag exception tracking, if desired. To use Bugsnag, install the # Bugsnag Python client with the command "pip install bugsnag", and set the # environment variable BUGSNAG_API_KEY. You can also optionally set # BUGSNAG_RELEASE_STAGE. if os.environ.get("BUGSNAG_API_KEY") is not None: try: import bugsnag import bugsnag.flask release_stage = os.environ.get("BUGSNAG_RELEASE_STAGE") or "production" bugsnag.configure(api_key=os.environ.get("BUGSNAG_API_KEY"), project_root=os.path.dirname( os.path.abspath(__file__)), use_ssl=True, release_stage=release_stage,
handler.setFormatter(logging.Formatter( '[%(asctime)s] %(levelname)s in %(module)s: %(message)s')) log_level = os.environ.get( 'FLASK_LOGGING_LEVEL', logging.getLevelName(logging.INFO)) handler.setLevel(log_level) flask_app.logger.addHandler(handler) flask_app.config['LOGGER_HANDLER_POLICY'] = 'never' flask_app.logger.setLevel(logging.DEBUG) app = connexion.FlaskApp(__name__) setup_logging(app.app) CORS(app.app) SENTRY_DSN = os.environ.get("SENTRY_DSN", "") sentry = Sentry(app.app, dsn=SENTRY_DSN, logging=True, level=logging.ERROR) app.app.logger.info('App initialized, ready to roll...') global scoring_status global scoring_object global s3_object if HPF_SCORING_REGION != "": if convert_string2bool_env(USE_CLOUD_SERVICES): s3_object = AmazonS3(bucket_name=AWS_S3_BUCKET_NAME, aws_access_key_id=AWS_S3_ACCESS_KEY_ID, aws_secret_access_key=AWS_S3_SECRET_ACCESS_KEY) s3_object.connect() app.scoring_object = HPFScoring(datastore=s3_object) else: app.scoring_object = HPFScoring(LocalDataStore("tests/test_data"))
""" import os from flask import Flask from werkzeug.contrib.fixers import ProxyFix from flask.ext.sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_envvar('LUNAPORT_AGENT_CFG') app.wsgi_app = ProxyFix(app.wsgi_app) # Fix for old proxyes db = SQLAlchemy(app) if os.environ.get('LUNAPORT_ENV') == 'production': sentry = Sentry(app, dsn=app.config.get('SENTRY_DSN')) sentry.init_app(app) from plugg_views import User, Job from helpers import auth_required user_ident = auth_required(User.UserIdent.as_view('user_ident')) user_view = auth_required(User.User.as_view('user')) job_view = auth_required(Test.Test.as_view('test')) app.add_url_rule('/api/v1.0/userident/', view_func=user_ident, methods=['GET']) app.add_url_rule('/api/v1.0/user/', defaults={'login': None}, view_func=user_view, methods=['GET']) app.add_url_rule('/api/v1.0/user/', view_func=user_view, methods=['POST']) app.add_url_rule('/api/v1.0/user/<login>', view_func=user_view, methods=['GET', 'PATCH']) app.add_url_rule('/api/v1.0/job/', defaults={'job_id': None}, view_func=test_view, methods=['GET'])
def setup_sentry(app, settings): sentry = Sentry(dsn=settings.SENTRY_DSN) sentry.init_app(app)
def create_app(): # Factory method to create the app prod_app_name = config.get('SERVER_APP') my_app = Flask(__name__) # set up uploading my_app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 # 1MB my_app.config['UPLOAD_FOLDER'] = tempfile.gettempdir() # Set up sentry logging my_app.config['SENTRY_USER_ATTRS'] = ['email'] try: sentry_dsn = config.get('SENTRY_DSN') Sentry(my_app, dsn=sentry_dsn, name=server_app) except ConfigException as e: logger.warn(e) # set up webpack if is_dev_mode(): manifest_path = '../build/manifest.json' else: manifest_path = '../server/static/gen/{}/manifest.json'.format( prod_app_name) webpack_config = { 'DEBUG': is_dev_mode(), 'WEBPACK_MANIFEST_PATH': manifest_path } # caching and CDN config my_app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 7 * 24 * 60 * 60 try: cdn_asset_url = config.get('ASSET_URL') webpack_config['WEBPACK_ASSETS_URL'] = cdn_asset_url logger.info("Asset pipeline: {}".format(cdn_asset_url)) except ConfigException: logger.info("Asset pipeline: no cdn") my_app.config.update(webpack_config) webpack.init_app(my_app) # set up mail sending try: if config.get('SMTP_ENABLED') == u'1': mail_config = { # @see https://pythonhosted.org/Flask-Mail/ 'MAIL_SERVER': config.get('SMTP_SERVER'), 'MAIL_PORT': int(config.get('SMTP_PORT')), 'MAIL_USE_SSL': config.get('SMTP_USE_SSL'), 'MAIL_USERNAME': config.get('SMTP_USER'), 'MAIL_PASSWORD': config.get('SMTP_PASS'), } my_app.config.update(mail_config) mail.init_app(my_app) logger.info(u'Mailing from {} via {}'.format( config.get('SMTP_USER'), config.get('SMTP_SERVER'))) else: logger.warn("Mail configured, but not enabled") except ConfigException as ce: logger.exception(ce) logger.warn("No mail configured") # set up user login cookie_domain = config.get('COOKIE_DOMAIN') my_app.config['SESSION_COOKIE_NAME'] = "mc_session" my_app.config['REMEMBER_COOKIE_NAME'] = "mc_remember_token" if cookie_domain != 'localhost': # can't set cookie domain on localhost my_app.config['SESSION_COOKIE_DOMAIN'] = cookie_domain my_app.config['REMEMBER_COOKIE_DOMAIN'] = cookie_domain # connect to the shared session storage my_app.session_interface = RedisSessionInterface( redis.StrictRedis.from_url(config.get('SESSION_REDIS_URL'))) return my_app
def create_app(mode, configs=None, log_level=None, **kwargs): # Allow configuration information to be specified with enviroment vars env_configs = {} for key in os.environ: if key.startswith('SIMPLECOIN_CONFIG'): env_configs[key] = os.environ[key] env_configs = [env_configs[value] for value in sorted(env_configs)] configs = ['defaults.toml'] + (env_configs or []) + (configs or []) if len(configs) == 1: print("Unable to start with only the default config values! {}" .format(configs)) exit(2) config_vars = {} for config in configs: if isinstance(config, basestring): if os.path.isabs(config): config_path = config else: config_path = os.path.join(root, config) config = open(config_path) updates = toml.loads(config.read()) toml.toml_merge_dict(config_vars, updates) # Initialize our flask application # ======================================================================= app = Flask(__name__, static_folder='../static', static_url_path='/static') app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates')) # Objectizes all configurations # ======================================================================= ConfigChecker(config_vars, app) # Setup logging # ======================================================================= del app.logger.handlers[0] app.logger.setLevel(logging.NOTSET) log_format = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s]: %(message)s') log_level = getattr(logging, str(log_level), app.config['log_level']) logger = logging.getLogger() logger.setLevel(log_level) handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(log_format) logger.addHandler(handler) # Handle optionally adding log file writers for each different run mode # ======================================================================= if mode == "manage" and app.config['manage_log_file']: hdlr = logging.FileHandler(app.config['manage_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) if mode == "scheduler" and app.config['scheduler_log_file']: hdlr = logging.FileHandler(app.config['scheduler_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) if mode == "webserver" and app.config['webserver_log_file']: hdlr = logging.FileHandler(app.config['webserver_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) logging.getLogger("gunicorn.access").setLevel(logging.WARN) logging.getLogger("requests.packages.urllib3.connectionpool").setLevel(logging.INFO) # Add the debug toolbar if we're in debug mode # ======================================================================= if app.config['DEBUG'] and mode == "webserver": # Log all stdout and stderr when in debug mode for convenience class LoggerWriter: def __init__(self, logger, level): self.logger = logger self.level = level def write(self, message): if message != '\n': self.logger.log(self.level, message) sys.stdout = LoggerWriter(app.logger, logging.DEBUG) sys.stderr = LoggerWriter(app.logger, logging.DEBUG) # Register the powerpool datastore + Cache # ======================================================================= db.init_app(app) def configure_redis(config): typ = config.pop('type') if typ == "mock_redis": from mockredis import mock_redis_client return mock_redis_client() return Redis(**config) cache_config = app.config.get('main_cache', dict(type='live')) cache_redis = configure_redis(cache_config) ds_config = app.config.get('redis_conn', dict(type='live')) ds_redis = configure_redis(ds_config) # Take advantage of the fact that werkzeug lets the host kwargs be a Redis # compatible object cache.init_app(app, config=dict(CACHE_TYPE='redis', CACHE_REDIS_HOST=cache_redis)) app.redis = ds_redis sentry = False if app.config.get('sentry'): try: from raven.contrib.flask import Sentry sentry = Sentry() except Exception: app.logger.error("Unable to initialize sentry!") # Helpful global vars # ======================================================================= app.SATOSHI = Decimal('0.00000001') app.MAX_DECIMALS = 28 # Configure app for running manage.py functions # ======================================================================= if mode == "manage" or mode == "webserver": # Dynamically add all the filters in the filters.py file for name, func in inspect.getmembers(filters, inspect.isfunction): app.jinja_env.filters[name] = func if mode == "manage": # Initialize the migration settings Migrate(app, db) # Disable for management mode if sentry: sentry = False # Configure app for serving web content # ======================================================================= elif mode == "webserver": # try and fetch the git version information try: output = subprocess.check_output("git show -s --format='%ci %h'", shell=True).strip().rsplit(" ", 1) app.config['hash'] = output[1] app.config['revdate'] = output[0] # celery won't work with this, so set some default except Exception: app.config['hash'] = '' app.config['revdate'] = '' app.logger.info("Starting up SimpleCoin!\n{}".format("=" * 100)) # Configure app for running scheduler.py functions + instantiate scheduler # ======================================================================= elif mode == "scheduler": if sentry and 'SENTRY_NAME' in app.config: app.config['SENTRY_NAME'] = app.config['SENTRY_NAME'] + "_scheduler" app.logger.info("=" * 80) app.logger.info("SimpleCoin cron scheduler starting up...") setproctitle.setproctitle("simplecoin_scheduler") # Make app accessible from out monkey patched code. Messy.... ThreadPool.app = app sched = Scheduler(standalone=True) # monkey patch the thread pool for flask contexts ThreadPool._old_run_jobs = ThreadPool._run_jobs def _run_jobs(self, core): self.app.logger.debug("Starting patched threadpool worker!") with self.app.app_context(): ThreadPool._old_run_jobs(self, core) ThreadPool._run_jobs = _run_jobs # All these tasks actually change the database, and shouldn't # be run by the staging server if not app.config.get('stage', False): sched.add_cron_job(sch.compress_slices, minute='0,15,30,45', second=35) # every minute at 55 seconds after the minute sched.add_cron_job(sch.generate_credits, second=55) sched.add_cron_job(sch.create_trade_req, args=("sell",), minute=1, hour="0,6,12,18") sched.add_cron_job(sch.create_trade_req, args=("buy",), minute=1, hour="0,6,12,18") # every minute at 55 seconds after the minute sched.add_cron_job(sch.collect_minutes, second=35) sched.add_cron_job(sch.collect_ppagent_data, second=40) # every five minutes 20 seconds after the minute sched.add_cron_job(sch.compress_minute, minute='0,5,10,15,20,25,30,35,40,45,50,55', second=20) # every hour 2.5 minutes after the hour sched.add_cron_job(sch.compress_five_minute, minute=2, second=30) # every minute 2 seconds after the minute sched.add_cron_job(sch.update_block_state, second=2) # every day sched.add_cron_job(sch.update_block_state, hour=0, second=0, minute=3) else: app.logger.info("Stage mode has been set in the configuration, not " "running scheduled database altering cron tasks") sched.add_cron_job(sch.update_online_workers, minute='0,5,10,15,20,25,30,35,40,45,50,55', second=30) sched.add_cron_job(sch.cache_user_donation, minute='0,15,30,45', second=15) sched.add_cron_job(sch.server_status, second=15) # every 15 minutes 2 seconds after the minute sched.add_cron_job(sch.leaderboard, minute='0,5,10,15,20,25,30,35,40,45,50,55', second=30) app.scheduler = sched if sentry: sentry.init_app(app, logging=True, level=logging.ERROR) # Route registration # ======================================================================= from . import views, models, api, rpc_views app.register_blueprint(views.main) app.register_blueprint(rpc_views.rpc_views) app.register_blueprint(api.api, url_prefix='/api') return app
handler.setFormatter( logging.Formatter( '[%(asctime)s] %(levelname)s in %(module)s: %(message)s')) log_level = os.environ.get('FLASK_LOGGING_LEVEL', logging.getLevelName(logging.WARNING)) handler.setLevel(log_level) flask_app.logger.addHandler(handler) flask_app.config['LOGGER_HANDLER_POLICY'] = 'never' flask_app.logger.setLevel(logging.DEBUG) app = create_app() setup_logging(app) app.wsgi_app = ProxyFix(app.wsgi_app) sentry = Sentry(app, dsn=config.SENTRY_DSN, logging=True, level=logging.ERROR) # Check whether schema is created or not # populate schema if not already done try: status, json_result = BayesianGraph.populate_schema() if status: app.logger.info("Ready to serve requests") else: app.logger.error(json_result) raise RuntimeError("Failed to setup graph schema") except Exception: sentry.captureException() raise RuntimeError("Failed to initialized graph schema") if __name__ == "__main__":
def create_app() -> Flask: app = Flask(__name__, static_folder='assets') app.config.from_pyfile('config.py') app.session_interface = RedisSessionInterface() app.wsgi_app = ProxyFix(app.wsgi_app) db.init_app(app) init_celery(app, celery) if app.config['SENTRY_DSN']: sentry = Sentry(app, dsn=app.config['SENTRY_DSN']) setup_templating(app) register_blueprints(app) @app.before_first_request def setup_logging(): if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.WARNING) @app.before_first_request def setup_db(): db.engine.pool._use_threadlocal = True @app.before_request def get_user_data(): try: g.user = {"id": session['steamid'], "nick": session['nick']} except KeyError: g.user = None @app.before_request def set_default_page_number(): try: g.page = int(request.args.get('p', 1)) except ValueError: g.page = 1 @app.before_request def generate_csrf_token(): if '_csrf_token' not in session: session['_csrf_token'] = binascii.b2a_hex(os.urandom(16)).decode() g.token = session['_csrf_token'] @app.context_processor def classes(): """Convenience function to return a list of TF2 classes.""" return { "classes": [ 'scout', 'soldier', 'pyro', 'demoman', 'heavyweapons', 'engineer', 'medic', 'sniper', 'spy' ] } @app.errorhandler(404) def page_not_found(e): """404 Page not found""" return redirect('/') @app.errorhandler(500) def server_error(e): """500 Internal server error""" return render_template('errors/500.html'), 500 return app
import requests import string from raven.contrib.flask import Sentry import logging # Initialize the Flask application app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.sqlite3' app.config['SECRET_KEY'] = "random string" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True sentry = Sentry( app, logging=True, level=logging.INFO, dsn= 'https://*****:*****@sentry.io/110511' ) db = SQLAlchemy(app) class stuff(db.Model): id = db.Column('user_id', db.Integer, primary_key=True) name = db.Column(db.String(100)) email = db.Column(db.String(100)) reqType = db.Column(db.String(100)) def __init__(self, name, email, reqType): self.name = name
# TODO, figure out how to load gevent monkey patch cleanly in production # try: # from gevent.monkey import patch_all # patch_all() # except ImportError: # print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if application.config.get('SENTRY_DSN'): from raven.contrib.flask import Sentry sentry = Sentry() sentry.init_app(application, dsn=application.config.get('SENTRY_DSN')) application.wsgi_app = ProxyFix(application.wsgi_app)
from __future__ import absolute_import from flask.ext.babel import Babel, gettext, ngettext from flask.ext.cache import Cache from flask.ext.mail import Mail from flask.ext.mongoengine import MongoEngine from flask.ext.redis import Redis from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import Security from flask.ext.social import Social from flask.ext.elasticsearch import ElasticSearch from flask.ext.s3 import FlaskS3 from raven.contrib.flask import Sentry def register_jinja_helpers(app): app.jinja_env.globals.update({'_': gettext, '__': ngettext}) babel = Babel() cache = Cache() db = SQLAlchemy() mail = Mail() mongo = MongoEngine() es = ElasticSearch() redis = Redis() security = Security() social = Social() s3 = FlaskS3() sentry = Sentry(logging=True)
print "%s: %s" % (threadName, time.ctime(time.time())) while True: msg = tg.getUpdate() if tg.waitNewMsg(msg) > 0: print("Ada Pesan") mobile_id, (mode, name, key, val) = tg.msgProcessing(msg) cmd_exec(mobile_id, mode, name, key, val) time.sleep(delay) #========================WEB SERVICE==================== app = Flask(__name__) app.logger.disabled = True sentry = Sentry( app, dsn= 'https://*****:*****@sentry.io/1267055' ) sentry.init_app(app) def simpleSync(parameter): db.updateField(parameter) return db.getValue() def methodExec(req, whois): mtd = req.args['method'] param = req.args.copy() del param['user'] del param['psw']
from flask import Flask, redirect, request, render_template, jsonify from models import User from timetable import TimetableResolver from timeline import Timeline from datetime import datetime import logging import json from raven.contrib.flask import Sentry app = Flask(__name__) sentry = Sentry(app, logging=True, level=logging.ERROR) @app.route('/settings/<user_token>', methods=["GET", "POST"]) def settings(user_token): return render_template('timeline_shutdown.html') @app.route('/') def index(): return "marhaba!" return redirect( 'https://apps.getpebble.com/applications/53ab84141d576ea3c30000d6') if __name__ == '__main__': app.run(debug=True, host="0.0.0.0")
def create_app(mode, configs=None, log_level=None, **kwargs): # Allow configuration information to be specified with enviroment vars env_configs = {} for key in os.environ: if key.startswith('SIMPLECOIN_CONFIG'): env_configs[key] = os.environ[key] env_configs = [env_configs[value] for value in sorted(env_configs)] configs = ['defaults.toml'] + (env_configs or []) + (configs or []) if len(configs) == 1: print("Unable to start with only the default config values! {}" .format(configs)) exit(2) config_vars = {} for config in configs: if isinstance(config, basestring): if os.path.isabs(config): config_path = config else: config_path = os.path.join(root, config) config = open(config_path) updates = toml.loads(config.read()) toml.toml_merge_dict(config_vars, updates) # Initialize our flask application # ======================================================================= app = Flask(__name__, static_folder='../static', static_url_path='/static') app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates')) # Objectizes all configurations # ======================================================================= ConfigChecker(config_vars, app) # Setup logging # ======================================================================= del app.logger.handlers[0] app.logger.setLevel(logging.NOTSET) log_format = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s]: %(message)s') log_level = getattr(logging, str(log_level), app.config['log_level']) logger = logging.getLogger() logger.setLevel(log_level) handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(log_format) logger.addHandler(handler) # Handle optionally adding log file writers for each different run mode # ======================================================================= if mode == "manage" and app.config['manage_log_file']: hdlr = logging.FileHandler(app.config['manage_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) if mode == "scheduler" and app.config['scheduler_log_file']: hdlr = logging.FileHandler(app.config['scheduler_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) if mode == "webserver" and app.config['webserver_log_file']: hdlr = logging.FileHandler(app.config['webserver_log_file']) hdlr.setFormatter(log_format) logger.addHandler(hdlr) logging.getLogger("gunicorn.access").setLevel(logging.WARN) logging.getLogger("requests.packages.urllib3.connectionpool").setLevel(logging.INFO) # Add the debug toolbar if we're in debug mode # ======================================================================= if app.config['DEBUG'] and mode == "webserver": # Log all stdout and stderr when in debug mode for convenience class LoggerWriter: def __init__(self, logger, level): self.logger = logger self.level = level def write(self, message): if message != '\n': self.logger.log(self.level, message) sys.stdout = LoggerWriter(app.logger, logging.DEBUG) sys.stderr = LoggerWriter(app.logger, logging.DEBUG) # Register the powerpool datastore + Cache # ======================================================================= db.init_app(app) babel.init_app(app) app.config['BABEL_DEFAULT_LOCALE'] = app.config.get('default_locale') def configure_redis(config): typ = config.pop('type') if typ == "mock_redis": from mockredis import mock_redis_client return mock_redis_client() return Redis(**config) cache_config = app.config.get('main_cache', dict(type='live')) cache_redis = configure_redis(cache_config) ds_config = app.config.get('redis_conn', dict(type='live')) ds_redis = configure_redis(ds_config) # Take advantage of the fact that werkzeug lets the host kwargs be a Redis # compatible object cache.init_app(app, config=dict(CACHE_TYPE='redis', CACHE_REDIS_HOST=cache_redis)) app.redis = ds_redis sentry = False if app.config.get('sentry'): try: from raven.contrib.flask import Sentry sentry = Sentry() except Exception: app.logger.error("Unable to initialize sentry!") # Helpful global vars # ======================================================================= app.SATOSHI = Decimal('0.00000001') app.MAX_DECIMALS = 28 # Configure app for running manage.py functions # ======================================================================= if mode == "manage" or mode == "webserver": # Dynamically add all the filters in the filters.py file for name, func in inspect.getmembers(filters, inspect.isfunction): app.jinja_env.filters[name] = func if mode == "manage": # Initialize the migration settings Migrate(app, db) # Disable for management mode if sentry: sentry = False # Configure app for serving web content # ======================================================================= elif mode == "webserver": # try and fetch the git version information try: output = subprocess.check_output("git show -s --format='%ci %h'", shell=True).strip().rsplit(" ", 1) app.config['hash'] = output[1] app.config['revdate'] = output[0] # celery won't work with this, so set some default except Exception: app.config['hash'] = '' app.config['revdate'] = '' app.logger.info("Starting up SimpleCoin!\n{}".format("=" * 100)) # Configure app for running scheduler.py functions + instantiate scheduler # ======================================================================= elif mode == "scheduler": if sentry and 'SENTRY_NAME' in app.config: app.config['SENTRY_NAME'] = app.config['SENTRY_NAME'] + "_scheduler" app.logger.info("=" * 80) app.logger.info("SimpleCoin cron scheduler starting up...") setproctitle.setproctitle("simplecoin_scheduler") sched = Scheduler(standalone=True) # monkey patch the scheduler to wrap each job call in its own flask # context. Kind of sloppy way to pass in the app context... Scheduler.app = app Scheduler._old_run_job = Scheduler._run_job def _run_job(self, *args, **kwargs): with self.app.app_context(): Scheduler._old_run_job(self, *args, **kwargs) Scheduler._run_job = _run_job stage_tasks = set(["cache_profitability", "leaderboard", "server_status", "update_network", "cache_user_donation", "update_online_workers"]) for task_config in app.config['tasks']: if not task_config.get('enabled', False): continue if app.config['stage'] and task_config['name'] not in stage_tasks: app.logger.debug( "Skipping scheduling {} because in stage mode!" .format(task_config['name'])) continue stripped_config = task_config.copy() del stripped_config['enabled'] task = getattr(sch, task_config['name']) sched.add_cron_job(task, **stripped_config) app.scheduler = sched if sentry: sentry.init_app(app, logging=True, level=logging.ERROR) # Route registration # ======================================================================= from . import views, models, api, rpc_views app.register_blueprint(views.main) app.register_blueprint(rpc_views.rpc_views) app.register_blueprint(api.api, url_prefix='/api') return app
from random import SystemRandom from flask_caching import Cache from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry random = SystemRandom() cache = Cache() login_manager = LoginManager() db = SQLAlchemy() sentry = Sentry()
def __init__(self, app): if app.config.get('SENTRY_DSN'): app.config.setdefault('SENTRY_NAME', app.config.get('SERVER_NAME')) self.sentry = Sentry(app, register_signal=False, wrap_wsgi=False) else: self.sentry = None
mimerender = mimerender.FlaskMimeRender(global_charset='utf-8') def render_json(**args): del args['template'] return simplejson.dumps(args) def render_html(**args): template = args['template'] del args['template'] return render_template(template, **args) app = Flask(__name__) sentry = Sentry(dsn='https://*****:*****@app.getsentry.com/1928') def calculate_arrivals(dt, cur_time): """Sometimes a bus is behind the clock, make sure it should 0mins then""" mins = (dt - cur_time).seconds / 60 # about 23 hours, this means bus is behind the clock if mins > 1400: return 0 return mins @app.route("/") def index(): from flask import request station = request.args.get('station', '')
def bind_sentry(self): self.raven = InMemoryClient() self.middleware = Sentry(self.app, client=self.raven)
try: APPLICATION_USERS = dict( [ user.split("::") for user in app.config["APPLICATION_USERS"] .encode("utf-8") .decode("unicode_escape") .split("\n") if user ] ) except AttributeError: APPLICATION_USERS = {} logger.warning("No application users configured.") sentry = Sentry(app, dsn=app.config.get("SENTRY_DSN", None)) auth = HTTPBasicAuth() if "CLAMD_SOCKET" in app.config: cd = clamd.ClamdUnixSocket(path=app.config["CLAMD_SOCKET"]) else: try: cd = clamd.ClamdNetworkSocket( host=app.config["CLAMD_HOST"], port=app.config["CLAMD_PORT"] ) except BaseException as exc: logger.exception(f"error bootstrapping clamd for network socket: {exc}") @auth.verify_password
from flask import Flask from raven.contrib.flask import Sentry import config from kizuna.support import Kizuna from .views import blueprint as views_blueprint DEV_INFO = Kizuna.read_dev_info('./.dev-info.json') app = Flask(__name__, static_folder=config.STATIC_DIR) app.secret_key = config.SECRET_KEY app.config['SENTRY_CONFIG'] = { 'dsn': config.SENTRY_URL, 'release': DEV_INFO.get('revision'), 'environment': config.KIZUNA_ENV } sentry = Sentry(app) if config.SENTRY_URL else None app.register_blueprint(views_blueprint)
def create_app(debug=False, dev=False): app = flask.Flask(__name__) app.debug = debug print("{0}App '{1}' created.{2}".format('\033[92m', __name__, '\033[0m')) # to remove later # Define custom filters into the Jinja2 environment. # Any filters defined in the jinja_env submodule are made available. # See: http://stackoverflow.com/questions/12288454/how-to-import-custom-jinja2-filters-from-another-file-and-using-flask custom_filters = { name: function for name, function in getmembers(jinja_filters) if isfunction(function) } app.jinja_env.filters.update(custom_filters) if app.debug == False: # ---------------------------------------------------------- # Set up getsentry.com logging - only use when in production # ---------------------------------------------------------- from raven.contrib.flask import Sentry dsn = 'https://*****:*****@app.getsentry.com/29096' app.config['SENTRY_DSN'] = dsn sentry = Sentry(app) # ---------------------------------------------------------- # -------------------------------------- # Configuration when running under uWSGI # -------------------------------------- try: import uwsgi app.use_x_sendfile = True except ImportError: # not running under uWSGI (and presumably, nginx) pass # Change the implementation of "decimal" to a C-based version (much! faster) try: import cdecimal sys.modules["decimal"] = cdecimal except ImportError: pass # no available # Determine which configuration file should be loaded based on which # server we are running on. This value is set in the uWSGI config file # for each server. if app.debug: #args['debug']: hostname = socket.gethostname() if (os.path.dirname(os.path.realpath(__file__))).find('utah.edu') >= 0: server_config_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'configuration_files', 'dev-utah.sdss.edu.cfg') # elif "sdss4-gateway.lco.cl" in hostname: # server_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'configuration_files', # 'sdss4-lcogateway.local.cfg') # elif "sdss-db4" in hostname or "sdss4-db" in hostname: # # determine if we are at LCO or APO # # by checking the public IP of the gateway machine # gatewayDN = socket.getfqdn("sdss-gateway") # if gatewayDN.endswith("lco.cl"): # server_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), # 'configuration_files', # 'sdss4-lcogateway.local.cfg') elif dev == False: server_config_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'configuration_files', 'sdss-db4.local.cfg') else: server_config_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'configuration_files', 'sdss-db4.dev.cfg') else: try: import uwsgi server_config_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'configuration_files', uwsgi.opt['flask-config-file']) # to set except ImportError: print_error( "Trying to run in production mode, but not running under uWSGI.\n" "You might try running again with the '--debug' flag.") sys.exit(1) print("Loading config file: {0}".format(server_config_file)) app.config.from_pyfile(server_config_file) #print(app.config) print("Server_name = {0}".format(app.config["SERVER_NAME"])) # Load Modules as needed #execfile(app.config['MODULES_INIT_SCRIPT'], globals()) #module('load', 'sdss_python_module/trunk') #print(os.environ['PYTHONPATH'].split(os.pathsep), sys.path, os.environ['SDSS_PYTHON_MODULE_DIR']) #import sdss #try: # import sdss #except ImportError: # print_error("The Python module 'sdss' could not be loaded.") # sys.exit(1) # This "with" is necessary to prevent exceptions of the form: # RuntimeError: working outside of application context with app.app_context(): from .model.database import db # ------------------- # Register blueprints # ------------------- from .controllers.index import index_page app.register_blueprint(index_page) return app
# Static content application = whitenoise.WhiteNoise( app.wsgi_app, root="website", autorefresh=settings.DEBUG, ) # Database db = SQLAlchemy() db.init_app(app) migrate = Migrate(app, db) # Sentry sentry = Sentry() sentry.init_app(app, app.config["SENTRY_DSN"]) # Register views app.register_blueprint(view_handler) # Meta def main(): # pragma: nocover from werkzeug.serving import run_simple run_simple( settings.HOST, settings.PORT, application, use_reloader=settings.DEBUG,
migrate = Migrate() cache = Cache() debug_toolbar = DebugToolbarExtension() webpack = Webpack() admin = PyXwordAdmin(db) limiter = Limiter(key_func=lambda: getattr(current_user, 'email', None), ) @limiter.request_filter def anonymous_whitelist(): return not current_user or current_user and current_user.is_anonymous sentry = Sentry( logging=True, level=logging.ERROR, ) markdown = Markdown() @login_manager.request_loader def load_user_from_request(request): # next, try to login using Basic Auth api_key = request.headers.get('Authorization') if api_key: api_key = api_key.replace('Basic ', '', 1) try: api_key = base64.b64decode(api_key).decode('utf-8')