简体   繁体   中英

Python Flask with Telethon

I want to use Telethon Telegram API from my Flask Web App. But when I am running it, I am getting following error:

RuntimeError: There is no current event loop in thread 'Thread-1'.

I think there is some issues with 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. If you don't want to dig into asyncio internals, just pip3 install telethon-sync and you're good to go.

Here's what I learned after trying this out. First, Make sure you know what asyncio is, it's really super easy. 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.

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

You can easily import asyncio and use the main loop. 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.
  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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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