Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use Jsonify in Flask websocket

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

I am replacing some ajax requests with websockets because it is needed for performances and network issues. I installed Flask-WebSocket with pip in my env. Now I get an error:

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 websockets python files 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 launch my application using this command:

gunicorn -k flask_sockets.worker app:app

Here is my __init__.py in 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?

like image 544
Depado Avatar asked Jan 08 '14 12:01

Depado


1 Answers

In flask

jsonify is a response that sends a response with data in json format.

you can do it like this:

import json

then change ws.send to:

ws.send(json.dumps(dict(cpu=cpu, ram=ram, disk=disk)))
like image 78
Syed Habib M Avatar answered Sep 30 '22 05:09

Syed Habib M