HTTP Server

Some of the following examples require a working web server. If you have already installed a web server and you have a working web back end, such as PHP, Ruby On Rails or TurboGears, to handle requests, you can use it-this applies also to environment D. You should be able to port the server-side examples to your framework of choice without too much effort.

If you do not have such a back end already in place, now is a good time to install one! However, if you want to get into action quickly, a simple web server with a naive request-handling mechanism is provided. The code relies on two HTTP server modules in Python's standard library, BaseHTTPServer and SimpleHTTPServer, which implement a rudimentary HTTP server.

The HTTP server example is divided into two parts. Example 75 implements a generic web server that is re-used in later examples. Example 76 shows simple request handlers that demonstrate the server usage. The later examples implement their own functions. You should combine the generic web server (Example 75) and example-specific functions to make the full server.

Example 75: HTTP server import BaseHTTPServer, SimpleHTTPServer, cgi, traceback, json class Server(BaseHTTPServer.HTTPServer): allow_reuse_address = True class Handler(SimpleHTTPServer. SimpleHTTPRequestHandler):

size = int(self.headers["Content-length"]) msg = json.read(self.rfile.read(size)) reply = process_json(msg) except:

self.send_response(50 0) self.end_headers()

print "Function process_json failed:"

traceback.print_exc()

return self.send_response(2 00) self.end_headers()

self.wfile.write(json.write(reply))

def do_GET(self):

path, query_str = self.path.split("?", 1) query = cgi.parse_qs(query_str) else:

try:

mime, reply = process_get(path, query) except:

self.send_response(50 0) self.end_headers()

print >> self.wfile, "Function process_query failed: \n"

traceback.print_exc(file=self.wfile)

return

self.

.send_response(20 0)

self.

.send_header("mime-type",

, mime)

self.

.end_headers()

self.

.wfile.write(reply)

When a web browser requests a URL from this server, the function do_GET is called. First, the function checks whether the URL contains any parameters, specified after a question mark. If it does, the parameters are parsed into the dictionary query with function cgi .parse_qs (). Otherwise, query parameters are initialized with an empty dictionary.

According to the HTTP specification, GET requests must not change the internal state of the server. All information which affects the server is sent in POST requests and encoded in JSON. Replies to the POST requests are also encoded in JSON.

Example 76: Simple request handlers for the HTTP server

def process_json(msg): return msg

def process_get(path, query):

return "text/plain", "Echo: path '%s' and query '%s''

% path, query)

def init_server():

print "Server starts"

httpd = Server((", 9000), Handler) httpd.serve_forever()

Each example may perform example-specific initialization in the function init_server().

The requests are handled by the functions process_get () and process_j son (). The function process_get () is given two parameters: the requested path from the URL (path) and the parsed parameters (query). The actual task performed by the function depends on the example. The function returns two values: the MIME type of the response, which tells whether the response contains, for example, HTML, plain text or an image, and the actual response in a string that is sent back to the requester. The requester is typically a web browser.

The function process_j son () is given the decoded JSON request as a sole parameter. It may return any Python data structure that is then encoded in JSON and returned to the requester. The requester is typically a PyS60 program.

Each of the following examples, which require a web server, provides its own init_server (), process_get () and process_j son () functions to handle tasks specific to that particular example. With each example, you should replace these functions in the web server code accordingly.

As with the TCP server, you can pick another port for the server instead of the default, 9000. Once the above code is running on your server, you can try to connect to it with a web browser on your PC and on your phone. The address is of the form http://192.168.0.2:9000/test/, where the IP address corresponds to that of your server. If everything goes well, the browser shows an echo message with the requested path and parameters.

0 0

Post a comment

  • Receive news updates via email from this site