BaseHTTPRequestHandler Extension - Retrieving Published Data

I saw this question, but I want to have access to POST'd data external from the handler.

Is there any way to do this?

Below is the code:

import BaseHTTPServer

HOST_NAME = ''
PORT_NUMBER=8088

postVars = ''

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_POST(s):
        s.send_response(200)
        s.end_headers()
        varLen = int(s.headers['Content-Length'])
        postVars = s.rfile.read(varLen)
        print postVars

server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

try:
    httpd.handle_request()
except KeyboardInterrupt:
    pass

print postVars
httpd.server_close()

postVars is evaluated during the Handler, but not after MyHandler

+3
source share
2 answers

This is because it postVarslocally depends on the MyHandler instance created by HTTPServer. If you want to access it, declare it postVarsas a global variable at the beginning of the method do_POST.

def do_POST(s):
  global postVars
  s.send_response(200)
  s.end_headers()
  varLen = int(s.headers['Content-Length'])
  postVars = s.rfile.read(varLen)

In any case, I'm not sure what you want to achieve using variables outside the server and the requestHandler context.

+9
source

BaseHTTPServer BaseHTTPRequestHandler. , postVars .

BaseHTTPServer :

class MyServer(BaseHTTPServer.HTTPServer):
    def __init__(self, *args, **kwargs):
         # Because HTTPServer is an old-style class, super() can't be used.
         BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
         self.postVars = None

postVars , :

class class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

def do_POST(s):
    s.send_response(200)
    s.end_headers()
    varLen = int(s.headers['Content-Length'])
    s.server.postVars = s.rfile.read(varLen)
    print postVars

MyServer BaseHTTPServer:

server_class = MyServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

print httpd.postVars

, .

+2

All Articles