简体   繁体   English

如何一起使用 Flask 和 Telethon

[英]How to use Flask and Telethon together

So i have a Flaks app, which obviously has @app.route decorators which are working after app.run() is executed.所以我有一个 Flaks 应用程序,它显然有 @app.route 装饰器,它们在 app.run() 执行后工作。 Also, i want to use in the same project telethon client event handler decorator, which is working after TelethonClient.run_until_disconected() is executed (pseudo code).另外,我想在同一个项目中使用 Telethon 客户端事件处理程序装饰器,它在执行 TelethonClient.run_until_disconected() 之后工作(伪代码)。 How to run both process together?如何同时运行两个进程?

The idea is to update Flask app content when Telethon receive or sends messages.这个想法是在 Telethon 接收或发送消息时更新 Flask 应用程序内容。 In other words i want to implement Telegtam chats with real-time update in my Flask app.换句话说,我想在我的 Flask 应用程序中实现 Telegtam 聊天和实时更新。 Thank you!谢谢!

I recommend you to use Quart.我建议你使用 Quart。

Quart is an asyncio reimplementation of the popular Flask microframework API. Quart 是流行的 Flask 微框架 API 的异步重新实现。 This means that if you understand Flask you understand Quart.这意味着,如果您了解 Flask,您就会了解 Quart。

All you gotta do is start Telethon client and just run quart using hypercorn.您所要做的就是启动 Telethon 客户端,然后使用 hypercorn 运行 quart。

An example一个例子

from quart import Quart
from telethon import TelegramClient
import asyncio 
import hypercorn.asyncio

app = Quart(__name__)
client = TelegramClient(
        "Session_name",
        api_id=yourapiid,
        api_hash=youapihash
    )
async def run():
    await client.start()
    await hypercorn.asyncio.serve(app)
loop = asyncio.get_event_loop()
loop.run_until_complete(run())

To install Quart: pip install quart安装夸脱: pip install quart

Install hypercorn: pip install hypercorn安装超级玉米: pip install hypercorn

Run application: python yourscriptname运行应用程序: python yourscriptname

Else: use threads其他:使用线程

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

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