当socket server和views.py分成两个文件时,如何通过Django视图发送套接字消息?

问题描述 投票:0回答:1

环境:Python 3.6和Django 2.1

我创建了一个Django网站和一个套接字服务器,文件组织如下:

  • 卷筒纸 ... 用户(Django应用程序) __init__.py views.py ... server.py

实际上我想用django构建一个伞形租赁系统,服务器通过多线程套接字连接到伞架(发送一些消息)。就像我按下借位按钮,views.py可以调用服务器test_function并向连接的伞架发送一些消息。

我可以在views.py中导入服务器变量或函数,但在server.py运行时我无法得到正确的答案。所以我想问你是否可以给我一些建议。非常感谢!

顺便说一句,我试图直接在clients中导入全局变量views.py,但仍然得到了[]

server.py定义了一个多线程服务器,基本如下:

clients = []

class StuckThread(threading.Thread):
    def __init__(self, **kwargs):
        self.name = kwargs.get('name', '')

    def run(self):
        while True:
            # do something

    def func1(self):
        # do something


def test_function(thread_name):
    # if the function is called by `views.py`, then `clients = []` and return 'nothing', but if I call this function in `server.py`, then I can get a wanted result, which is `got the thread`
    for client in clients:
        if client['thread'].name == thread_name:
            return 'got the thread'
    return 'nothing'

if __name__ == '__main__':
    ip_port = ('0.0.0.0', 65432)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(ip_port)
    server.listen(max_listen_num)
    while True:
        client, address = socket.accept()
        param = {'name': 'test name'}
        stuck_thread = StuckThread(**param)
        clients.append({"client": client, "address": address, "thread": stuck_thread})
        stuck_thread.start()

我有一个像这样的Django views.py

def view_function(request):
    from server import clients
    print(clients) # got []
    form server import test_function
    print(test_function('test name')) # got 'nothing'
    return render(request, 'something.html')
django python-3.x sockets
1个回答
0
投票

我通过django views.py和server.py之间的套接字通信解决了这个问题。我打开另一个端口来接收来自views.py的消息。按下借用按钮后,views.py中的套接字客户端将构建并向服务器发送参数和其他消息。

© www.soinside.com 2019 - 2024. All rights reserved.