我目前有以下代码:
from BaseHTTPServer import BaseHTTPRequestHandler
from pathlib import Path
from random import randint
import json
import random
example = 'logs/example.json'
class GetHandler(BaseHTTPRequestHandler):
# Slurp data from file
def dummy_data(self):
json_result = Path(example)
if json_result.is_file():
return json.load(open(example))
# Return data or empty
def random_selection(self):
data = self.dummy_data()
try:
return random.sample(data, randint(1, len(data)+50))
# Purposefully introduce entropy
except ValueError:
return ''
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(self.random_selection()))
return
if __name__ == '__main__':
from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 8080), GetHandler)
print 'Starting server at http://127.0.0.1:8080'
server.serve_forever()
我修改了/etc/hosts
如下:
server-0001 server-0002 server-0003 server-0004 127.0.0.1
我正在寻找一种方法让服务器0001-4重定向到127.0.0.1:8080
,但我没有看到如何?这与/etc/resolv.conf
有关吗?我正在使用OSX,但希望任何* nix解决方案都能正常工作我希望(除非ipfw明显,因为我们不再像理智的人那样)。
答案 0 :(得分:0)
看起来最贴心的答案是修补/etc/hosts
,然后将BaseHTTPServer
的端口更改为80
。这并不能解决原始问题,但这是一个公平的妥协。
修补脚本:
#!/bin/bash
# ensure running as root
if [ "$(id -u)" != "0" ] ; then
exec sudo "$0" "$@"
fi
if ! grep "^#- marker " /etc/hosts ; then
echo -e '\n##+ marker' >> /etc/hosts
while read server ; do
[ 'x' != "${server}x" ] && echo -e "127.0.0.1 ${server}.io www.${server}.io" >> /etc/hosts
done <read/servers.txt
echo -e '\n##- marker' >> /etc/hosts
fi
对Python的修改
....
def main():
try:
server = HTTPServer(('', 80), GetHandler)
print '->> Starting server at http://127.0.0.1:80 and all patched hosts'
server.serve_forever()
except KeyboardInterrupt:
print '->> Interrupt received; closing server socket'
server.socket.close()
if __name__ == '__main__':
main()