2

I am trying to read data sent to python's http.server from a local javascript program posted with AJAX. Everything works in python 2.7 as in this example, but now in python 3+ I can't access the header anymore to get the file length.

  # python 2.7 (works!)
  class handler_class(SimpleHTTPServer.SimpleHTTPRequestHandler):

      def do_POST(self):
          if self.path == '/data':
              length = int(self.headers.getheader('Content-Length'))
              NewData = self.rfile.read(length)

I've discovered I could use urllib.request, as I have mocked up below. However, I am running on a localhost and don't have a full url as I've seen in the examples, and I am starting to second guess if this is even the right way to go? Frustratingly, I can see the content-length printed out in the console, but I can't access it.

  # python 3+ (url?)

  import urllib.request     
  class handler_class(http.server.SimpleHTTPRequestHandler):

      def do_POST(self):
          if self.path == '/data':
              print(self.headers) # I can see the content length here but cannot access it!
              d = urllib.request.urlopen(url) # what url?
              length = int(d.getheader('Content-Length'))
              NewData = self.rfile.read(length)

Various url's I have tried are:

  self.path 
  http://localhost:8000/data 
  /data

and I generally get this error:

  ValueError: unknown url type: '/data'

So why is 'urllib.request' failing me and more importantly, how does one access 'self.header' in this Python3 world?

Community
  • 1
  • 1
o1sound
  • 480
  • 7
  • 22
  • Please include the headers that you can print, but cannot "access". You don't want to use urllib to open a new connection to a server - that would be pointless here (the reason you can't find a suitable url to use). – Gerrat Oct 30 '14 at 21:20
  • 2
    Did you try: `self.headers['Content-Length']` ? – Gerrat Oct 30 '14 at 21:30
  • please give the whole traceback and the lines, the error occurs. – Daniel Oct 30 '14 at 21:44
  • @Gerrat that's exactly it! I'm just not familiar enough with python to have tried `self.headers['Content-Length']`, but it quite happily spit out the number of bytes. Thank you. – o1sound Oct 31 '14 at 00:45

0 Answers0