Python+client_connection.sendall(http_resp)+TypeError: 'str' does not support the buffer interface

本文详细记录了在使用Python搭建简单Web服务器时遇到的类型错误问题,通过分析发现是Bytes与Unicode字符串类型的不匹配导致。文章提供了解决方案,包括在发送HTTP响应时将Unicode字符串转换为Bytes类型,并成功实现Web服务器运行与网页访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文记录本人学习进步点滴,如有错误或不妥,请不吝赐教。


在使用python搭建一个简单的web server时遇到的问题,代码如下

import socket

HOST, PORT = '', 8888

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port '+str(PORT)+'...')
while True:
    client_connection, client_address = listen_socket.accept()
    request = client_connection.recv(1024)
    print(request)

    http_resp = """\
HTTP/1.1 200 OK

Hello, World!
"""
    client_connection.sendall(http_resp)
    client_connection.close()

错误信息表明这是一个类型错误。在stackoverflow上寻找解决方案,发现这是在把python 2版本的代码移植到python 3版本时容易发生的错误。

在python 3中,bytes strings 和 unicode strings是两个不同的类型。我们知道,在网络通信的socket中,使用的是字节流,即bytes strings,而程序中的http_resp是unicode string,所以会发生TypeError,因为socket使用的是字节流buffer。

幸而,python提供了bytes strings和unicode strings之间进行转换的机制。使用unicode strings的encode()可以将其转为bytes strings;使用bytes strings的decode()可以将其转为unicode strings。

好,我们尝试一下,将原代码中的client_connection.sendall(http_resp)改为client_connection.sendall(http_resp.encode()),运行脚本,可正常运行

这里写图片描述

接着我们打开浏览器,访问localhost:8888/hello,能正常访问

这里写图片描述

我们知道,python中的bytes strings定义需在前面附上字符b,所以我们尝试另一种解决方案,修改http_resp定义为

http_response = b"""\
HTTP/1.1 200 OK

Hello, World!
"""

同样能正常运行脚本和访问localhost:8888/hello,所以可知问题确实是由bytes strings和unicode strings引起的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值