python 搭建sse服务

本文介绍了如何使用FastAPI构建一个服务器端应用,提供实时事件流服务,并通过客户端如requests和gradio实现与WebUI的交互。代码展示了如何发送和处理来自客户端的消息以及处理SSE(Server-SentEvents)流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import time
from pydantic import BaseModel

app = FastAPI()


# 定义一个Pydantic模型来描述JSON数据的结构
class Item(BaseModel):
    msg: str


@app.post("/stream")
async def stream(item: Item):

    async def event_stream():
        while True:
            # 模拟一个事件
            yield '{} data: {}\n\n'.format(item.msg, time.ctime())
            # 立即发送事件,而不是等待缓冲
            await asyncio.sleep(2)  # 每2秒发送一次事件

    return StreamingResponse(event_stream(), media_type="text/event-stream")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

代码客户端

import requests
import json

# SSE URL
url = 'http://localhost:8000/stream'

# JSON payload
payload = {'msg': '你好'}

# Headers for SSE request
headers = {'Content-Type': 'application/json', 'Accept': 'text/event-stream'}

# Send SSE request
response = requests.post(url,
                         data=json.dumps(payload),
                         headers=headers,
                         stream=True)

# Check if the request was successful
if response.status_code == 200:
    # Process the SSE stream
    for line in response.iter_lines():
        if line:
            decoded_line = line.decode('utf-8')
            print(decoded_line)
else:
    print(f"Request failed with status code: {response.status_code}")

# Close the connection
response.close()

webui客户端

import random
import gradio as gr
import requests
import json
"""
用户输入后的回调函数 random_response
参数:
message: 用户此次输入的消息
history: 历史聊天记录,比如 [["use input 1", "assistant output 1"],["user input 2", "assistant output 2"]]
​
返回值:输出的内容
"""


def random_response(message, history):
    return random.choice(["Yes", "No"])


def chat(message, history):
    # SSE URL
    url = 'http://localhost:8000/stream'

    # JSON payload
    payload = {'msg': '你好'}

    # Headers for SSE request
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
    }

    # Send SSE request
    response = requests.post(url,
                             data=json.dumps(payload),
                             headers=headers,
                             stream=True)

    # Check if the request was successful
    if response.status_code == 200:
        # Process the SSE stream
        for line in response.iter_lines():
            if line:
                decoded_line = line.decode('utf-8')
                yield decoded_line
    else:
        print(f"Request failed with status code: {response.status_code}")

    # Close the connection
    response.close()


gr.ChatInterface(chat).launch(server_name='0.0.0.0',
                                         server_port=8001)

### 实现高性能SSE服务的最佳实践 #### 使用Flask-SSE框架简化开发过程 为了创建高效的服务器发送事件(SSE)服务,可以利用`flask-sse`扩展来加速开发流程。此工具允许开发者快速搭建基于HTTP协议的单向通信通道,使得服务器能够主动推送更新给客户端浏览器。 ```python from flask import Flask, Response import time app = Flask(__name__) @app.route('/events') def events(): def generate_events(): while True: yield f"data: {time.time()}\n\n" time.sleep(1) return Response(generate_events(), content_type='text/event-stream') if __name__ == "__main__": app.run(threaded=True) ``` 上述代码展示了如何通过简单的循环结构持续不断地向连接中的每一个客户端广播时间戳信息[^4]。 #### 异步处理提高并发能力 采用异步I/O模式可显著增强应用程序响应多请求的能力。借助于`asyncio`库以及兼容其特性的Web框架如Sanic或FastAPI,能更高效地管理大量活跃连接而不必担心阻塞问题。 ```python import asyncio from sanic import Sanic from sanic.response import stream app = Sanic("MyApp") async def event_publisher(response): while True: await response.write(f'data: Server Time {time.time()} \n\n') await asyncio.sleep(1) @app.route("/stream") async def handle(request): return stream(event_publisher, content_type="text/event-stream") if __name__ == '__main__': app.run(host="0.0.0.0", port=8000, debug=False, access_log=False) ``` 这段例子说明了怎样运用协程函数配合流式传输机制实现实时消息传递功能[^5]。 #### 配置Gunicorn作为生产级WSGI容器 当准备将应用部署到实际环境中时,推荐选用像Gunicorn这样的成熟可靠的WSGI HTTP服务器软件包。它不仅支持多种工作进程类型(包括gevent),而且易于配置与维护。 ```bash gunicorn -w 4 -k gevent my_sse_app:app ``` 命令行参数指定了四个worker线程并启用了gevent模块以确保最佳性能表现[^6]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值