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

Python HTTP服务器报错TypeError: writable()参数数量不符求助

问题分析与修复

错误原因

  1. 方法误用:你调用self.wfile.writable()并传入HTML字节内容,但writable()是用来判断输出流是否可写的方法,它不需要任何参数,传入参数直接触发了TypeError。正确写入内容的方法是write()。
  2. 语法错误:self.wfile.close缺少括号,方法调用必须加括号才会执行关闭操作。

修正后的代码

import http.server  # 移除无用的asyncio.Handle导入

class HandleRequests(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        # 替换writable为write,写入HTML字节内容
        self.wfile.write(bytes("<html><head><title>First application</title></head><body style='color: #333; margin-top: 30px;'><center><h2>Welcome to our first prometheus-python application.</center></h2></body></html>","utf-8"))
        self.wfile.close()  # 添加括号执行关闭方法

if __name__ == "__main__":
    server = http.server.HTTPServer(('localhost', 5000), HandleRequests)
    server.serve_forever()

额外说明

  • 导入的from asyncio import Handle未被使用,可直接移除以精简代码。
  • 运行修正后的代码后,刷新http://localhost:5000/即可看到正常HTML页面,控制台也会输出请求日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:50:26