Created
April 26, 2020 20:32
-
-
Save burrussmp/81ea93f33e0a0c57d16406bcc36212f3 to your computer and use it in GitHub Desktop.
A POST request handler to parse and receive a PNG image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def deal_post_data(self): | |
ctype, pdict = cgi.parse_header(self.headers['Content-Type']) | |
pdict['boundary'] = bytes(pdict['boundary'], "utf-8") | |
pdict['CONTENT-LENGTH'] = int(self.headers['Content-Length']) | |
if ctype == 'multipart/form-data': | |
form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) | |
# typeOfImage = form["Type"].value + '.png' | |
bbox = { | |
'x':int(form["x"].value), | |
'y':int(form["y"].value), | |
'width':int(form["width"].value), | |
'height':int(form["height"].value) | |
} | |
try: | |
byteThings = b"" | |
if isinstance(form["file"], list): | |
for record in form["file"]: | |
#open("./%s"%name, "wb").write(record.file.read()) | |
byteThings += record.file.read() | |
else: | |
#open("./%s"%name, "wb").write(form["file"].file.read()) | |
byteThings += form["file"].file.read() | |
nparr = np.fromstring(byteThings, np.uint8) | |
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
cropped_img = processor.crop(img,bbox['x'],bbox['width'],bbox['y'],bbox['height']) | |
processor.set_image(form["Type"].value,cropped_img) | |
except IOError: | |
return (False, "Can't create file to write, do you have permission to write?") | |
return (True, "Files uploaded",form["Type"].value) | |
def do_POST(self): | |
r, info,typeOfImage = self.deal_post_data() | |
print(r, info, "by: ", self.client_address) | |
processor.processImage(typeOfImage) | |
f = io.BytesIO() | |
message = '' | |
if r: | |
self.send_response(200) | |
self.end_headers() | |
message = processor.message() | |
else: | |
self.send_response(500) | |
self.end_headers() | |
message = 'error' | |
f.write(message.encode()) | |
self.wfile.write(f.getvalue()) | |
f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment