相关疑难解决方法(0)

将 telethon 与 django 结合使用:线程“Thread-1”中没有当前事件循环

我想使用django中的Telethon。但是当我运行它时,我收到以下错误:

RuntimeError:线程“Thread-1”中没有当前事件循环。

我的代码views.py:

from django.shortcuts import render,HttpResponse
from telethon.sync import TelegramClient, events

async def join(client):
    ch = '@andeh_ir'
    try:
        await client(JoinChannelRequest(ch))
        print('[+] Joined The Channel')
    except:
        print('[-] skiped')

def addChannel(request):
    api_id   =   XXXXXX
    api_hash = 'xxxxxxxxxxxxxxxxxxxxx'
    client = TelegramClient('+254716550762', api_id, api_hash )
    with client:
        client.loop.run_until_complete(join(client))
    return HttpResponse('addChannel')
Run Code Online (Sandbox Code Playgroud)

python django multithreading asynchronous telethon

2
推荐指数
1
解决办法
3205
查看次数

使用asyncio在django中执行定期任务

您是否认为可以使用asyncio在django中每n秒运行一次任务,这样主进程就不会被阻塞?

例如,在控制台中每5分钟打印一次,例如:

    import asyncio
    from random import randint

    async def do_stuff(something, howmany):   
        for i in range(howmany):
            print('We are doing  {}'.format(something))
            await asyncio.sleep(randint(0, 5))

    if __name__ == '__main__':
        loop = asyncio.get_event_loop()
        work = [
            asyncio.ensure_future(do_stuff('something', 5)),

        ]
        loop.run_until_complete(asyncio.gather(*work))
Run Code Online (Sandbox Code Playgroud)

似乎django将在循环运行时停止工作.即使这可以在开发中工作,当网站在像apache或gunicorn这样的东西上线时它会如何表现?

python django multithreading periodic-task python-asyncio

1
推荐指数
1
解决办法
885
查看次数