Novice question re. BaseHTTPRequestHandler and receiving data...
I've been using BaseHTTPRequestHandler to receive JSON strings passed as data to my URI. I now need to receive both JSON strings and ascii files. How can I tell that I've received both JSON data and a separate flat file? How do I access the data in the file?
What if I've received multiple files?
BTW, I just ran a test by calling my URI from Postman & see the following headers:
headers: Host: localhost:6081
Content-Type: application/x-www-form-urlencoded
User-Agent: python-requests/2.2.1 CPython/3.4.0 Linux/3.13.0-35-generic
Accept: */*
Accept-Encoding: gzip, deflate, compress
Content-Length: 403
Thank you!
Ben
The answer is in the CGI library. Refer to the following StackOverflow post: Simple Python WebServer. The second answer in that post was most useful for us.
Here is some test code that you might find useful to print out what's going on behind the scenes, especially if you're trying to receive multiple files in one post:
print("command: " + self.command + "\npath: " + self.path + "\nrequest_version: " \
+ self.request_version + "\nheaders: " + str(self.headers))
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type'],
})
print("\nform:", str(form))
print("\nform['file'].filename:", form['file'].filename)
filename = form['file'].filename
data = form['file'].file.read()
open("/tmp/%s" % filename, "wb").write(data)
print('\ndata:', data)