Stream video using HTTP Range requests with FastAPI and Pyrogram

The current code uses FastAPI and Pyrogram to create a video streaming server. The server should support HTTP Range requests to allow streaming of video segments but the video client is not able to skip forward or backward during streaming as expected.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from fastapi import FastAPI, Request
from pyrogram import Client
from starlette.responses import StreamingResponse
app = FastAPI()
client = Client("my_account", api_id=......, api_hash="....")
@app.on_event("startup")
async def startup_event():
await client.start()
@app.on_event("shutdown")
async def shutdown_event():
await client.stop()
@app.get('/stream/{file_id}')
async def stream(file_id: str, request: Request):
range_header = request.headers.get('Range', None)
start, end = 0, None
if range_header:
byte1, byte2 = range_header.replace('bytes=', '').split('-')
start = int(byte1)
if byte2:
end = int(byte2)
async def generate():
offset = start // (1024 * 1024) # Convert start to chunks
limit = (1 << 31) - 1 # Default limit
if end is not None:
limit = (end - start) // (1024 * 1024) + 1 # Convert end to chunks
async for chunk in client.stream_media(file_id, offset=offset, limit=limit):
yield chunk
response = StreamingResponse(generate(), media_type='video/mp4')
response.headers['Accept-Ranges'] = 'bytes'
if range_header:
response.status_code = 206
response.headers['Content-Range'] = f'bytes {start}-{end if end else ""}/*'
return response
</code>
<code>from fastapi import FastAPI, Request from pyrogram import Client from starlette.responses import StreamingResponse app = FastAPI() client = Client("my_account", api_id=......, api_hash="....") @app.on_event("startup") async def startup_event(): await client.start() @app.on_event("shutdown") async def shutdown_event(): await client.stop() @app.get('/stream/{file_id}') async def stream(file_id: str, request: Request): range_header = request.headers.get('Range', None) start, end = 0, None if range_header: byte1, byte2 = range_header.replace('bytes=', '').split('-') start = int(byte1) if byte2: end = int(byte2) async def generate(): offset = start // (1024 * 1024) # Convert start to chunks limit = (1 << 31) - 1 # Default limit if end is not None: limit = (end - start) // (1024 * 1024) + 1 # Convert end to chunks async for chunk in client.stream_media(file_id, offset=offset, limit=limit): yield chunk response = StreamingResponse(generate(), media_type='video/mp4') response.headers['Accept-Ranges'] = 'bytes' if range_header: response.status_code = 206 response.headers['Content-Range'] = f'bytes {start}-{end if end else ""}/*' return response </code>
from fastapi import FastAPI, Request
from pyrogram import Client
from starlette.responses import StreamingResponse

app = FastAPI()
client = Client("my_account", api_id=......, api_hash="....")

@app.on_event("startup")
async def startup_event():
    await client.start()

@app.on_event("shutdown")
async def shutdown_event():
    await client.stop()

@app.get('/stream/{file_id}')
async def stream(file_id: str, request: Request):
    range_header = request.headers.get('Range', None)
    start, end = 0, None
    if range_header:
        byte1, byte2 = range_header.replace('bytes=', '').split('-')
        start = int(byte1)
        if byte2:
            end = int(byte2)

    async def generate():
        offset = start // (1024 * 1024)  # Convert start to chunks
        limit = (1 << 31) - 1  # Default limit
        if end is not None:
            limit = (end - start) // (1024 * 1024) + 1  # Convert end to chunks
        async for chunk in client.stream_media(file_id, offset=offset, limit=limit):
            yield chunk

    response = StreamingResponse(generate(), media_type='video/mp4')
    response.headers['Accept-Ranges'] = 'bytes'
    if range_header:
        response.status_code = 206
        response.headers['Content-Range'] = f'bytes {start}-{end if end else ""}/*'
    return response

An example of log

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>PS C:UsersAdministratorDesktopmixnginx_streamteldriveplaystream> uvicorn editor:app --host 0.0.0.0 --port 11840
INFO: Started server process [10540]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:11840 (Press CTRL+C to quit)
INFO: 127.0.0.1:56602 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 200 OK
INFO: 127.0.0.1:56601 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 206 Partial Content
</code>
<code>PS C:UsersAdministratorDesktopmixnginx_streamteldriveplaystream> uvicorn editor:app --host 0.0.0.0 --port 11840 INFO: Started server process [10540] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:11840 (Press CTRL+C to quit) INFO: 127.0.0.1:56602 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 200 OK INFO: 127.0.0.1:56601 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 206 Partial Content </code>
PS C:UsersAdministratorDesktopmixnginx_streamteldriveplaystream> uvicorn editor:app --host 0.0.0.0 --port 11840
INFO:     Started server process [10540]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:11840 (Press CTRL+C to quit)
INFO:     127.0.0.1:56602 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 200 OK
INFO:     127.0.0.1:56601 - "GET /stream/BAACAgQAAx0Eb1YTJQABBYGv............ HTTP/1.1" 206 Partial Content

Example of URL streaming is http://127.0.0.1:11840/stream/BAACAgQAAx0Eb1....
BAACAgQAAx0Eb1.... is file_id from telegram

New contributor

nathan never is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật