Flask使用requests发送POST请求时出现'Request'对象不可迭代TypeError如何处理
TypeError 报错根因
代码中存在类型错配:将Flask框架的全局request对象直接传入requests.post()的data参数,而非requests可识别的请求体内容。
- Flask的
request是Werkzeug封装的、对应当前入站HTTP请求的代理对象,本身不支持迭代遍历作为请求体使用 - requests库的底层适配器在构造出站请求时,会尝试遍历传入的
data参数来生成请求报文,碰到不可迭代的Request代理对象时就会抛出TypeError: 'Request' object is not iterable
针对性修复方案
根据你的转发需求,选择对应修改方式:
- 转发当前收到的表单类POST数据
替换原代码中data=request的写法,改为传入从Flask请求中解析出的普通表单字典request.form,完整可运行代码如下:@main.route('/send/ban', methods=['POST']) def send_ban(): # 替换错误的request传参,使用解析后的表单字典作为请求体 r = requests.post('http://localhost:5001/upload/ban', data=request.form, timeout=5) if r.status_code == 200: if not r.text.find('Uploaded'): flash('Successfully Banned User', 'primary') return redirect('/ban') elif r.status_code == 404: flash('Unable to ban user, server appears to be offline', 'danger') return redirect('/ban') elif r.status_code == 500: flash('Unable to ban user, server appears to be having issues', 'danger') return redirect('/ban') - 转发JSON格式的POST数据
如果下游5001端口的服务接收的是JSON报文,使用json参数传入解析后的请求JSON字典,requests会自动完成序列化并设置正确的请求头:r = requests.post( 'http://localhost:5001/upload/ban', json=request.get_json(), timeout=5 ) - 完全透传原始请求字节流
如果需要原样转发带文件、二进制内容的请求体,直接读取原始请求字节流传入data参数,同时带上原始请求的Content-Type头避免下游解析错误:r = requests.post( 'http://localhost:5001/upload/ban', data=request.get_data(), headers={'Content-Type': request.content_type}, timeout=5 )
避坑提醒
- 注意区分Flask导入的
request全局对象和requests库的request方法,二者类型、作用完全不同,不能混用作请求体参数 - 不要直接把整个Flask request对象传给requests的任何参数,必须取对应的可序列化内容片段作为请求体
内容的提问来源于stack exchange,提问作者parker02311
相关产品推荐
相关产品推荐

