Question: Django & Socket Server: Can I add socket server instance to "memory"?

Question

Django & Socket Server: Can I add socket server instance to "memory"?

Answers 0
Added at 2017-10-07 11:10
Tags
Question

I'm working with:

  • Django 1.11
  • Python Sockets

I have a Socket server like this:

class SocketServer(threading.Thread):

    def __init__(self, ip="127.0.0.1", port=5000, _buffer=1024):
        super(RoomSocketServer, self).__init__()
        self.IP = ip
        self.PORT = port
        self.RECV_BUFFER = _buffer  # Advisable to keep it as an exponent of 2
        self.CONNECTION_LIST = []  # list of socket clients
        self.MESSAGE_QUEUES = {}  # List of message queue by socket
        self.OUTPUTS = []
        self.SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # this has no effect, why ?
        self.SERVER.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.SERVER.bind((self.IP, self.PORT))
        self.SERVER.listen(10)

        # Add server socket to the list of readable connections
        self.CONNECTION_LIST.append(self.SERVER)
        self.ROOM = Room.objects.create(port=port, ip=ip, type_room=type_room)

    def read_sockets(self, read_sockets):
        ''' ... '''

    def write_sockets(self, write_sockets):
        ''' ... '''

    def error_sockets(self, error_sockets):
        ''' ... '''

    def run(self):
        while 1:
            # Get the list sockets which are ready to be read through select
            read_sockets, write_sockets, error_sockets = select.select(self.CONNECTION_LIST, self.OUTPUTS, [])

            # Read sockets
            self.read_sockets(read_sockets)
            self.write_sockets(write_sockets)
            self.error_sockets(error_sockets)

        self.SERVER.close()

I can run this SocketServer like this anywhere on Django (custom_command, a view, celery...):

from socket_server import SocketServer

socket_server = SocketServer()
socket_server.start()
# And the code continues while the socket server is running
# I would like to save socket_server instance anywhere to access
# Later from anywhere or trigger a signal to finish it

Like I say above, I would like to know (if possible) where would any of you save the instance of the server to access it from different parts of the Django project ?

UPDATE

I tried using memcached on Django but when I try to store the SocketServer instance on memcached I get this error:

PicklingError: Can't pickle : attribute lookup thread.lock failed

Answers to

Django & Socket Server: Can I add socket server instance to "memory"?

Source Show
◀ Wstecz