[英]Python http server giving error when connected to
Im getting an error with my server code. 我的服务器代码出错了。 It worls till a browser tries to connect to it.
它会直到浏览器尝试连接到它。 I really have no clue what it can be.
我真的不知道它是什么。 could any one take a look at it and point me in the right direction?
任何人都可以看一看并指出我正确的方向吗?
The error code is 错误代码是
Exception happened during processing of request from ('127.0.0.1', 57953)
Traceback (most recent call last):
File "C:\Python34\lib\socketserver.py", line 306, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Python34\lib\socketserver.py", line 332, in process_request
self.finish_request(request, client_address)
File "C:\Python34\lib\socketserver.py", line 345, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python34\lib\socketserver.py", line 666, in __init__
self.handle()
File "C:\Python34\lib\http\server.py", line 400, in handle
self.handle_one_request()
File "C:\Python34\lib\http\server.py", line 388, in handle_one_request
method()
File "C:\Ny mapp\serverpy.py", line 44, in do_GET
self.wfile.write(f.read())
File "C:\Python34\lib\socket.py", line 391, in write
return self._sock.send(b)
TypeError: 'str' does not support the buffer interface
The script 剧本
#!/usr/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.path="/index.html"
try:
#Check the file extension required and
#set the right mime type
sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True
if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
#Handler for the POST requests
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print("Your name is: %s" % form["your_name"].value)
self.send_response(200)
self.end_headers()
self.wfile.write("Thanks %s !" % form["your_name"].value)
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print('Started httpserver on port ' , PORT_NUMBER)
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
Your error: 你的错误:
TypeError: 'str' does not support the buffer interface
means that in socket
, self._sock.send(b)
only accepts bytes
objects. 表示在
socket
, self._sock.send(b)
只接受bytes
对象。 So you need to send a bytes encoded string. 所以你需要发送一个字节编码的字符串。
Try using the following: 尝试使用以下内容:
def do_GET(self):
if self.path=="/":
self.path="/index.html"
try:
sendReply = False
if self.path.endswith(".html"):
mimetype='text/html'
sendReply = True
if self.path.endswith(".jpg"):
mimetype='image/jpg'
sendReply = True
if self.path.endswith(".gif"):
mimetype='image/gif'
sendReply = True
if self.path.endswith(".js"):
mimetype='application/javascript'
sendReply = True
if self.path.endswith(".css"):
mimetype='text/css'
sendReply = True
if sendReply == True:
#Open the static file requested and send it
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type',mimetype)
self.end_headers()
# save the contents
read = f.read()
# write the contents as bytes
self.wfile.write(bytes(read, 'utf-8'))
f.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
Use 'rb'
. 使用
'rb'
。 It's OK with webfont(.ttf;.woff;woff2) etc. webfont(.ttf; .woff; woff2)等没关系。
f = open(filepath, 'rb')
data = f.read()
self.wfile.write(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.