【问题标题】:Can you help to find the errors in the code你能帮忙找出代码中的错误吗
【发布时间】:2017-09-28 18:40:25
【问题描述】:
#!/usr/bin/env python3
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep

PORT_NUMBER = 8080

#This class will handles any incoming request from
#the browser 
class myHandler_RequestHandler(BaseHTTPRequestHandler):
    #Handler for the GET requests
    def do_GET(BaseHTTPRequestHandler, 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
                filename = open(curdir + sep + self.path) 
                self.wfile.write(bytes('filename',"utf8"))
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.end_headers()
                self.wfile.write(f.read())
                filename.decode("utf-8")
                filename.close()
            return


        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler_RequestHandler)
    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()

处理来自 ('127.0.0.1', 44598)TypeError:需要一个类似字节的对象,而不是'str'

【问题讨论】:

  • 您能在问题中提及您遇到了什么错误吗?
  • 请阅读How to Ask 并提供minimal reproducible example。至少:什么错误?
  • 处理来自 ('127.0.0.1', 44598) 的请求时发生异常 TypeError: a bytes-like object is required, not 'str'
  • 请编辑您的问题,错误(带有完整的回溯)属于它,因为它需要帮助您!

标签: python python-3.x


【解决方案1】:

首先,我没有看到声明变量f(文件)的位置。此外,您的字节调用不会从文件中读取字节。此外,将“if”s 更改为“elif”s。此外,使用 os.path.join() 连接文件路径或使用路径操作“/”。 要在 Py3 中读取文件,请使用:

fp = os.path.join(os.getcwd(), self.path)
with open(fp, 'rb') as f:
  buf = f.read() # buf now is bytes/content of the file
self.wfile.write(buf)

类似的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多