class SchedulerApp(object): def __init__(self, args): super(SchedulerApp, self).__init__() self.args = args config = Config.getInstance() worker = config.getWorkerName(); self.mailer = SMTPHandler(config.getSmtpServer(), 'scheduler@%s' % worker, config.getSupportEmail(), "[indico_scheduler] Problem at %s" % worker) self.mailer.setLevel(logging.ERROR) def run(self): root_logger = logging.getLogger('') root_logger.addHandler(self.mailer) logger = logging.getLogger('daemon') try: Scheduler(multitask_mode = self.args.mode).run() return_val = 0 except base.SchedulerQuitException: logger.info("Daemon shut down successfully") return_val = 0 except: logger.exception("Daemon terminated for unknown reason ") return_val = -1 finally: return return_val
def configure_logging(app): """Configure file(info) and email(error) logging.""" import logging from logging.handlers import SMTPHandler # Set info level on logger, which might be overwritten by handers. # Suppress DEBUG messages. app.logger.setLevel(logging.INFO) info_log = os.path.join(app.config['LOG_FOLDER'], 'info.log') info_file_handler = logging.handlers.RotatingFileHandler( info_log, maxBytes=100000, backupCount=10) info_file_handler.setLevel(logging.INFO) info_file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(info_file_handler) if not app.config['DEBUG']: mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'], app.config['ADMINS'], 'O_ops... %s failed!' % app.config[ 'PROJECT'], (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(mail_handler)
def _add_logger(self, app): """ Creates SMTPHandler for logging errors to the specified admins list """ kwargs = dict() username = app.config.get('MAIL_USERNAME') password = app.config.get('MAIL_PASSWORD') if username and password: kwargs['credentials'] = (username, password) mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['DEFAULT_MAIL_SENDER'], app.config['ADMINS'], '[ERROR] Findevent got error', **kwargs) mail_handler.setFormatter(logging.Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) mail_handler.setLevel(logging.DEBUG) if not app.debug: app.logger.addHandler(mail_handler)
def configure_logging(app): import logging from logging.handlers import RotatingFileHandler, SMTPHandler app.logger.setLevel(logging.INFO) log_path = os.path.join(app.instance_path, 'info.log') file_handler = RotatingFileHandler(log_path, maxBytes=100000, backupCount=10) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) try: mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['MAIL_FROM'], app.config['ADMINS'], 'Error on %s' % app.config['SERVER_NAME'], (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']), ()) mail_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) except KeyError: pass
def init(app): if app.config.get('ERROR_EMAIL'): if app.debug: logging.getLogger().setLevel(logging.DEBUG) else: log_format = logging.Formatter(''' --- Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s %(message)s ''') # Send errors via email mail_handler = SMTPHandler('127.0.0.1', app.config.get('DEFAULT_MAIL_SENDER'), app.config.get('ERROR_EMAIL'), 'Error') mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(log_format) # Also continue to log errors to stderr stream_handler = logging.StreamHandler() stream_handler.setFormatter(log_format) app.logger.addHandler(stream_handler) app.logger.addHandler(mail_handler)
def __init__(self, fromaddr, toaddrs, mailhost='localhost', subject='%(line)s', send_empty_entries=False, flood_level=10, username=None, password=None, headers=None, template=None, charset='utf-8', content_type='text/plain'): SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject) self.subject_formatter = SubjectFormatter(subject) self.send_empty_entries = send_empty_entries self.flood_level = flood_level self.hour = self.now().hour self.sent = 0 self.username = username self.password = password self.headers = headers or {} self.template = template self.charset = charset self.content_type = content_type if not self.mailport: self.mailport = smtplib.SMTP_PORT
def init_error_logger_with_email_handler(app): """ Initialize a logger to send emails on error-level messages. Unhandled exceptions will now send an email message to app.config.ADMINS. """ if app.debug: return # Do not send error emails while developing # Retrieve email settings from app.config host = app.config['MAIL_SERVER'] port = app.config['MAIL_PORT'] from_addr = app.config['MAIL_DEFAULT_SENDER'] username = app.config['MAIL_USERNAME'] password = app.config['MAIL_PASSWORD'] secure = () if app.config.get('MAIL_USE_TLS') else None # Retrieve app settings from app.config to_addr_list = app.config['ADMINS'] subject = app.config.get('APP_SYSTEM_ERROR_SUBJECT_LINE', 'System Error') # Setup an SMTP mail handler for error-level messages mail_handler = SMTPHandler( mailhost=(host, port), # Mail host and port fromaddr=from_addr, # From address toaddrs=to_addr_list, # To address subject=subject, # Subject line credentials=(username, password), # Credentials secure=secure, ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def add_logging_handlers(self): if self.debug: return import logging from logging import Formatter, Filter from logging.handlers import RotatingFileHandler, SMTPHandler # Set general log level self.logger.setLevel(logging.INFO) # Inject additional log record fields class ContextFilter(Filter): def __init__(self, app): self.app = app def filter(self, record): record.app_name = self.app.name record.url = request.url record.ip = request.remote_addr if g.current_user: user = g.current_user record.user = '******' % (user.name, user.email_address) else: record.user = '******' return True self.logger.addFilter(ContextFilter(self)) # Add SMTP handler mail_handler = SMTPHandler( 'localhost', '*****@*****.**', self.config.get('ADMINS', []), 'SkyLines Error Report') mail_handler.setLevel(logging.ERROR) mail_formatter = Formatter(''' App: %(app_name)s Time: %(asctime)s URL: %(url)s IP: %(ip)s User: %(user)s Message: %(message)s ''') mail_handler.setFormatter(mail_formatter) self.logger.addHandler(mail_handler) # Add log file handler (if configured) path = self.config.get('LOGFILE') if path: file_handler = RotatingFileHandler(path, 'a', 10000, 4) file_handler.setLevel(logging.INFO) file_formatter = Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') file_handler.setFormatter(file_formatter) self.logger.addHandler(file_handler)
def configure_logging(app): '''Setup file(info) and email(error) logging''' # Return if in debug or testing mode if app.debug or app.testing: return import logging from logging.handlers import RotatingFileHandler, SMTPHandler # Set logging level to info app.logger.setLevel(logging.INFO) # Rotating File loggiing for (info) level debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG']) file_handler = RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(processName)s\t | %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(file_handler) # Mail logging haldler for (error) level mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'], app.config['SITE_ADMINS'], 'O_ops... %s failed!' % app.config['SITE_NAME'], (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter( '%(asctime)s %(processName)s\t | %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(mail_handler)
def init_app(self, app): handlers = [] filehandler = RotatingFileHandler(filename=app.config['LOG_FILE_LOC'], maxBytes=1000000, backupCount=5) formatter = logging.Formatter( "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s") filehandler.setLevel(logging.INFO) if app.config['TESTING']: filehandler.setLevel(logging.ERROR) filehandler.setFormatter(formatter) logging.basicConfig() handlers.append(filehandler) if not app.debug: mail_handler = SMTPHandler( (app.config['INTERNAL_MAILS_SERVER'], app.config['INTERNAL_MAILS_PORT']), app.config['INTERNAL_MAILS_SERVER_USERNAME'], app.config['NIGHTS_WATCH'], app.config.get('SERVER_ERROR_MAIL_SUBJECT', 'Server error'), credentials=(app.config['INTERNAL_MAILS_SERVER_USERNAME'], app.config['INTERNAL_MAILS_SERVER_PASSWORD']), secure=()) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(formatter) handlers.append(mail_handler) self.logging_queue_listener = QueueListener( self.logging_queue, *handlers) app.logger.addHandler(self.logging_queue_handler)
def create_app(name, config_filename): app = Flask(name, template_folder='app/templates', static_folder='app/static') app.config.from_pyfile(config_filename) from app.models import db db.init_app(app) db.app = app from app.sms import mail mail.init_app(app) mail.app = app from app.views import main app.register_blueprint(main) #TODO: Secure admin view admin = Admin() admin.init_app(app) admin.app = app admin.add_view(ModelView(User, db.session)) if not (app.debug or app.config.get('LOGGING_DISABLE', False)): import logging from logging import Formatter from logging.handlers import SMTPHandler, RotatingFileHandler mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'], fromaddr=app.config['LOGGING_SENDER'], toaddrs=app.config['ADMINS'], subject='dci-notify Server Error', credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) file_handler = RotatingFileHandler(filename=os.path.join(basedir, 'app.log'), maxBytes=1048756, backupCount=5) mail_handler.setLevel(logging.ERROR) file_handler.setLevel(logging.WARNING) mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) app.logger.addHandler(mail_handler) app.logger.addHandler(file_handler) return app
def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, send_empty_entries=False, flood_level=None): SMTPHandler.__init__(self, mailhost, fromaddr, toaddrs, subject, credentials=credentials, secure=secure) self.subject_formatter = SubjectFormatter(subject) self.send_empty_entries = send_empty_entries self.flood_level = flood_level self.hour = now().hour self.sent = 0
def init_app(cls, app): Config.init_app(app) import logging from logging.handlers import SMTPHandler from logging import StreamHandler # email errors to admin credentials = None secure = None if getattr(cls, "MAIL_USERNAME", None) is not None: credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD) if getattr(cls, "MAIL_USE_TLS", None): secure = () mail_handler = SMTPHandler( mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT), fromaddr=cls.MAIL_SENDER, toaddrs=[cls.ADMIN], subject=cls.MAIL_SUBJECT_PREFIX + u"Application Error", credentials=credentials, secure=secure, ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) # log to stderr file_handler = StreamHandler() file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) # handle proxy server headers from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app)
def init(level=None, logger=getLogger(), handler=StreamHandler(), development=True): logging.basicConfig(level=level, datefmt='%m-%d %H:%M') logger = logging.getLogger() if (os.isatty(sys.stdout.fileno()) and not sys.platform.startswith('win')): fmt = ANSIFormatter() else: fmt = TextFormatter() handler.setFormatter(fmt) logger.addHandler(handler) if level: logger.setLevel(level) if not development: logger.info("Setting up email handler for production-mode.") fmt = EmailFormatter() smtpHandler = SMTPHandler('127.0.0.1', '*****@*****.**', ['*****@*****.**'], 'ALERT docfu error!') smtpHandler.setFormatter(fmt) smtpHandler.setLevel(logging.ERROR) logger.addHandler(smtpHandler) return logger
def init_app(cls, app): Config.init_app(app) # send error log to admin'email import logging from logging.handlers import SMTPHandler # log to stderr from logging import StreamHandler file_handler = StreamHandler() file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) secure = None if getattr(cls, 'MAIL_USERNAME', None) is not None: credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD) if getattr(cls, 'MAIL_USER_TLS', None): secure = () mail_hanlder = SMTPHandler( mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT), fromaddr=cls.ZBLOG_MAIL_SENDER, toaddrs=[cls.ZBLOG_ADMIN], subject=cls.ZBLOG_MAIL_SUBJECT_PREFIX + 'Application Error', credentials=credentials, secure=secure ) mail_hanlder.setLevel(logging.ERROR) app.logger.addHandler(mail_hanlder)
def exception_handler(app): """ Register 0 or more exception handlers (mutates the app passed in). :param app: Flask application instance :return: None """ # This will not execute when debug is set to True. mail_handler = SMTPHandler((app.config.get('MAIL_SERVER'), app.config.get('MAIL_PORT')), '*****@*****.**', [app.config.get('MAIL_USERNAME')], '[Exception handler] A 5xx was thrown', (app.config.get('MAIL_USERNAME'), app.config.get('MAIL_PASSWORD')), secure=()) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter(''' Time: %(asctime)s Message type: %(levelname)s Message: %(message)s ''')) app.logger.addHandler(mail_handler) return None
def init_app(cls, app): Config.init_app(app) import logging from app.log import ContextFilter from logging import Formatter from logging.handlers import SMTPHandler, RotatingFileHandler credentials = None secure = None if getattr(cls, 'MAIL_USERNAME', None) is not None: credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD) if getattr(cls, 'MAIL_USE_TLS', None): secure = () mail_handler = SMTPHandler( mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT), fromaddr=cls.MAIL_SENDER, toaddrs=[cls.MAIL_FEEDBACK_ADDRESS], subject=cls.MAIL_SUBJECT_PREFIX + ' Application Error', credentials=credentials, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) context_provider = ContextFilter() app.logger.addFilter(context_provider) audit_log_handler = RotatingFileHandler(cls.AUDIT_LOG, maxBytes=131072, backupCount=5) audit_log_handler.setLevel(logging.INFO) audit_log_handler.setFormatter(Formatter('%(asctime)s [%(levelname)s] %(ip)s %(admin_username)s[%(admin_id)d]: %(blueprint)s-%(funcName)s %(message)s')) app.logger.addHandler(audit_log_handler) app.logger.setLevel(logging.INFO)
def create_app(config={}): app = Flask("spindle") app.config.from_object(default_settings) app.config.from_envvar("SPINDLE_SETTINGS", silent=True) app.config.update(config) config = { "schemas": app.config.get("SCHEMAS"), "database": app.config.get("DATABASE_URI"), "elastic_host": app.config.get("ELASTICSEARCH_HOST"), "elastic_index": app.config.get("ELASTICSEARCH_INDEX"), } app.loom_config = Config(config) load_local_schema(app.loom_config.resolver) app.loom_config.setup() assets.init_app(app) oauth.init_app(app) if not app.debug and app.config.get("MAIL_ADMINS"): app_name = app.config.get("APP_NAME") credentials = app.config.get("MAIL_CREDENTIALS", ()) mail_handler = SMTPHandler( app.config.get("MAIL_HOST"), app.config.get("MAIL_FROM"), app.config.get("MAIL_ADMINS"), "%s crash report" % app_name, credentials=credentials, secure=(), ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) return app
def config_logging(app): info_log = os.path.join(app.root_path, app.config['INFO_LOG']) error_log = os.path.join(app.root_path, app.config['ERROR_LOG']) formatter = logging.Formatter( '''%(asctime)s %(levelname)s [in %(pathname)s:%(lineno)d]: %(message)s ''') if app.config['TESTING'] == False: error_handler = RotatingFileHandler(error_log, maxBytes=102400, backupCount=10) error_handler.setLevel(logging.ERROR) error_handler.setFormatter(formatter) app.logger.addHandler(error_handler) if app.debug == True: info_handler = RotatingFileHandler(info_log, maxBytes=102400, backupCount=10) info_handler.setLevel(logging.INFO) info_handler.setFormatter(formatter) app.logger.addHandler(info_handler) else: from logging.handlers import SMTPHandler mail_handler = SMTPHandler(mailhost=app.config['MAILHOST'], fromaddr=app.config['FROMADDR'], toaddrs=app.config['TOADDR'], subject='Server Error', credentials=(app.config['FROMADDR'], app.config['PASSWORD'])) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def ErrorMail(): if not app.debug: import logging from logging.handlers import SMTPHandler credentials=None if MAIL_USERNAME or MAIL_PASSWORD: credentials=(MAIL_USERNAME,MAIL_PASSWORD) mail_handler = SMTPHandler(MAIL_PORT, 'no-reply@' + MAIL_SERVER, ADMINS, 'microblg failture',credentials) from logging import Formatter mail_handler.setFormatter(Formatter(''' Messagetype: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def init(app): """ Initialize logging for the application, (only if its not in debug mode) """ if not app.debug: from logging import Formatter from logging.handlers import SMTPHandler, TimedRotatingFileHandler # File handler file_formatter = Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') file_handler = TimedRotatingFileHandler(app.config['LOG_FILE_NAME'], when='midnight', backupCount=31) file_handler.setFormatter(file_formatter) file_handler.setLevel(app.config['LOG_FILE_LEVEL']) app.logger.addHandler(file_handler) # Email handler mail_formatter = Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''') mail_handler = SMTPHandler(app.config['LOG_EMAIL_SERVER'], app.config['LOG_EMAIL_SENDER'], app.config['ADMIN_EMAILS'].split(','), '[%s] Error' % app.config['HOST_DOMAIN']) mail_handler.setFormatter(mail_formatter) mail_handler.setLevel(app.config['LOG_EMAIL_LEVEL']) app.logger.addHandler(mail_handler)
def register_loggers(app): if not (app.debug or app.config.get('LOGGING_DISABLE', False)): import logging from logging import Formatter from logging.handlers import SMTPHandler mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'], fromaddr=app.config['LOGGING_SENDER'], toaddrs=app.config['ADMINS'], subject='CorpScores Server Error', credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) app.logger.addHandler(mail_handler) return None
def register_error_logger(app): if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler( ('smtp.gmail.com','587'), '[Sistema Impresion] ' + date.today().strftime("%d-%m-%Y"), ADMINS, 'Error!', ('*****@*****.**', '*****'), tuple() ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''') )
def configure_app(): '''Configure app loading in order from: [annotator.settings_default] [annotator.settings_local] annotator.cfg # in app root dir config file specified by env var ANNOTATOR_CONFIG ''' # app.config.from_object('annotator.settings_default') # app.config.from_object('annotator.settings_local') here = os.path.dirname(os.path.abspath( __file__ )) # parent directory config_path = os.path.join(os.path.dirname(here), 'annotator.cfg') if os.path.exists(config_path): app.config.from_pyfile(config_path) if 'ANNOTATOR_CONFIG' in os.environ: app.config.from_envvar('ANNOTATOR_CONFIG') ADMINS = app.config.get('ADMINS', '') if not app.debug and ADMINS: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', '*****@*****.**', ADMINS, 'annotator error') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def configure_logging(app): if app.debug or app.testing: return mail_handler = SMTPHandler( app.config["MAIL_SERVER"], "*****@*****.**", app.config["ADMINS"], "application error", (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]), ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]") debug_log = os.path.join(app.root_path, app.config["DEBUG_LOG"]) debug_file_handler = RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) debug_file_handler.setLevel(logging.DEBUG) debug_file_handler.setFormatter(formatter) app.logger.addHandler(debug_file_handler) error_log = os.path.join(app.root_path, app.config["ERROR_LOG"]) error_file_handler = RotatingFileHandler(error_log, maxBytes=100000, backupCount=10) error_file_handler.setLevel(logging.ERROR) error_file_handler.setFormatter(formatter) app.logger.addHandler(error_file_handler)
def configure_app(config_file): app.config.from_pyfile(config_file) mysql_db.set_config( app.config['DB_HOST'], app.config['DB_USERNAME'], app.config['DB_PASSWORD'], app.config['DB_DATABASE'] ) commonsense.set_config( app.config['CS_SERVER'], app.config['CS_VERBOSITY'], ) # Setup logging if not app.config['DEBUG']: import logging from logging.handlers import SMTPHandler # log everything >= DEBUG to a file file_handler = logging.FileHandler("/var/log/AuthAPI/tma-api.log") file_handler.setLevel(logging.DEBUG) app.logger.addHandler(file_handler) # log errors by email email_handler = SMTPHandler( '127.0.0.1', "ADMIN_EMAIL", app.config['ADMINS'], "Exception in AuthAPI") email_handler.setLevel(logging.ERROR) app.logger.addHandler(email_handler)
def configure_logging(app): """Configure file(info) and email(error) logging.""" if app.debug or app.testing: # skip debug and test mode. return import logging from logging.handlers import RotatingFileHandler, SMTPHandler # Set info level on logger, which might be overwritten by handers. app.logger.setLevel(logging.INFO) debug_log = os.path.join(app.root_path, app.config["DEBUG_LOG"]) file_handler = logging.handlers.RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]") ) app.logger.addHandler(file_handler) ADMINS = ["*****@*****.**"] mail_handler = SMTPHandler( app.config["MAIL_SERVER"], app.config["MAIL_USERNAME"], ADMINS, "O_ops... %s failed!" % PROJECT, (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]), ) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]") ) app.logger.addHandler(mail_handler)
def configure_logging(app): """Configure file(info) and email(error) logging.""" if app.debug or app.testing: # skip debug and test mode. return import logging from logging.handlers import SMTPHandler # Set info level on logger, which might be overwritten by handers. app.logger.setLevel(logging.INFO) debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG']) file_handler = logging.handlers.RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(file_handler) ADMINS = ['*****@*****.**'] mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'], ADMINS, 'Error: Satellite', (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(logging.ERROR) mail_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(mail_handler)
def configure_logging(app): """Configure file(info) and email(error) logging.""" if app.debug or app.testing: # Skip debug and test mode. Just check standard output. return # Set info level on logger, which might be overwritten by handers. # Suppress DEBUG messages. app.logger.setLevel(INFO) info_file_handler = StreamHandler() info_file_handler.setLevel(INFO) info_file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(info_file_handler) # Testing # app.logger.info("testing info.") # app.logger.warn("testing warn.") # app.logger.error("testing error.") mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'], app.config['ADMINS'], 'O_ops... %s failed!' % app.config['PROJECT'], (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])) mail_handler.setLevel(ERROR) mail_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]') ) app.logger.addHandler(mail_handler)
def init_logging(app): """Initialize app error logging :type app: flask.Flask :param app: The application to configure. """ if app.debug: return ADMINS = ['*****@*****.**'] import logging from logging.handlers import SMTPHandler credentials = None secure = None if app.config.get("MAIL_USERNAME") is not None: credentials = (app.config["MAIL_USERNAME"], app.config.get("MAIL_PASSWORD")) if app.config.get("MAIL_USE_TLS") is not None or app.config.get("MAIL_USE_SSL") is not None: secure = tuple() mail_handler = SMTPHandler(app.config["MAIL_SERVER"], app.config["ERROR_SENDER"], app.config["ERROR_ADDRESS"], app.config["ERROR_SUBJECT"], credentials=credentials, secure=secure) mail_handler.setLevel(logging.ERROR) if app.config.get("ERROR_FORMAT") is not None: mail_handler.setFormatter(Formatter(app.config["ERROR_FORMAT"])) for log in (getLogger('sqlalchemy'), app.logger): log.addHandler(mail_handler)
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ if app.config['ELASTICSEARCH_URL'] else None app.redis = Redis.from_url(app.config['REDIS_URL']) app.task_queue = rq.Queue('rvlsnr-tasks', connection=app.redis) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix='/api') if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='FlaskApp Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/flaskApp.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('RVLSNR startup') return app
from app import routes, models, errors if not my_app.debug: if my_app.config['MAIL_SERVER']: auth = None if my_app.config['MAIL_USERNAME'] or my_app.config['MAIL_PASSWORD']: auth = (my_app.config['MAIL_USERNAME'], my_app.config['MAIL_PASSWORD']) secure = None if my_app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler(mailhost=(my_app.config['MAIL_SERVER'], my_app.config['MAIL_PORT']), fromaddr='no-reply@' + my_app.config['MAIL_SERVER'], toaddrs=my_app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) my_app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message) s [in %(pathname)s:%(lineno)d]' ))
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) configure_uploads(app, images) patch_request_class(app, size=33554432) app.r = Redis.from_url(app.config['REDIS_URL']) app.q = Queue('climb_dest-tasks', connection=app.r) # start worker: rq worker climb_dest-tasks from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.user import bp as user_bp app.register_blueprint(user_bp) from app.destinations import bp as destinations_bp app.register_blueprint(destinations_bp) from app.currency import bp as currency_bp app.register_blueprint(currency_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='climb_dest Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/climb_dest.log', maxBytes=10240, backupCount=10) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Climbit startup') return app
app.job_logger = logging.getLogger('jobs') app.job_logger.setLevel(logging.INFO) if not app.debug: # Use SMTPHandler only in production if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr=app.config['MAIL_DEFAULT_SENDER'], toaddrs=app.config['MAIL_DEFAULT_RECIPIENT'], subject='EasyWP Cron Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.error_logger.addHandler(mail_handler) # Use rotating error log in production and development. It is especially useful in # an environment like Passenger which streams error log into Apache log. error_file_handler = RotatingFileHandler(os.path.join(logs_dir, 'error_log'), maxBytes=10240, backupCount=10) error_file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]', time_format))
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) mail.init_app(app) moment.init_app(app) bootstrap.init_app(app) migrate.init_app(app, db) login.init_app(app) editormd.init_app(app) # Blueprint registration from app.errors import bp as error_bp app.register_blueprint(error_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.post import bp as post_bp app.register_blueprint(post_bp) # searching mechanism with elastic search app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ if app.config['ELASTICSEARCH_URL'] else None if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Microblog startup') return app
elif app.config["EVERYONE_IS_ADMIN"]: flask.g.user = bunch.Bunch({ "username": "******", "email": "admin@localhost", "admin": True }) if not app.debug: credentials = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) mail_handler = SMTPHandler( (app.config['MAIL_SERVER'], app.config['MAIL_PORT']), app.config['MAIL_FROM'], app.config['ADMINS'], 'webfaf exception', credentials) mail_handler.setLevel(logging.ERROR) rate_limiter = RateLimitingFilter(app.config['THROTTLING_RATE'], app.config['THROTTLING_TIMEFRAME'], app.config['THROTTLING_BURST']) mail_handler.addFilter(rate_limiter) app.logger.addHandler(mail_handler) @app.errorhandler(403) def forbidden(error): return flask.render_template("403.html"), 403
from geocron.web import application from geocron import settings if not settings.DEBUG: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler(settings.SMTP_HOST, '*****@*****.**', settings.ADMINS, 'Our application failed', (settings.SMTP_USER, settings.SMTP_PASSWORD)) mail_handler.setLevel(logging.ERROR) application.logger.addHandler(mail_handler) from logging.handlers import WatchedFileHandler file_handler = WatchedFileHandler("/tmp/geocron.log") file_handler.setLevel(logging.WARNING) application.logger.addHandler(file_handler) application.secret_key = settings.SECRET_KEY applications = { '/': application, }
from flask import Flask, request, Response, jsonify, render_template, flash, redirect, g, url_for, session, abort, json from MySQLdb import connect app = Flask(__name__) app.debug = True import json, os, time ADMINS = ['*****@*****.**'] if app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', '*****@*****.**', ADMINS, 'YourApplication Failed') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'db'): g.db = connect(host='sql.mit.edu', db='lucid+sofar', user='******', passwd='KO01BAHjiKGkZ') return g.db @app.teardown_appcontext def close_db(error):
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) app.config['SECRET_KEY'] = 'secret!' app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = '587' app.config['MAIL_USE_TLS'] = '1' app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' socketio.init_app(app) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) # moment.init_app(app) # babel.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix='/api') from app.games import bp as games_bp app.register_blueprint(games_bp, url_prefix='/games') app.config['OAUTH_CREDENTIALS'] = { 'facebook': { 'id': '160139164703343', 'secret': '4a005ebc42acab187de54ba991ef3ea6' }, 'google': { 'id': '160139164703343', 'secret': '4a005ebc42acab187de54ba991ef3ea6' } } if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: #Transport Layer Security secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='CodeGame Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/codegame.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.addHandler(logging.INFO) app.logger.info('CodeGame startup') return app
lm = LoginManager() lm.init_app(app) lm.login_view = 'login' oid = OpenID(app, os.path.join(basedir, 'tmp')) from app import views, models if not app.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, 'microblog failure', credentials) mail_handler.setLevel(logging.INFO) app.logger.addHandler(mail_handler) if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler('tmp/microblog.log', 'a', 1 * 1024 * 1024, 10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO)
from config import SQLALCHEMY_DATABASE_URI, ADMINS, MAIL_PASSWORD, MAIL_PORT, MAIL_SERVER, MAIL_USERNAME, basedir from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import os app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True) db_session = scoped_session(sessionmaker(bind=engine), scopefunc=_app_ctx_stack.__ident_func__) from app import views if not app.debug: import logging from logging.handlers import SMTPHandler, RotatingFileHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, 'confiscated failure', credentials, ()) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) file_handler = RotatingFileHandler(os.path.join(basedir, 'tmp/error.log'), 'a', 1 * 1024 * 1024, 10) file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('confiscated startup')
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) # Register errors Blueprint with main application # The import here avoids circular dependencies that may arise # if it's imported higher up in the code from app.errors import bp as errors_bp app.register_blueprint(errors_bp) # Register auth Blueprint with main application from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') # Register main Blueprint with main application from app.main import bp as main_bp app.register_blueprint(main_bp) # Handle errors if not app.debug and not app.testing: # Send email on error # Severity ERROR if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) # Write error logs # Severity INFO or higher if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=30) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Microblog startup') return app
def create_app(config_class: Type[Config] = Config) -> Flask: app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) app.redis = Redis.from_url(app.config['REDIS_URL']) app.task_queue = rq.Queue('microblog-tasks', connection=app.redis) if app.config['ELASTICSEARCH_URL']: app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) else: app.elasticsearch = None from app.auth import bp as auth_bp from app.main import bp as main_bp from app.errors import bp as errors_bp app.register_blueprint(main_bp, url_prefix='/') app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(errors_bp) print('blueprints loaded') if not app.debug and not app.testing: if current_app.config['MAIL_SERVER']: auth = None if current_app.config['MAIL_USERNAME'] or current_app.config[ 'MAIL_PASSWORD']: auth = (current_app.config['MAIL_USERNAME'], current_app.config['MAIL_PASSWORD']) if current_app.config['MAIL_USE_TLS']: secure: Union[None, Tuple[str], Tuple[str, str]] = ('', ) else: secure = None mail_handler = SMTPHandler( mailhost=(current_app.config['MAIL_SERVER'], current_app.config['MAIL_PORT']), fromaddr=current_app.config['ADMINS'][0], toaddrs=current_app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.INFO) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Microblog startup') return app
from flask_moment import Moment # creating app that is being exported app = Flask(__name__) # special variable -> name of the module app.config.from_object(Config) # passing our object as the configuration db = SQLAlchemy(app) # creating alchemy instance migrate = Migrate(app, db) #creating migration intance login = LoginManager(app) #initializing flask-login login.login_view = "login" # <- function name | for @login_requried moment = Moment(app) # geting the routes from the routes file to execute them from app import routes, models, errors if not app.debug: if app.config['MAIL_SERVER']: # se for configurado informações de email auth = None if app.config["MAIL_USERNAME"] or app.config["MAIL_PASSWORD"]: auth = (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]) secure = None if app.config["MAIL_USE_TLS"]: secure = () mail_handler = SMTPHandler( mailhost=(app.config["MAIL_SERVER"], app.config["MAIL_PORT"]), fromaddr="no-reply@" + app.config["MAIL_SERVER"], toaddrs=app.config["ADMINS"], subject="FlaskBlog Failure", credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
def create_app(config_class=Config): logging.getLogger('elasticsearch').setLevel(logging.DEBUG) logging.getLogger('urllib3').setLevel(logging.DEBUG) tracer = logging.getLogger('elasticsearch.trace') tracer.setLevel(logging.DEBUG) tracer.addHandler(logging.FileHandler('indexer.log')) app = Flask(__name__, static_url_path="/static") app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) app.elasticsearch = Elasticsearch(app.config['ELASTICSEARCH_URL']) \ if app.config['ELASTICSEARCH_URL'] else None celery.conf.update(BROKER_URL=app.config['REDIS_URL'], CELERY_RESULT_BACKEND=app.config['REDIS_URL']) from app.errors import bp as errors_bp # noqa: F401 app.register_blueprint(errors_bp) from app.auth import bp as auth_bp # noqa: F401 app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp # noqa: F401 app.register_blueprint(main_bp) from app.api import bp as api_bp # noqa: F401 app.register_blueprint(api_bp, url_prefix='/api') socketio.init_app(app, async_mode='eventlet', message_queue=app.config['REDIS_URL']) if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config["MAIL_PASSWORD"]: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = False if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config["MAIL_SERVER"], toaddrs=app.config['ADMINS'], subject="My Blog failure", credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/myblog.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s \ [in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('MyBlog startup') return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) app.temp_lock = threading.Lock() def temporary_cleanup(): temp_folder = os.path.join(app.root_path, 'static', 'temp') app.temp_lock.acquire() for filename in os.listdir(temp_folder): file_path = os.path.join(temp_folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) app.temp_lock.release() db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) scheduler = BackgroundScheduler(daemon=True) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) scheduler.add_job(temporary_cleanup, trigger='interval', minutes=60) scheduler.start() if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler(mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='theassignmentautomation@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Assignment Automation Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/assignmentautomation.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Assignment Automation startup') return app
console.setLevel(logging.ERROR) logger.addHandler(console) if SLACK_TOKEN and SLACK_CHANNEL: from pyslack import SlackHandler handler = SlackHandler(SLACK_TOKEN, SLACK_CHANNEL, username='******') formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(name)s (%(process)d): %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) if os.environ.get('SENDGRID_USERNAME'): from logging.handlers import SMTPHandler mail_handler = SMTPHandler('smtp.sendgrid.net', '*****@*****.**', ['*****@*****.**'], 'State of the Union Heroku Exception', credentials=(os.environ['SENDGRID_USERNAME'], os.environ['SENDGRID_PASSWORD'])) mail_handler.setLevel(logging.ERROR) logger.addHandler(mail_handler) mail_handler.setFormatter( logging.Formatter("""\ Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s""")) wsgi = WSGIHandler(middleware)
def create_app(config_class=DefaultConfig): ''' Application factory ''' app = Flask(__name__) # https://flask.palletsprojects.com/en/1.1.x/config/ app.config.from_object(config_class) app.config.from_envvar('FLASK_CONFIG', silent=True) app.logger.info('%s loading', app.config['APP_NAME']) app.logger.info("Connect to database %s", app.config['SQLALCHEMY_DATABASE_URI']) app.logger.info("ProjectRegistry URL: %s", app.config['PROJECTREGISTRY']) app.logger.info("Xpress URL: %s", app.config['XPRESS_RESTAPI_ENDPOINT']) app.logger.info("BaseSpace Endpoint: %s", app.config['BASESPACE_ENDPOINT']) app.logger.info("BaseSpace Token: %s", mask(app.config['BASESPACE_TOKEN'])) app.logger.info("SevenBridges Token: %s", mask(app.config['SB_AUTH_TOKEN'])) app.logger.info("AWS Batch Job Definition: %s", app.config['JOB_DEFINITION']) app.logger.info("AWS Batch Job Queue: %s", app.config['JOB_QUEUE']) app.logger.info("scRNASeq Lambda Function: %s", app.config['SCRNASEQ_LAMBDA_FN']) DB.init_app(app) MIGRATE.init_app(app, DB) BASESPACE.init_app(app) BOTO3.init_app(app) LOGINMANAGER.init_app(app) LOGINMANAGER.login_view = 'user.login' SEVENBRIDGES.init_app(app) if not app.debug and not app.testing: # If FLASK_LOG_FILE and FLASK_LOG_LEVEL env vars defined, set up logging. if 'FLASK_LOG_FILE' in app.config and 'FLASK_LOG_LEVEL' in app.config and \ app.config['FLASK_LOG_FILE'] is not None: app.logger.info("Setting up file logging to %s", app.config['FLASK_LOG_FILE']) file_handler = TimedRotatingFileHandler( app.config['FLASK_LOG_FILE'], when='midnight', backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(app.config['FLASK_LOG_LEVEL']) app.logger.addHandler(file_handler) # Send emails on critical errors if 'MAIL_SERVER' in app.config and app.config[ 'MAIL_SERVER'] is not None: auth = None app.logger.info("Setting up email logger") if 'MAIL_USERNAME' in app.config or 'MAIL_PASSWORD' in app.config: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if 'MAIL_USE_TLS' in app.config: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['MAIL_ADMINS'], subject='%s Failure' % app.config['APP_NAME'], credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) from app.blueprints import main_bp app.register_blueprint(main_bp) from app.api import BLUEPRINT as api_bp app.register_blueprint(api_bp) from app.blueprints.user import BP as user_bp app.register_blueprint(user_bp) from app.blueprints import basespace_bp app.register_blueprint(basespace_bp) from app.blueprints import aws_batch_bp app.register_blueprint(aws_batch_bp) app.logger.info('%s loaded.', app.config['APP_NAME']) return app
gi = geoip2.database.Reader('/usr/share/GeoIP/GeoLite2-Country.mmdb') class RequestFormatter(logging.Formatter): def format(self, record): s = logging.Formatter.format(self, record) try: return '[%s] [%s] [%s %s] ' % (self.formatTime( record), request.remote_addr, request.method, request.path) + s except: return '[%s] [SYS] ' % self.formatTime(record) + s if not app.debug: mail_handler = SMTPHandler(app.config['SMTP_SERVER'], app.config['APP_EMAIL'], app.config['ADMIN_EMAIL'], 'LetterBomb ERROR') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) handler = logging.FileHandler( os.path.join(app.root_path, 'log', 'info.log')) handler.setLevel(logging.INFO) handler.setFormatter(RequestFormatter()) app.logger.addHandler(handler) app.logger.setLevel(logging.INFO) app.logger.warning('Starting...') def region():
app.config['MAIL_USERNAME'] = config["mail_user"] app.config['MAIL_PASSWORD'] = config["mail_pass"] app.config['MAIL_DEFAULT_SENDER'] = config["mail_from"] app.config['MAIL_USE_TLS'] = True app.config['MAIL_USE_SSL'] = False mail = Mail(app) # Setup Storage app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.db" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Logging log_handler_mail = SMTPHandler(config["mail_host"].split(":"), config["mail_from"], config["admins"], '[faucet] Error', (config["mail_user"], config["mail_pass"])) log_handler_mail.setFormatter(logging.Formatter( "Message type: %(levelname)s\n" + "Location: %(pathname)s:%(lineno)d\n" + "Module: %(module)s\n" + "Function: %(funcName)s\n" + "Time: %(asctime)s\n" + "\n" + "Message:\n" + "\n" + "%(message)s\n" )) log_handler_mail.setLevel(logging.WARN) log_handler_stdout = logging.StreamHandler(sys.stdout)
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) app.app_context().push() db.create_all() migrate.init_app(app, db) login.init_app(app) mail.init_app(app) # bootstrap.init_app(app) # moment.init_app(app) babel.init_app(app) # search engine app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ if app.config['ELASTICSEARCH_URL'] else None print(app.config['ELASTICSEARCH_URL']) print(app.elasticsearch) # erros blueprint from app.errors import bp as errors_bp app.register_blueprint(errors_bp) # auth blueplint from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') # the main of the app from app.main import bp as main_bp app.register_blueprint(main_bp) if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) # logs if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/mur2.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Mur2 startup') # configuration the Flask-upload configure_uploads(app, photos) return app
APP.jinja_env.trim_blocks = True APP.jinja_env.lstrip_blocks = True # set up FAS APP.config.from_object('progit.default_config') if 'PROGIT_CONFIG' in os.environ: APP.config.from_envvar('PROGIT_CONFIG') FAS = FAS(APP) SESSION = progit.lib.create_session(APP.config['DB_URL']) # Set up the logger ## Send emails for big exception mail_handler = SMTPHandler( APP.config.get('SMTP_SERVER', '127.0.0.1'), '*****@*****.**', APP.config.get('MAIL_ADMIN', APP.config['EMAIL_ERROR']), 'Progit error') mail_handler.setFormatter( logging.Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) mail_handler.setLevel(logging.ERROR) if not APP.debug:
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) csrf.init_app(app) db.init_app(app) with app.app_context(): if db.engine.url.drivername == 'sqlite': migrate.init_app(app, db, render_as_batch=True) else: migrate.init_app(app, db) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ if app.config['ELASTICSEARCH_URL'] else None app.redis = Redis.from_url(app.config['REDIS_URL']) app.task_queue = rq.Queue('op-tasks', connection=app.redis) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='op app Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if app.config['LOG_TO_STDOUT']: stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) app.logger.addHandler(stream_handler) else: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/dashboard.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('op fintech startup') return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) moment.init_app(app) cors.init_app(app, resources={r"/api/*": {"origins": "*"}}) csrf.init_app(app) resize.init_app(app) app.jinja_env.cache = {} socketio.init_app(app) # babel.init_app(app) # app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \ # if app.config['ELASTICSEARCH_URL'] else None # app.redis = Redis.from_url(app.config['REDIS_URL']) # app.task_queue = rq.Queue('microblog-tasks', connection=app.redis) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix='/api') from app.admin import bp as admin_bp app.register_blueprint(admin_bp, url_prefix='/admin') from app.gallery import bp as gallery_bp app.register_blueprint(gallery_bp, url_prefix='/content') if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='MHS Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if app.config['LOG_TO_STDOUT']: stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) app.logger.addHandler(stream_handler) else: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/MHS.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('MHS startup') return app
def create_app(test_config=None): print('Py version {}.{}'.format(*sys.version_info[:2])) print('Flask version', flask__version__) # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(DATABASE=os.path.join(app.instance_path, 'flask1.db'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # Error Handling in Flask - https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling if not app.debug: auth = (app.config['MAIL_USU'], app.config['MAIL_PASS']) secure = () mail_handler = SMTPHandler(mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr=app.config['MAIL_FROM'], toaddrs=app.config['MAIL_TO_ERRORS'], subject='Cogosys - Error', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/errors.log', maxBytes=51200, backupCount=5) file_handler.setFormatter( logging.Formatter( '\n%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) # guardar static path static_path = str(os.path.abspath(__file__ + "/../static")) print('Usando static path =', static_path) app._static_path = static_path ###### DB from . import db db.init_app(app) ###### LOGIN from . import login login.init_app(app) ###### ROUTES (y TEMPLATES) from . import routes app.register_blueprint(routes.bp) from .views import menu_bps for menu_bp in menu_bps: app.register_blueprint(menu_bp) ###### REQUESTS LOGGER if not os.path.exists('logs'): os.mkdir('logs') app._request_logger = logging.getLogger("requests") app._request_logger.setLevel(logging.DEBUG) req_file_handler = RotatingFileHandler('logs/requests.log', maxBytes=102400, backupCount=5) req_file_handler.setFormatter( logging.Formatter('[%(asctime)s] %(message)s')) req_file_handler.setLevel(logging.DEBUG) app._request_logger.addHandler(req_file_handler) @app.before_request def log_request_info(): from flask import request r = request if r.endpoint != None and r.endpoint != 'static': log_vals = [] if len(r.values): for key, val in r.values.items(): if key == 'password': sanit_val = '*' * len(val) else: sanit_val = val.replace('"', r'\"') log_vals.append(f'{key}="{sanit_val}"') app._request_logger.debug( '%s, %s, %s, (%s), %s, %s', r.method, r.path, r.endpoint, ';'.join(log_vals), r.remote_addr, r.headers.get('USER_AGENT', '--Sin USER_AGENT--')) return app
from .momentjs import momentjs app.jinja_env.globals['momentjs'] = momentjs from app import routes, model, errors if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='NoteOnTheGo Server Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if app.config['LOG_TO_STDOUT']: stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) app.logger.addHandler(stream_handler) else: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/note-on-the-go.log', maxBytes=10240,
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) app.config['UPLOADED_PHOTOS_DEST'] = 'static/img/' configure_uploads(app, photos) app.config['UPLOADED_ARCHIVES_DEST'] = 'static/arch/' configure_uploads(app, archives) # create the folders when setting up your app app.config['IMG_PICKED'] = 'static/picked/' # create the folders when setting up your app app.config['TO_DOWNLOAD'] = 'static/to-download/' #app.config['UPLOADED_FILES_DEST'] = 'static/files/<username>' #configure_uploads(app, files) app.redis = Redis.from_url(app.config['REDIS_URL']) app.task_queue = rq.Queue('pypick-tasks', connection=app.redis) db.init_app(app) #db.create_all() ###new edits migrate.init_app(app, db) #manager.init_app(app) #manager.add_command('db', MigrateCommand) ###end new edits login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Pypick Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/pypick.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in % (pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('pyGemPick web app starting up!') return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) app.config['SESSION_REDIS'] = redis_client # plugin db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) cache.init_app(app, config=app.config['CACHE_CONFIG']) redis_client.init_app(app) limiter.init_app(app) Session(app) app.task_queue = rq.Queue(app.config['WORKER_NAME'], connection=redis_client) # blueprint from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.main import bp as main_bp app.register_blueprint(main_bp) from app.tinyurl import bp as tinyurl_bp app.register_blueprint(tinyurl_bp) if not app.debug and not app.testing: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if app.config['LOG_TO_STDOUT']: stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) app.logger.addHandler(stream_handler) else: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter('%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Demo blog startup') return app
import logging from logging.handlers import SMTPHandler if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = SMTPHandler( # отправка лога с ошибкой mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Blog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) @app.shell_context_processor # создание контекста оболочки, который добавляет экземпляр и модели бд в сеанс оболочки def make_shell_context(): return {'db': db, 'User': User, 'Post': Post} if __name__ == '__main__': # app.run(host='localhost', port=5000) # app.run(host='10.55.130.176', port=5000) # app.run(host='10.55.130.54', port=5000)
from flaskext.babel import Babel from flask_mail import Mail __author__ = "Sean Whalen" __copyright__ = "Copyright (C) 2012 %s" % __author__ __license__ = "MIT" __version__ = "0.4.2" # Ignore flask case # pylint: disable=C0103 app = Flask(__name__) app.config.from_pyfile("config.py") if not app.debug: mail_handler = SMTPHandler(app.config['MAIL_SERVER'], app.config['DEFAULT_MAIL_SENDER'], [app.config['ADMIN_MAIL']], 'D*C Notifications Failed', credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']), secure=()) mail_handler.setLevel(ERROR) app.logger.addHandler(mail_handler) db = SQLAlchemy(app) babel = Babel(app) mail = Mail(app) import dcnotify.views