因此,我在python 3中构建了BaseHTTPRequestHandler图像服务器,并在do_GET函数中按如下方式处理get请求:
if self.path.split('?')[0] == '/get/image':
os.chdir("/var/www/Static/images")
self._set_headers()
for file in glob.glob("*welcome-image*"):
f = open('/var/www/Static/images/' + file, 'rb')
self.wfile.write(f.read())
f.close
如果我随后转到服务器URL,则它会提供请求的图像,但是如果我再试一次,则会得到502(我使用Nginx proxypass,因此这使我得到了502),我必须等待15秒才能成功收到请求图片。
奇怪的是,如果我删除if语句,它将起作用,并且每次我要求它时都会返回一个图像。另外,如果我尝试发出请求,但它给我一个502,则看起来do_GET函数未运行,因为如果我在该函数的顶部打印一些文本,则它不会打印。
这是整个脚本:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os, glob, base64, random, json, io, string, _thread
from urllib.parse import urlparse
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
activeRequests = []
class ImageServer(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-type")
self.end_headers()
def do_HEAD(self):
self._set_headers()
def do_OPTIONS(self):
self._set_headers()
def do_GET(self):
if self.path.split('?')[0] == '/get/image':
os.chdir("/var/www/Static/images")
self._set_headers()
for file in glob.glob("*welcome-image*"):
f = open('/var/www/Static/images/' + file, 'rb')
self.wfile.write(f.read())
f.close
def do_POST(self):
self._set_headers()
self.send_header('Content-type', 'text/html')
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
post = json.loads(body.decode('utf8').replace("'", '"'))
if self.path == '/upload/meta':
data = {}
data['response'] = "received"
data['ID'] = id_generator()
post['ID'] = data['ID']
post['b64'] = [0] * post['chunks'];
activeRequests.append(post)
self.wfile.write(bytes(json.dumps(data), "utf8"))
elif self.path == '/upload/image':
info = {}
for active in activeRequests:
if(active['ID']) == post['ID']:
info = active
active['b64'][post['chunk_id']] = post['chunk']
if post['chunk_id'] == active['chunks'] -1:
self.buildImage(info)
self.wfile.write(bytes(json.dumps(post), "utf8"))
break
def buildImage(self, b64_data):
data = list(filter((0).__ne__, b64_data['b64']))
imgdata = base64.b64decode(''.join(data).split(',')[1] + "==")
cut = b64_data['name'].split('.');
filename = b64_data['hash'] + '?' + cut[0] + '?' + b64_data['for'] + '.' + cut[1]
with open('/var/www/Static/images/' + filename, 'wb') as f:
image = f.write(imgdata)
print('Image Uploaded')
if __name__ == "__main__":
print('starting server...')
server_address = ('localhost', 1337)
httpd = HTTPServer(server_address, ImageServer)
print('server is running!');
httpd.serve_forever()