【发布时间】: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