How to get the requested file name in BaseHTTPServer in python?

允我心安 提交于 2021-02-08 09:10:40

问题


I'm writing an HTTP server in Python and I need to get the name of the requested file from the sent request in order to send from from the server

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()

I have used the self.path to get the whole path but it only contains a '/' character and the when the request is a "POST" request it contains '/send' in the documentation page of this library HERE I couldn't fine any thing useful

I want to get the file name requested I don't know what self.path contains really.


回答1:


When I run your codes, it looks work well.

When I entered localhost:8080/test.html, server printed

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

Isn't it what you want to get?




回答2:


According to the documentation of the Python BaseHTTPserver library :

path Contains the request path.

so that if a client send sth like 127.1.1.1:8080 the self.path only contains a '/' character but if it is sth like 127.1.1.1:8080/index.html

the self.path contains 'index.html' and there is no problem

but I don't know why in a POST request there exists a '/send' in the self.path



来源:https://stackoverflow.com/questions/27183844/how-to-get-the-requested-file-name-in-basehttpserver-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!