当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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?

网友答案:

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)))
分享给朋友:
您可能感兴趣的文章:
随机阅读: