1

I have the following server code. It creates python http server.

Right now, it only receives info sent by a client, but I want to be able to store whatever the client send to the server.

For example, if client sends "Hello World", then "Hello World" appears on server side, but it only displays it. I want to be able to store this received string in some variable.

Let's say.... string str, then if I do print str, then it prints "Hello World".

Could anyone tell me the way to accomplish this?

import time
import BaseHTTPServer


HOST_NAME = '127.0.0.1' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 8868 # Maybe set this to 9000.


class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(s):
        s.send_response(200)
    def do_GET(s):
        """Respond to a GET request."""
        s.send_response(200)

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

Whenever I run this server, and click button to send stuff to this server, then server displays the following.

Thu Oct 15 10:14:48 2015 Server Starts - 127.0.0.1:8882
127.0.0.1 - - [15/Oct/2015 10:14:52] "GET id=497&message=A%20typed%27char*%27 HTTP/1.1" 200 -

And I want to be able to store this GET id=497 blah blah to a variable inside function as string.

1 Answers1

1
  • What you see in the console is just logs that the server prints using the logging module.

  • the 's' parameter in your methods is misleading. use 'self'

  • the request information is stored as MyHandler attributes.

Example:

def do_HEAD(self):
    self.send_response(200)
def do_GET(self):
    """Respond to a GET request."""
    print('client', self.client_address)
    print('server', self.server)
    self.send_response(200)

See: https://docs.python.org/2/library/basehttpserver.html

Stephane Martin
  • 1,612
  • 1
  • 17
  • 25
  • So it's not possible to store logs in some variable? I tried your command, but it only displays ('server', ). This is not what I want. I want to be able to store logs?? in some variable. – Toshihiro M Sakurai Oct 16 '15 at 16:29
  • As you can see in my question, I want to be able to store 127.0.0.1 - - [15/Oct/2015 10:14:52] "GET id=497&message=A%20typed%27char*%27 HTTP/1.1" 200 - in some variable. Is this possible? – Toshihiro M Sakurai Oct 16 '15 at 16:31
  • Of course you can store whatever information is available in the 'self' object. Just write "blabla = self.attribute" instead of the print. Please read the linked documentation to have a list of available attributes. – Stephane Martin Oct 16 '15 at 16:39