项目场景:
python Flask构建restful API接口服务,通过postman进行接口服务验证测试
问题描述及解决方法
提示:这里描述项目中遇到的问题:
验证接口调用text/plain时出现报错
源代码(错误):
from flask import Flask,url_for,request,json
app = Flask(__name__)
@app.route("/message",methods=['POST'])
def api_message():
if request.headers['Content-Type'] =='text/plain':
return "Text message:" + request.data()#报错1:TypeError: 'bytes' object is not callable
elif request.headers['Content-Type'] == 'application/json':
return "Json message: " + json.dumps(request.json)
elif request.headers['Content-Type'] == 'application/octet-stream':
f= open("./binary",'wb')
f.write(request.data)
f.close()
return("Binary message written!")
else:
return("415 Unsupported Media Type!")
}
if __name__ == "__main__":
app.run()
报错1: TypeError: ‘bytes’ object is not callable
报错1原因: 类中函数名或者变量名重用(即变量名和函数名有重复)
根据报错1的原因进行修改
return "Text message:" + request.data()#报错1:TypeError: 'bytes' object is not callable
修改成
return "Text message:" + request.data
但验证接口调用text/plain时还是报错
报错2: TypeError: can only concatenate str (not “bytes”) to str
报错2原因: 两边字符的格式不一致,导致不能用“+”进行拼接
根据报错2的原因进行修改
return "Text message:" + request.data#报错2:TypeError: can only concatenate str (not "bytes") to str
修改成
return "Text message:" + str(request.data)
修改完成后,接口调用text/plain时不报错,也可以获取request中txt格式的流数据,但是输入123,本该正常输出Text message:123,却输出Text message:b’123’
异常解决方法: 使用bytes类型中的decode()方法,decode()方法完成从比特流向字符串解码的过程
根据异常解决方法进行修改
return "Text message:" + str(request.data)
修改成
return "Text message:" + request.data.decode('utf-8')
文章来源:https://www.toymoban.com/news/detail-405063.html
源代码(正确):文章来源地址https://www.toymoban.com/news/detail-405063.html
from flask import Flask,url_for,request,json
app = Flask(__name__)
@app.route("/message",methods=['POST'])
def api_message():
if request.headers['Content-Type'] =='text/plain':
return "Text message:" + request.data.decode('utf-8')
elif request.headers['Content-Type'] == 'application/json':
return "Json message: " + json.dumps(request.json)
elif request.headers['Content-Type'] == 'application/octet-stream':
f= open("./binary",'wb')
f.write(request.data)
f.close()
return("Binary message written!")
else:
return("415 Unsupported Media Type!")
}
if __name__ == "__main__":
app.run()
到了这里,关于【Python Flask/postman:request中post的header:Content-type=“text/plain”报错及解决方法】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!