Cannot use Jsonify in websocket flash drive

Jsonify doesn't seem to work out of application context, is there a workaround?

I am replacing some ajax requests with websockets because it is necessary for performance and network problems. I installed Flask-WebSocket with pip in my env. Now I get the error message:

RuntimeError: working outside of application context

The skeleton of my application is as follows:

app/
β”œβ”€β”€ forms
β”œβ”€β”€ static
β”‚   β”œβ”€β”€ css
β”‚   β”œβ”€β”€ img
β”‚   β”‚   └── DefaultIcon
β”‚   β”‚       β”œβ”€β”€ eps
β”‚   β”‚       └── png
β”‚   └── js
β”œβ”€β”€ templates
β”œβ”€β”€ ups
└── views

The python files for websockets are located in views / ajax.py:

# -*- coding: utf-8 -*-

# OS Imports
import time

# Flask Imports
from flask import jsonify
from .. import sockets
from app.functions import get_cpu_load, get_disk_usage, get_vmem

# Local Imports
from app import app
from app.views.constants import info, globalsettings

@sockets.route('/_system')
def _system(ws):
    """
    Returns the system informations, JSON Format
    CPU, RAM, and Disk Usage
    """
    while True:
        message = ws.receive()
        if message == "update":
            cpu = round(get_cpu_load())
            ram = round(get_vmem())
            disk = round(get_disk_usage())
            ws.send(jsonify(cpu=cpu, ram=ram, disk=disk)

I run my application using the following command:

gunicorn -k flask_sockets.worker app:app

Here is mine __init__.pyin the app / folder:

# -*- coding: utf-8 -*-
from flask import Flask
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)
app.config.from_object('config')
from app import views as application

Why doesn't jsonify work, what can I use instead?

+4
source share
1 answer

In the flask

jsonify - , json.

:

import json

ws.send :

ws.send(json.dumps(dict(cpu=cpu, ram=ram, disk=disk)))
+7

All Articles