python requests/aiohttp 请求 sse 接口方法

python requests/aiohttp 请求 sse 接口方法

1、requests

import json
import requests
import time

def listen_sse(url):
    # 发送GET请求到SSE端点
    while True:
        with requests.get(url, stream=True, timeout=20) as response:
            try:
                # 确保请求成功
                response.raise_for_status()

                # 逐行读取响应内容
                for line in response.iter_lines():
                    if line:
                        line = line.decode('utf-8')
                        print(line)
            except requests.exceptions.HTTPError as err:
                print(f"HTTP error: {err}")
            except Exception as err:
                print(f"An error occurred: {err}")
                return

# 替换为你的SSE端点URL
sse_url = 'http://your-sse-server-url'
listen_sse(sse_url)

2、aiohttp

import aiohttp
import asyncio

async def sse_client(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status != 200:
                print('Failed to connect to server')
                return
            async for msg in response.content.iter_any():
                print('Received message:', msg.decode('utf-8'))

if __name__ == "__main__":
    # 替换为你的SSE服务器URL
    sse_url = "http://your-sse-server-url"
    asyncio.run(sse_client(sse_url))

你可能感兴趣的:(python,开发语言)