简体   繁体   English

带有 Telethon 的 Python 烧瓶

[英]Python Flask with Telethon

I want to use Telethon Telegram API from my Flask Web App.我想从我的 Flask Web 应用程序中使用 Telethon Telegram API。 But when I am running it, I am getting following error:但是当我运行它时,我收到以下错误:

RuntimeError: There is no current event loop in thread 'Thread-1'.运行时错误:线程“Thread-1”中没有当前事件循环。

I think there is some issues with asyncio.我认为 asyncio 存在一些问题。 But I am not sure about that.但我不确定。

Here is my code这是我的代码

#!/usr/bin/python3

from flask import Flask
from telethon import TelegramClient
from telethon import sync

app = Flask(__name__)

@app.route('/')
def index():
    api_id = XXXXXX
    api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    client = TelegramClient('XXXXXX', api_id, api_hash)
    client.start()
    return 'Index Page'

if __name__ == '__main__':
    app.run()

Basically, it's due to Python's GIL.基本上,这是由于 Python 的 GIL。 If you don't want to dig into asyncio internals, just pip3 install telethon-sync and you're good to go.如果您不想深入了解asyncio内部结构,只需pip3 install telethon-sync就可以了。

Here's what I learned after trying this out.这是我在尝试后学到的东西。 First, Make sure you know what asyncio is, it's really super easy.首先,确保你知道 asyncio 是什么,它真的超级简单。 Then You can work on it with more productivity.然后,您可以以更高的生产力来处理它。

Telethon uses asyncio which means that when you call blocking methods you have to wait until the coroutine finishes. Telethon 使用 asyncio,这意味着当您调用阻塞方法时,您必须等到协程完成。

client.loop ###Doesn't work inside flask, it might have to do with threads.

You can easily import asyncio and use the main loop.您可以轻松导入 asyncio 并使用主循环。 like this.像这样。

import asyncio
loop = asyncio.get_event_loop()

Now you're ready to wait for coroutines to finish.现在您已准备好等待协程完成。

  1. Create a new async function and add await to the blocking methods.创建一个新的异步函数并将 await 添加到阻塞方法中。
  2. Execute the code using the main event loop.使用主事件循环执行代码。

Here's a code sample.这是一个代码示例。

async def getYou():
    return await client.get_me()

@app.route("/getMe", methods=['GET'])
def getMe():
    return {"MyTelegramAccount": loop.run_until_complete(getYou())}

And one more thing.还有一件事情。 don't use telethon.sync, it's not fully translated to sync, it uses the above pattern it awaits all of the methods.不要使用telethon.sync,它没有完全转换为同步,它使用上述模式等待所有方法。

在你的地方,我会考虑使用Quart,它是 Telethon 自己的文档中建议的,它更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM