首页 > 解决方案 > 如何在 Django REST 框架中运行异步 curl 请求

问题描述

如何在 Django REST 框架中运行异步 curl 请求。该请求应该在后台运行。

我的代码是这样的:

def track(self, appUserId, appEventName, appEventData):
    asyncio.run(self.main(appUserId, appEventName, appEventData))

async def main(self, appUserId, appEventName, appEventData):
    async with aiohttp.ClientSession() as session:
        tasks = []
        task = asyncio.ensure_future(self.sendData(session, {
                "userId": self.appUserIdSandbox if (self.sandBoxEnabled == True) else appUserId,
                "eventName": appEventName,
                
                "eventData": appEventData
            }))
        tasks.append(task)
        task_count = await asyncio.gather(*tasks)
    

async def sendData(self,session, appEventData):
    response  = {}
    payload = json.dumps(appEventData)
    headers = {
        "Authorization": self.__authKey,
        "Cache-Control": "no-cache",
        "Content-Type": "application/json",
    }
    async with session.post(self.__apiUrl,
            headers=headers,
            data=payload) as response:
        result_data = await response.json()
        return response

标签: djangoasynchronousdjango-rest-frameworkasync-await

解决方案


推荐阅读