簡體   English   中英

如何在python中的BaseHTTPServer中獲取請求的文件名?

[英]How to get the requested file name in BaseHTTPServer in python?

我正在用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', 這里我無法罰款任何有用的東西

我想獲取請求的文件名,但我不知道self.path真正包含什么。

當我運行您的代碼時,它看起來運行良好。

當我輸入localhost:8080 / test.html時,服務器已打印

127.0.0.1--[2014年11月28日16:55:36]“ GET / test.html HTTP / 1.1” 200-

這不是你想要的嗎?

根據Python BaseHTTPserver庫的文檔:

path包含請求路徑。

這樣一來,如果客戶端發送的內容類似於127.1.1.1:8080則self.path僅包含一個'/'字符,但如果發送的內容類似於127.1.1.1:8080/index.html

self.path包含'index.html' ,沒有問題

但是我不知道為什么在POST請求中self.path中存在一個'/send'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM