Пример #1
0
 def resolve_mould_visualization(self,
                                 info,
                                 mouldId=None,
                                 fromTime=None,
                                 toTime=None,
                                 interval="20s"):
     influx = InfluxDB()
     query = 'SELECT mean("cycleTime") AS "cycleTime", sum("powerConsumption") AS "powerConsumption" FROM "mqtt_consumer" WHERE time > \'{fromTime}\' AND time < \'{toTime}\' AND "mouldId"=\'{mouldId}\' GROUP BY time({interval}) FILL(0)'.format(
         mouldId=mouldId,
         fromTime=fromTime.isoformat(),
         toTime=toTime.isoformat(),
         interval=interval)
     result = influx.query(query)
     return list(result.get_points(measurement='mqtt_consumer', tags=None))
Пример #2
0
class RecordView(FlaskView):
    influx_db = InfluxDB()
    record_schema = RecordSchema()

    @staticmethod
    def _transform_datapoints(hostname: str, timestamp: str,
                              data: dict) -> list:
        datapoints = []

        for k, v in data.items():
            if k in ['entities', 'players']:

                for sk, sv in v.items():
                    datapoints.append({
                        "measurement": k,
                        "time": timestamp,
                        "tags": {
                            "host": hostname,
                            "world": sk
                        },
                        "fields": {
                            k: sv
                        }
                    })

            else:
                datapoints.append({
                    "measurement": k,
                    "time": timestamp,
                    "tags": {
                        "host": hostname
                    },
                    "fields": v
                })

        return datapoints

    @jwt_required
    @json_required
    def post(self):

        hostname = get_jwt_identity()
        timestamp = datetime.now(get_localzone()).isoformat()

        try:
            record = self.record_schema.load(request.get_json())
        except ValidationError as e:
            abort(422, str(e))

        self.influx_db.connection.write_points(
            self._transform_datapoints(hostname, timestamp, record))

        return jsonify(record), 201
Пример #3
0
from mycodo.databases.models import PID
from mycodo.devices.camera import camera_record
from mycodo.mycodo_client import DaemonControl
from mycodo.mycodo_flask.routes_authentication import clear_cookie_auth
from mycodo.mycodo_flask.utils import utils_general
from mycodo.utils.influx import query_string
from mycodo.utils.system_pi import assure_path_exists
from mycodo.utils.system_pi import str_is_float

blueprint = Blueprint('routes_general',
                      __name__,
                      static_folder='../static',
                      template_folder='../templates')

logger = logging.getLogger(__name__)
influx_db = InfluxDB()

limiter = Limiter()


@blueprint.route('/')
def home():
    """Load the default landing page"""
    if flask_login.current_user.is_authenticated:
        if flask_login.current_user.landing_page == 'live':
            return redirect(url_for('routes_page.page_live'))
        elif flask_login.current_user.landing_page == 'dashboard':
            return redirect(url_for('routes_page.page_dashboard'))
        return redirect(url_for('routes_page.page_live'))
    return clear_cookie_auth()
Пример #4
0
from flask import send_file
from flask_influxdb import InfluxDB
from influxdb import InfluxDBClient

from config import COLUMNS
from config import PI_VERSIONS
from config import STATS
from config import VERSION
from config import countries
from secret_variables import INFLUXDB_DATABASE
from secret_variables import OWN_IDS

tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))

app = Flask(__name__, template_folder=tmpl_dir)
influx_db = InfluxDB(app)

gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)

app.config['INFLUXDB_DATABASE'] = INFLUXDB_DATABASE


@app.route('/', methods=('GET', 'POST'))
def default_page():
    timer = timeit.default_timer()
    timeframe = '3'
    sort_type = 'Mycodo_revision'
    if request.method == 'POST':
        sort_type = request.form['sorttype']
Пример #5
0
class RecordView(FlaskView):

    influx_db = InfluxDB()
    record_schema = RecordSchema()

    @staticmethod
    def _convert_cpu_to_influx_datapoints(hostname: str, timestamp: str,
                                          cpu_percentages: list) -> list:

        datapoints = []

        for i in range(len(cpu_percentages)):
            datapoints.append({
                "measurement": "cpu_utilization",
                "time": timestamp,
                "tags": {
                    "host": hostname,
                    "core": i
                },
                "fields": {
                    "utilized_percent": cpu_percentages[i]
                }
            })

        return datapoints

    @staticmethod
    def _convert_memory_to_influx_datapoints(hostname: str, timestamp: str,
                                             memory_usage: dict) -> dict:
        return {
            "measurement": "memory_utilization",
            "time": timestamp,
            "tags": {
                "host": hostname
            },
            "fields": {
                "used_bytes": memory_usage['used_bytes'],
                "used_percent": memory_usage['used_percent']
            }
        }

    @staticmethod
    def _convert_filesystem_to_influx_datapoints(hostname: str, timestamp: str,
                                                 filesystems: dict) -> list:

        datapoints = []

        for filesystem, utilization in filesystems.items():
            datapoints.append({
                "measurement": "filesystem_utilization",
                "time": timestamp,
                "tags": {
                    "host": hostname,
                    "filesystem": filesystem
                },
                "fields": {
                    "used_bytes": utilization['used_bytes'],
                    "used_percent": utilization['used_percent']
                }
            })

        return datapoints

    @staticmethod
    def _convert_netio_to_influx_datapoints(hostname: str, timestamp: str,
                                            netio: dict) -> list:

        datapoints = []

        for dev, stats in netio.items():
            datapoints.append({
                "measurement": "netio",
                "time": timestamp,
                "tags": {
                    "host": hostname,
                    "dev": dev
                },
                "fields": {
                    "rx_rate_bytes": stats['rx_rate_bytes'],
                    "tx_rate_bytes": stats['tx_rate_bytes']
                }
            })

        return datapoints

    @jwt_required
    @json_required
    def post(self):

        hostname = get_jwt_identity()
        timestamp = datetime.now(get_localzone()).isoformat()

        try:
            record = self.record_schema.load(request.get_json())
        except (ValidationError) as e:
            abort(422, str(e))

        datapoints = []

        if 'cpu' in record.keys():
            datapoints.extend(
                self._convert_cpu_to_influx_datapoints(hostname, timestamp,
                                                       record['cpu']))

        if 'memory' in record.keys():
            datapoints.append(
                self._convert_memory_to_influx_datapoints(
                    hostname, timestamp, record['memory']))

        if 'filesystem' in record.keys():
            datapoints.extend(
                self._convert_filesystem_to_influx_datapoints(
                    hostname, timestamp, record['filesystem']))

        if 'netio' in record.keys():
            datapoints.extend(
                self._convert_netio_to_influx_datapoints(
                    hostname, timestamp, record['netio']))

        conn = self.influx_db.connection
        conn.write_points(datapoints)

        return jsonify(record), 201
Пример #6
0
# from . import users
# from . import oauth2

# from .users import User
# from .oauth2 import OAuth2Token

__all__ = [
    # oauth2,
]

from flask_mongoengine import MongoEngine
from flask_influxdb import InfluxDB

db = MongoEngine()
influxdb = InfluxDB()


def init_db(app):
    db.init_app(app)
    influxdb.init_app(app=app)


def init_mongoengine(settings):
    import mongoengine as me
    dbname = settings.get('MONGODB_DB')
    host = settings.get('MONGODB_HOST', 'localhost')
    port = int(settings.get('MONGODB_PORT', '27017'))
    username = settings.get('MONGODB_USERNAME', '')
    password = settings.get('MONGODB_PASSWORD', '')

    me.connect(db=dbname,
Пример #7
0
from flask_influxdb import InfluxDB

app = Flask(__name__)

INFLUXDB_HOST = 'influxdb'
INFLUXDB_DATABASE = 'lr2db'
INFLUXDB_PORT = '8086'

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'csv'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['INFLUXDB_HOST'] = INFLUXDB_HOST
app.config['INFLUXDB_DATABASE'] = INFLUXDB_DATABASE
app.config['INFLUXDB_PORT'] = INFLUXDB_PORT

influx_db = InfluxDB(app=app)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


#@app.route('/')
#def hello_world():
#    return render_template('index.html')


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
from flask_influxdb import InfluxDB
from flask import Flask, render_template

influx = InfluxDB()


def create_app(config: str) -> Flask:
    app = Flask(__name__)
    app.config.from_pyfile(config)

    influx.init_app(app)

    @app.route('/newdb/<dbname>')
    def newdb(dbname):
        influx.database.create(dbname)
        return ''

    @app.route('/example')
    def write():
        data_measurement = 'testseries'
        data_tags = ['time', 'value_1', 'value_2', 'value_3']

        influx.database.switch(database='test')
        tabledata = influx.query('SELECT {0} from {1}'.format(
            ', '.join(data_tags), data_measurement))

        data_points = []
        for measurement, tags in tabledata.keys():
            for p in tabledata.get_points(measurement=measurement, tags=tags):
                data_points.append(p)
Пример #9
0
app.config['JWT_SECRET_KEY'] = 'super-secret'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 86400
jwt = JWTManager(app)
@jwt.user_claims_loader
def add_claims_to_access_token(user):
    roles = []
    for role in user.roles:
        roles.append(role.name)
    return {"roles": roles}
app.debug = True
db = MongoEngine()
cors = CORS(app)

app.config['INFLUXDB_HOST'] = 'localhost'
app.config['INFLUXDB_PORT'] = '8086'
# app.config['INFLUXDB_USER'] = 
# app.config['INFLUXDB_PASSWORD'] = 
app.config['INFLUXDB_DATABASE'] = 'fabbrica'
influx_db = InfluxDB()

if __name__ == '__main__':
    db.init_app(app)
    influx_db.init_app(app=app)
    from schema import schema
    app.add_url_rule(
        '/graphql',
        view_func=GraphQLView.as_view('graphql',
        schema=schema, graphiql=True))
        
    init_db()
    app.run()
# InfluxDB (SensorDB) Instance for App
from flask_influxdb import InfluxDB

influx = InfluxDB()
Пример #11
0
from flask import Flask, request, Response, render_template
from flask_influxdb import InfluxDB
import json

app = Flask(__name__)
app.config.from_pyfile("config.cfg")
influxdb = InfluxDB(app=app)


@app.route('/webhook', methods=['POST'])
def respond():
    if request.headers.getlist("X-Forwarded-For"):
        ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
        ip = request.remote_addr

    if not request.content_type.startswith('application/json'):
        print(request.content_type)
        print(request.data)
        return Response(status=400)
    else:
        print("OK:", request.json, "|", ip, sep=" ")

        influxdb.write_points([{
            "fields": {
                "close": float(request.json['close'])
            },
            "tags": {
                "action": request.json['action'],
                "source": request.json['source'],
                "ticker": request.json['ticker'],