Exemplo n.º 1
0
def make_app(set_path=False, testing=False, config_override=None):
    # If you are reading this code and wonder how to access the app:
    # >>> from flask import current_app as app
    # This only works while inside an application context but you really shouldn't have any
    # reason to access it outside this method without being inside an application context.
    # When set_path is enabled, SERVER_NAME and APPLICATION_ROOT are set according to BaseURL
    # so URLs can be generated without an app context, e.g. in the snms shell

    if _app_ctx_stack.top:
        Logger.get('flask').warn(
            'make_app({}) called within app context, using existing app:\n{}'.
            format(set_path, '\n'.join(traceback.format_stack())))
        return _app_ctx_stack.top.app
    app = SnmsFlask('snms', static_folder=None, template_folder='templates')
    app.config['TESTING'] = testing
    app.config['SNMS'] = load_config(only_defaults=testing,
                                     override=config_override)
    configure_app(app, set_path)

    with app.app_context():
        configure_db(app)
        configure_tsdb(app)
        celery.init_app(app)
        options.init_app(app)
        setup_request_stats(app)
        add_blueprints(app)
        Logger.init_app(app)
        configure_mqtt(app)
        plugin_engine.init_app(app, Logger.get('plugins'))
        if not plugin_engine.load_plugins(app):
            raise Exception('Could not load some plugins: {}'.format(', '.join(
                plugin_engine.get_failed_plugins(app))))
        add_plugin_blueprints(app)
        signals.app_created.send(app)

        from flask_cors import CORS
        CORS(app, resources=r'/*', allow_headers='*')
    return app
    def logger(self):
        from snms.core.logger import Logger

        logger = Logger.get('db')
        logger.setLevel(logging.DEBUG)
        return logger
# Authors: Gopal Lal
#
# License: www.baseapp.com/swarmsense-whitelabel-iot-platoform
"""Controller for OTA Firmware"""
import os

import werkzeug
from flask import request, send_file
from flask_restful import Resource, reqparse
from snms.core.db import db
from snms.core.logger import Logger
from snms.modules.ota import Firmware, FirmwareRequestSchema
from snms.utils import get_filters
from snms.modules.sensors import Sensor
# from snms.web.util import send_file
_LOGGER = Logger.get()


class FirmwareListResource(Resource):
    def get(self):
        order_by, order_type, offset, limit, filter = get_filters(
            in_request=request)
        firmwares = Firmware.query
        if 'q' in filter.keys():
            firmwares = firmwares.filter(
                Firmware.name.ilike("%{}%".format(filter['q'])))
        if 'type' in filter.keys():
            firmwares = firmwares.filter(Firmware.type == filter['type'])
        if order_by in [
                'id', 'sensor_type', 'name', 'version', 'created_at',
                'is_deployed'
Exemplo n.º 4
0
# This file is part of SwarmSense IoT Platform
# Copyright (c) 2018, Baseapp Systems And Softwares Private Limited
# Authors: Gopal Lal
#
# License: www.baseapp.com/swarmsense-whitelabel-iot-platoform

import json
import datetime
from flask import current_app
from snms.core.logger import Logger
from snms.core.mqtt import mqtt, MQTT_LOG_DEBUG
from snms.core.mqtt.consumer import EmqpConsumer
from snms.core.config import config
from snms.modules.sensors.controllers import post_sensor_value_with_uid

_LOGGER = Logger.get(__name__)

USE_RABBITMQ = True


def mqtt_cmd(args):
    if USE_RABBITMQ:
        host = config.MQTT_BROKER_URL
        username = config.MQTT_USERNAME
        password = config.MQTT_PASSWORD
        amqp_url = "amqp://{}:{}@{}:5672".format(username, password, host)
        consumer = EmqpConsumer(amqp_url, mqtt.app)
        consumer.run()
        return
    else:
        # mqtt.init_app(current_app)
def apply_db_loggers(app):
    if not app.debug or getattr(db, '_loggers_applied', False):
        return
    db._loggers_applied = True
    from snms.core.logger import Logger

    logger = Logger.get('db')
    logger.setLevel(logging.DEBUG)

    @listens_for(Engine, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        if not g.get('req_start_sent'):
            g.req_start_sent = True
            logger.debug('Request started', extra={'sql_log_type': 'start_request',
                                                   'repl': app.config.get('REPL'),
                                                   'req_verb': request.method if has_request_context() else None,
                                                   'req_path': request.path if has_request_context() else None,
                                                   'req_url': request.url if has_request_context() else None})

        context._query_start_time = time.time()
        source_line = _get_sql_line()
        if source_line:
            log_msg = 'Start Query:\n    {0[file]}:{0[line]} {0[function]}\n\n{1}\n{2}'.format(
                source_line,
                _prettify_sql(statement),
                _prettify_params(parameters) if parameters else ''
            ).rstrip()
        else:
            # UPDATEs can't be traced back to their source since they are executed only on flush
            log_msg = 'Start Query:\n{0}\n{1}'.format(
                _prettify_sql(statement),
                _prettify_params(parameters) if parameters else ''
            ).rstrip()
        # psycopg2._psycopg.Binary objects are extremely weird and don't work in isinstance checks
        if hasattr(parameters, 'iteritems'):
            parameters = {k: _fix_param(v) for k, v in parameters.items()}
        else:
            parameters = tuple(_fix_param(v) for v in parameters)
        logger.debug(log_msg,
                     extra={'sql_log_type': 'start',
                            'req_path': request.path if has_request_context() else None,
                            'sql_source': source_line['items'] if source_line else None,
                            'sql_statement': statement,
                            'sql_verb': statement.split()[0],
                            'sql_params': parameters})

    @listens_for(Engine, 'after_cursor_execute')
    def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        total = time.time() - context._query_start_time
        source_line = _get_sql_line()
        source = source_line['items'] if source_line else None
        logger.debug('Query complete; total time: %s', total, extra={'sql_log_type': 'end',
                                                                     'req_path': (request.path
                                                                                  if has_request_context()
                                                                                  else None),
                                                                     'sql_source': source,
                                                                     'sql_duration': total,
                                                                     'sql_verb': statement.split()[0]})

    @appcontext_tearing_down.connect_via(app)
    @request_tearing_down.connect_via(app)
    def on_tearing_down(sender, **kwargs):
        if g.get('req_end_sent'):
            return
        g.req_end_sent = True
        stats = get_request_stats()
        if not stats['query_count']:
            return
        logger.debug('Request finished', extra={'sql_log_type': 'end_request',
                                                'sql_query_count': stats['query_count'],
                                                'repl': app.config.get('REPL'),
                                                'req_verb': request.method if has_request_context() else None,
                                                'req_url': request.url if has_request_context() else None,
                                                'req_path': request.path if has_request_context() else None,
                                                'req_duration': stats['req_duration'],
                                                'req_query_duration': stats['query_duration']})
Exemplo n.º 6
0
# This file is part of SwarmSense IoT Platform
# Copyright (c) 2018, Baseapp Systems And Softwares Private Limited
# Authors: Gopal Lal
#
# License: www.baseapp.com/swarmsense-whitelabel-iot-platoform

from __future__ import unicode_literals

from snms.core import signals
from snms.core.logger import Logger
from snms.modules.users.models.users import User
from snms.modules.users.models.settings import UserMetaData

__all__ = ('User', 'UserMetaData')

logger = Logger.get('users')


@signals.users.registered.connect
def _registered(user, identity, from_moderation, **kwargs):
    logger.info("User registered")
Exemplo n.º 7
0
def handle_exception(exception):
    Logger.get('wsgi').exception(exception.message or 'WSGI Exception')
    if current_app.debug:
        raise
    raise
 def logger(cls):
     return Logger.get('plugin.{}'.format(cls.name))