连接到Python HTTP服务器时出错

丹尼尔·达克(Daniel Darko)

我的服务器代码出现错误。它一直困扰着浏览器尝试连接到它。我真的不知道这可能是什么。有人可以看看它,并指出正确的方向吗?

错误代码是

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

剧本

#!/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()
扎克·盖茨

您的错误:

TypeError: 'str' does not support the buffer interface

表示中的socketself._sock.send(b)仅接受bytes对象。因此,您需要发送一个字节编码的字符串。

尝试使用以下内容:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用IDE连接到Openshift服务器时出错

连接到 MS SQL 服务器时出错

尝试从Gitea连接到AD服务器时出错

连接到MongoDb Atlas服务器时出错

Celery:连接到RabbitMQ服务器时出错

调用连接到 SQL 服务器的函数时出错

连接到WebSockets NodeJS Express服务器时出错

WinError 10060尝试使用Python PySFTP模块连接到远程服务器时出错

连接APNS服务器时出错

连接到 0.0.0.0 时 Python HTTP 服务器不工作

连接到Python服务器

mongodb失败:连接到数据库服务器时出错:没有可访问的服务器

“ psql:无法连接到服务器:连接被拒绝”连接到远程数据库时出错

错误:无法连接到服务器 127.0.0.1:27017,连接尝试失败:SocketException:连接到 127.0.0.1:27 时出错

连接到 nodejs 服务器时出错找不到 node-restful

通过特定客户端连接到centos服务器时出错

easyRTC连接到socket.io服务器时出错

连接到本地数据库服务器时出错

使用C#和.NET 4.5连接到SSL服务器时出错

550连接到FTP服务器时出错。仅在C#中发生

Android - 尝试连接到本地服务器时出错(Xampp)

连接到SQL Server时出错。服务器未找到或无法访问

从RSocket-Java客户端连接到Spring Boot RSocket服务器时出错

从Azure逻辑应用连接到Azure SQL服务器时出错

将Android客户端连接到NodeJS中的套接字服务器时出错

SharePoint Designer:连接到我的客户生产服务器时出错

使用JSP在tomcat服务器中连接到Oracle数据库时出错

使用JDBC连接到远程MySQL(主机gator)服务器时出错

从PHP页面连接远程服务器时出错