【问题标题】:How to get the requested file name in BaseHTTPServer in python?如何在 python 的 BaseHTTPServer 中获取请求的文件名?
【发布时间】:2014-11-28 07:28:14
【问题描述】:

我正在用 Python 编写一个 HTTP 服务器,我需要从发送的请求中获取所请求文件的名称,以便从服务器发送

Here is my code:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import os.path
from os import curdir, sep

PortNum = 8080


class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests
def do_GET(self):
    if self.path=="/":
        print os.path.splitext(self.path)[0]
        print self.path
        print "my code"
        self.path="/index_example3.html"

    try:
        #Check the file extension required and
        #set the right mime type


        extension = os.path.splitext(self.path)[-1]
        mime_types = {
       '.html': 'text/html',
       '.jpg':'image/jpg',
        '.gif': 'image/gif',
       '.js': 'application/javascript',
       '.css': 'text/css',
        }

        mimetype = mime_types.get(extension)
        sendReply = mimetype is not None

        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.wfile.write(f.read())
            f.close()
        return
    except IOError:
        self.send_error(404,'File Not Found'% self.path)




try:
   #Create a web server and define thehandler to manage the
   #incoming request
   server = HTTPServer(('',PortNum),myHandler)
   print('Started httpserver on port ',PortNum)
   #wait forever for incoming http requests
   server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shuting down the web server'
    server.socket.close()

我已经使用 self.path 来获取整个路径,但它只包含一个“/”字符,当请求是“POST”请求时,它在这个库的文档页面中包含“/send”@987654321 @我不能罚款任何有用的东西

我想获取请求的文件名我不知道 self.path 到底包含什么。

【问题讨论】:

    标签: python http python-2.7 network-programming


    【解决方案1】:

    当我运行你的代码时,它看起来运行良好。

    当我输入localhost:8080/test.html,服务器打印出来

    127.0.0.1 - - [28/Nov/2014 16:55:36] "GET /test.html HTTP/1.1" 200 -

    这不是你想要的吗?

    【讨论】:

    • 这应该在评论中而不是答案中
    • 是的,你是对的,它工作正常,但是 POST 请求为什么包含“/send”呢?
    【解决方案2】:

    根据 Python BaseHTTPserver 库的文档:

    路径 包含请求路径。

    这样如果客户发送像127.1.1.1:8080这样的东西 self.path 只包含一个'/' 字符,但如果它像127.1.1.1:8080/index.html 一样的话

    self.path 包含'index.html' 没有问题

    但我不知道为什么在 POST 请求中 self.path 中存在 '/send'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多