11

I'm running the code below to get POST messages. How do I get the file (sent with POST) and how do I respond with HTTP status code 200 OK?

#!/usr/bin/env python

import ssl
import BaseHTTPServer, SimpleHTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler

class HttpHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        print "got POST message"
        # how do I get the file here?
        print self.request.FILES


httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), HttpHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()    



$curl -X POST -d @../some.file https://localhost:4443/resource --insecure

AttributeError: 'SSLSocket' object has no attribute 'FILES'

Bob
  • 10,741
  • 27
  • 89
  • 143

2 Answers2

11

BaseHTTPRequestHandler will process the first line and the headers of the http request then leave the rest up to you. You need to read the remainder of the request using BaseHTTPRequestHandler.rfile

You can use self.send_response(200) to respond with 200 OK

Given the curl command you have specified the following should answer your question:

class HttpHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        file_content = self.rfile.read(content_length)

        # Do what you wish with file_content
        print file_content

        # Respond with 200 OK
        self.send_response(200)

Note that by using -d @../some.file in your curl command you are saying "this is an ascii file, oh and strip out the newlines and carriage returns please", thus there could be differences between the file you are using and the data you get in the request. Your curl command does not emulate an html form file-upload like post request.

Jeremy Allen
  • 6,434
  • 2
  • 26
  • 31
-1

It is generally available in

request.FILES

dictionary

hspandher
  • 15,934
  • 2
  • 32
  • 45