Python處理application/json錯(cuò)誤的方法詳解
問(wèn)題描述
調(diào)用sse流式接口使用httpx_sse的方式
import httpx
from httpx_sse import connect_sse
# 省略無(wú)關(guān)代碼
try:
with httpx.Client() as client:
with connect_sse(client, "GET", url, params=param) as event_source:
clear_textbox(response_textbox)
# 把 iter_sse() 迭代完, 就相當(dāng)于處理完了一次流式調(diào)用
for sse in event_source.iter_sse():
# 流式響應(yīng)中,每次響應(yīng)體的處理邏輯
print(f"generated_answer的值是: '{sse.data}'")
response = sse.data
if response != '':
# self.response = response
append_text(response_textbox, response)
except httpx.RequestError as e:
print(f"請(qǐng)求錯(cuò)誤:{e}")
except Exception as e:
print(f"發(fā)生了一個(gè)錯(cuò)誤:{e}")
httpx_sse的connet_sse源碼:
@contextmanager
def connect_sse(
client: httpx.Client, method: str, url: str, **kwargs: Any
) -> Iterator[EventSource]:
headers = kwargs.pop("headers", {})
headers["Accept"] = "text/event-stream"
headers["Cache-Control"] = "no-store"
with client.stream(method, url, headers=headers, **kwargs) as response:
yield EventSource(response)
可以看到connect_sse源碼中的headers的"Accept"設(shè)置了只接受"text/event-stream"流式結(jié)果,正常這么調(diào)用是沒(méi)錯(cuò)的。但是當(dāng)后端的流式接口因?yàn)?01權(quán)限問(wèn)題等報(bào)錯(cuò)返回了"application/json"格式,如
{ “code”:401, “msg”:“登錄過(guò)期,請(qǐng)重新登錄”, “data”:null} 這樣的json格式結(jié)果時(shí),以上代碼就會(huì)報(bào)錯(cuò),因?yàn)樗皇?quot;text/event-stream"流式響應(yīng)結(jié)果頭。那么該怎么辦呢?
方案
重新寫(xiě)一個(gè)自定義的connect_sse。
import httpx
from httpx_sse import EventSource
from typing import Any, Iterator
from contextlib import contextmanager
import json
# 自定義調(diào)用sse接口
@contextmanager
def custom_connect_sse(
self, client: httpx.Client, method: str, url: str, **kwargs: Any
) -> Iterator[EventSource]:
headers = kwargs.pop("headers", {})
# 只有當(dāng)沒(méi)有指定Accept時(shí)才添加默認(rèn)值
headers["Accept"] = "*/*"
headers["Cache-Control"] = "no-store"
with client.stream(method, url, headers=headers, **kwargs) as response:
content_type = response.headers.get('content-type', '').lower()
json_flag = False
if 'text/event-stream' in content_type:
# 處理SSE流
yield json_flag, EventSource(response)
elif 'application/json' in content_type:
# yield response # 在這里你可以決定如何進(jìn)一步處理這個(gè)JSON響應(yīng)
# 讀取并合并所有文本塊
text_data = ''.join([chunk for chunk in response.iter_text()])
# 解析整個(gè)響應(yīng)體為JSON
json_data = json.loads(text_data)
json_flag = True
yield json_flag, json_data
調(diào)用代碼
# 使用自定義的connect_sse函數(shù)
try:
with httpx.Client() as client:
with self.custom_connect_sse(client, "GET", url, params=param, headers=headers) as (json_flag, event_source):
if json_flag:
code = event_source.get("code")
msg = event_source.get("msg")
print(f"Code: [code], Message: {msg}")
else:
full_answer = ""
clear_textbox(response_textbox)
for sse in event_source.iter_sse():
print(f"generated_answer的值是: '{sse.data}'")
response = sse.data
if response:
append_text(response_textbox, response)
full_answer += response
user_record += reply + full_answer + "\n"
print(f"user_record:{user_record}")
except httpx.RequestError as e:
print(f"請(qǐng)求錯(cuò)誤:{e}")
except Exception as e:
print(f"發(fā)生了一個(gè)錯(cuò)誤:{e}")
關(guān)鍵步驟:
1.設(shè)置headers[“Accept”] = “/”,所有響應(yīng)頭都可以接收
2.content_type = response.headers.get(‘content-type’, ‘’).lower() 判斷響應(yīng)頭是流式還是json,并用json_flag記錄是否json標(biāo)識(shí),返回不同的結(jié)果。如果是json,則循環(huán)合并處理chunk塊,拼裝完整json返回結(jié)果(實(shí)測(cè)第一次就返回完整json結(jié)構(gòu)了,但是代碼得這么寫(xiě))。
3.使用自定義connect_sse方法時(shí),根據(jù)json_flag來(lái)分別處理成功調(diào)用流式結(jié)果還是異常的json結(jié)果。
到此這篇關(guān)于Python處理application/json錯(cuò)誤的方法詳解的文章就介紹到這了,更多相關(guān)Python處理application/json錯(cuò)誤內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?常用的print輸出函數(shù)和input輸入函數(shù)
這篇文章主要介紹了Python?常用的print輸出函數(shù)和input輸入函數(shù),今天主要學(xué)習(xí)一下Python中的輸入輸出流,會(huì)對(duì)標(biāo)準(zhǔn)輸入輸出流、文件輸入輸出流展開(kāi)介紹,需要的朋友可以參考一下2022-02-02
Python sql注入 過(guò)濾字符串的非法字符實(shí)例
這篇文章主要介紹了Python sql注入 過(guò)濾字符串的非法字符實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
Python實(shí)現(xiàn)獲取亂序列表排序后的新下標(biāo)的示例
本文主要介紹了Python實(shí)現(xiàn)獲取亂序列表排序后的新下標(biāo)的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
淺談pytorch卷積核大小的設(shè)置對(duì)全連接神經(jīng)元的影響
今天小編就為大家分享一篇淺談pytorch卷積核大小的設(shè)置對(duì)全連接神經(jīng)元的影響,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
Python英文文本分詞(無(wú)空格)模塊wordninja的使用實(shí)例
今天小編就為大家分享一篇關(guān)于Python英文文本分詞(無(wú)空格)模塊wordninja的使用實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-02-02
python 如何利用argparse解析命令行參數(shù)
這篇文章主要介紹了python 利用argparse解析命令行參數(shù)的步驟,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-09-09

