在python中如何通过web服务器将URL作为回复发送回
我已经用python编写了这个HTTP web服务器,它只向浏览器/客户机发送回复“web即将到来!”,但是我希望这个web服务器应该发回客户机给出的URL,就像我编写的一样在python中如何通过web服务器将URL作为回复发送回,python,Python,我已经用python编写了这个HTTP web服务器,它只向浏览器/客户机发送回复“web即将到来!”,但是我希望这个web服务器应该发回客户机给出的URL,就像我编写的一样 http://localhost:13555/ChessBoard_x16_y16.bmp 然后服务器应该回复相同的url,而不是“网站马上就来!”消息。 请告诉我怎么做 服务器代码: import sys import http.server from http.server import HTTPServer fro
http://localhost:13555/ChessBoard_x16_y16.bmp
然后服务器应该回复相同的url,而不是“网站马上就来!”消息。
请告诉我怎么做
服务器代码:
import sys
import http.server
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
#import usb.core
class MyHandler(SimpleHTTPRequestHandler): #handles client requests (by me)
#def init(self,req,client_addr,server):
# SimpleHTTPRequestHandler.__init__(self,req,client_addr,server)
def do_GET(self):
response="Website Coming Soon!"
self.send_response(200)
self.send_header("Content-type", "application/json;charset=utf-8")
self.send_header("Content-length", len(response))
self.end_headers()
self.wfile.write(response.encode("utf-8"))
self.wfile.flush()
print(response)
HandlerClass = MyHandler
Protocol = "HTTP/1.1"
port = 13555
server_address = ('localhost', port)
HandlerClass.protocol_version = Protocol
try:
httpd = HTTPServer(server_address, MyHandler)
print ("Server Started")
httpd.serve_forever()
except:
print('Shutting down server due to some problems!')
httpd.socket.close()
你可以按你的要求去做,但有点复杂 当客户端(例如web浏览器)连接到您的web服务器时,它会发送如下所示的请求:
GET /ChessBoard_x16_y16.bmp HTTP/1.1
Host: localhost:13555
这假设您的客户机正在使用HTTP/1.1,这可能适用于您现在所能找到的任何东西。如果您希望使用HTTP/1.0或更早版本的客户端,那么使用起来就困难多了,因为没有Host:
header
使用Host
头的值和作为GET
请求参数传递的路径,您可以构造一个URL,在许多情况下,该URL将与客户端使用的URL相匹配
但它并不一定在所有情况下都匹配:
- 客户端和服务器之间可能有一个代理,在这种情况下,代码看到的路径和主机名/端口可能与客户端使用的路径和主机名/端口不同
- 可能存在修改目标ip地址和/或端口的数据包操作规则,以便代码看到的连接与客户端使用的参数不匹配
do_GET
方法中,您可以通过
self.headers
属性和通过self.path
的请求路径。例如:
def do_GET(self):
response='http://%s/%s' % (self.headers['host'],
self.path)