嗨,我在摆弄django channels 2,想获取URL参数并在函数中使用它,但它似乎包含一个空格或类似的东西,这会导致我的函数出现问题。我的函数有1个参数,但当我试图在中传递URL参数时,它会给出以下错误task_status() takes 1 positional argument but 2 were given
。我可以看到,当我尝试打印URL时,它会打印正确的值,但还会创建一行新行。
有没有任何方法可以只获取URL参数并能够在函数中直接使用它?
consumers.py
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
await self.send({
"type": "websocket.accept"
})
user = self.scope['user']
get_task_id = self.scope['url_route']['kwargs']['task_id']
print(get_task_id)
get_info = await self.task_status(get_task_id)
print(get_info)
await self.send({
"type": "websocket.send",
"text": "hey"
})
async def websocket_receive(self, event):
print("receive", event)
async def websocket_disconnect(self, event):
print("disconnected", event)
def task_status(task_id):
command = "golemcli tasks show {}".format(task_id)
taskoutput = subprocess.getoutput(command)
print(taskoutput)
路由.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/dashboard/task/(?P<task_id>[0-9a-f-]+)', consumers.ChatConsumer),
]
网站URLhttp://localhost:8000/dashboard/task/aa3c6c12-5446-11ea-b237-1e0f691c9a55
你的task_status
是一个方法,所以它的第一个扩充应该是self
,python总是在你调用它时将这个扩充添加到函数中,这就是你出错的原因。它正在用self
和task_id
调用方法
要解决这个问题,你应该这样定义你的方法:
def task_status(self, task_id):
....
在另一点上,您正在task_status
方法中同步等待,这将阻止整个服务器处理任何其他事务。
您应该将task_status
设置为async
方法,然后使用异步子流程comand启动并使用await
作为输出https://docs.python.org/3/library/asyncio-subprocess.html#examples