2

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.

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

This rather sould be in a comment and not an answer
yes you are right it works fine but how about the POST requests why it contains '/send'?
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.