如何在Pyramid中读取HTTP POST参数?含表单键值对场景
嘿,我之前也踩过这个坑!当请求是application/x-www-form-urlencoded类型的表单键值对时,用request.json_body肯定会报错——因为这个属性只专门处理application/json格式的请求体,它会尝试把你的id=tr_uH4yPGBahB当成JSON解析,这不报错才怪呢😅
下面给你两种靠谱的解决方式:
1. 直接用request.POST读取表单参数
Pyramid会自动帮你解析application/x-www-form-urlencoded类型的请求体,把参数存在request.POST里,它是一个类字典的对象,用法和普通字典差不多:
from pyramid.view import view_config @view_config(route_name='test_route', request_method='POST') def test_view(request): # 安全获取id参数(如果参数不存在会返回None) item_id = request.POST.get('id') # 如果确定参数一定存在,也可以直接取值 # item_id = request.POST['id'] return {'received_id': item_id}
用这个方法,你就能拿到请求体里的id=tr_uH4yPGBahB对应的tr_uH4yPGBahB值了。
2. 兼容JSON和表单数据的写法(可选)
如果你的接口需要同时支持JSON和表单两种请求格式,可以先判断请求的Content-Type,再选择对应的读取方式:
@view_config(route_name='multi_type_route', request_method='POST') def multi_type_view(request): item_id = None if request.content_type == 'application/json': try: data = request.json_body item_id = data.get('id') except Exception as e: return {'error': 'Invalid JSON format'} elif request.content_type == 'application/x-www-form-urlencoded': item_id = request.POST.get('id') else: return {'error': 'Unsupported Content-Type, use JSON or form data'} return {'received_id': item_id}
总结一下:request.json_body只给JSON请求用,表单键值对就用request.POST,分清楚就不会报错啦!
内容的提问来源于stack exchange,提问作者edbras
相关产品推荐
相关产品推荐

