You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask开发哈希接口时出现hashlib TypeError: 'str' object is not callable报错

问题原因
  • 报错的核心原因是语法错误:路由传入的text是字符串类型,你代码中写的text('utf-8')是把字符串当成函数调用,才触发了'str' object is not callable的报错。哈希函数要求传入字节类型参数,你需要调用字符串的encode方法完成转换,正确写法是text.encode('utf-8')。
  • 附加优化建议:你当前使用hash作为变量名,覆盖了Python内置的hash()函数,属于不规范的命名习惯,建议更换为更具辨识度的变量名避免后续潜在问题。
修复后可正常运行的代码
from flask import Flask, request
from flask_restful import Api, Resource
import hashlib

app = Flask(__name__)
api = Api(app)


class hashing(Resource):
  def get(self, text):
    sha256_instance = hashlib.sha256(text.encode('utf-8'))
    text_hashed = sha256_instance.hexdigest()
    return {"data":text_hashed}

api.add_resource(hashing, "/hash/<text>")

if __name__ == "__main__":
    app.run(debug=True)

内容的提问来源于stack exchange,提问作者freezy361

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:45:05