Django socketio process

20 Views Asked by At

I'm dealing with a little problem that I need to solve. I have an application in Django and I need a websocket, but I don't like Django channels, so I created a socket server in Flask and I'm trying to connect Django to it, by creating middleware that when called starts a process that sends messages through the process what it has in the queue

But either the shared variable doesn't work or the process itself doesn't work properly. Please if you have any advice or solution write also how to terminate the process with socket when django terminates

This is my code:

socket.py
---
import socketio
import json
from project.settings import SOCKET_CONFIG, MANAGER
from multiprocessing import Process

sio = socketio.Client()

class Socket:

    queue = MANAGER.list()

    def __init__(self, get_response):
        self.get_response = get_response
        thread = Process(target=Socket.process_loop, args=())
        thread.start()

    def __call__(self, request):
        return self.get_response(request)

    @staticmethod
    def process_loop():
        sio.connect('http://{}:{}'.format(SOCKET_CONFIG["host"],SOCKET_CONFIG["port"]))
        while True:
            try:
                import time
                time.sleep(1)
                data = Socket.queue.pop(0)
                sio.emit('message', data)
            except BaseException as e: print(e)

settings.py
---
import os, subprocess
from multiprocessing import Process, Manager
MANAGER = Manager()
SOCKET_CONFIG={
    "host":"localhost",
    "port":8001
}
MIDDLEWARE = [
...
'_middlewares.socket.Socket'
]
...
0

There are 0 best solutions below