FastAPI POST重定向GET传参报错及传参可行性咨询
我搞不懂怎么在FastAPI的重定向响应里传递额外数据,查了几个相关回答也没理清问题。
前端代码(HTML文件中的脚本)
function cmb_pos() { var data = { 'dep_id': dep_id, 'div_id': div_id, } fetch('/job-history/add-new/intermediate/{{persona_id}}', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(response => console.log(JSON.stringify(response))) };
第一个端点(接收POST请求、执行操作并重定向的函数)
from starlette.datastructures import URL @router.post(path="/add-new/intermediate/{persona_id}", response_class=responses.RedirectResponse, ) async def my_test(request: Request, item: Item, persona_id: int, service: Related): staff_schedule = await service.get_item_by_where(....) context_ext = {} context_ext["request"] = request context_ext["staff_schedule"] = staff_schedule context_ext["flag"] = True redirect_url = URL(request.url_for("create_job_history_init", persona_id=persona_id)) .include_query_params(context_ext=context_ext) return responses.RedirectResponse( url=redirect_url, status_code=status.HTTP_303_SEE_OTHER, )
第二个端点(重定向目标函数)
@router.get(path="/persona_id={persona_id}/add-new", response_class=responses.HTMLResponse, ) async def create_job_history_init(request: Request, persona_id: int, schedule_service: CommonsDep, context_ext: Optional[dict] = None, ): context = {} schedule = await schedule_service.get_all_item() related = ...... context = schedule | related context["request"] = request context["persona_id"] = persona_id context["context_ext"] = context_ext return backend.webapps.templates.TemplateResponse( name="job_history/create_job_history.html", context=context, )
遇到的错误
File "/Users/pas/------/backend/webapps/job_history.py", line 276, in my_test
).include_query_params(context_ext=context_ext)File "/Users/pas/-------/.my_pers/lib/python3.11/site-packages/starlette/datastructures.py", line 143, in include_query_params
params = MultiDict(parse_qsl(self.query, keep_blank_values=True))File "/Users/pas/---------/.my_pers/lib/python3.11/site-packages/starlette/datastructures.py", line 83, in query
return self.components.queryFile "/Users/pas/---------/.my_pers/lib/python3.11/site-packages/starlette/datastructures.py", line 66, in components
self._components = urlsplit(self._url)TypeError: unhashable type: 'URL'
请问我哪里操作有误?是否可以通过重定向传递额外数据?非常感谢!
更新
看到一个解决方案,但使用时出现如下错误:
return tuple(x.decode(encoding, errors) if x else '' for x in args)
AttributeError: 'URL' object has no attribute 'decode'
对应的代码行是:parsed = list(urllib.parse.urlparse(redirect_url))
我自己找到的可行解决方案是修改为:parsed = list(urllib.parse.urlparse(redirect_url._url))
添加._url后成功完成了解析。
内容的提问来源于stack exchange,提问作者Speedy Gonzales

