運行環境Mac? Python 3.5.2
Q:
http_response = """\
HTTP/1.1 200 OK
?
Hello, World!
"""
client_connection.sendall(http_response)
?
TypeError: a bytes-like object is required, not 'str'
類型錯誤,需要的是一個byte類型,不是str類型
A:
http_response = """\
HTTP/1.1 200 OK
?
Hello, World!
"""
encode_http_response = http_response.encode()
client_connection.sendall(encode_http_response)
?
Expand:
str通過encode()方法可以編碼為指定的bytes
反過來,如果我們從網絡或磁盤上讀取了字節流,那么讀到的數據就是bytes。要把bytes變為str,就需要用decode()方法: