【django-channels】异步读取MySQL,You cannot call this from an async context - use a thread or sync

在channels异步获取MySQL数据时,做到实时推送的功能,但想获取对应类型的多条时,遇到
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.

多次调试发现

错误代码示例:

@database_sync_to_async
    def get_testTagImg(self,folder):        
        try:
            return  ImageManagement.objects.values('filename')
            .filter(file_path=folder,image_status='test',xml_status=1)
        except Exception as e:
            return False

正确代码示例:

@database_sync_to_async
def get_testTagImg(self,folder):        
    try:
        return  list(ImageManagement.
        objects.values('filename').filter(file_path=folder,image_status='test',xml_status=1))
    except Exception as e:
        return False

由于是异步获取,如果需要获取筛选的多行数据,貌似需要先转成列表返回,不然会报标题的错误,或者只取第一个值也不会出现该错误,即:

ImageManagement.objects.
values('filename').filter(file_path=folder,image_status='test',xml_status=1).first()

PS:个人解决办法,不喜勿喷,有更好的请指点多谢!

你可能感兴趣的:(django,mysql,python,websocket)