example.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # This is Python example on how to use Mongoose embeddable web server,
  2. # http://code.google.com/p/mongoose
  3. #
  4. # Before using the mongoose module, make sure that Mongoose shared library is
  5. # built and present in the current (or system library) directory
  6. import mongoose
  7. import sys
  8. # This function is a "/foo" URI handler: it will be called each time
  9. # HTTP request to http://this_machine:8080/foo made.
  10. # It displays some request information.
  11. def uri_handler(conn, info, data):
  12. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  13. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  14. conn.printf('%s %s\n', info.request_method, info.uri)
  15. conn.printf('my_var: %s\n', conn.get_var('my_var') or '<not set>')
  16. conn.printf('HEADERS: \n')
  17. for header in info.http_headers[:info.num_headers]:
  18. conn.printf(' %s: %s\n', header.name, header.value)
  19. # This function is 404 error handler: it is called each time requested
  20. # document is not found by the server.
  21. def error_404_handler(conn, info, data):
  22. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  23. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  24. conn.printf('Document %s not found!\n', info.uri)
  25. # Create mongoose object, and register '/foo' URI handler
  26. # List of options may be specified in the contructor
  27. server = mongoose.Mongoose(root='/tmp', ports='8080')
  28. # Register custom URI and 404 error handler
  29. server.set_uri_callback('/foo', uri_handler, 0)
  30. server.set_error_callback(404, error_404_handler, 0)
  31. # Any option may be set later on by setting an attribute of the server object
  32. server.ports = '8080,8081' # Listen on port 8081 in addition to 8080
  33. # Mongoose options can be retrieved by asking an attribute
  34. print 'Starting Mongoose %s on port(s) %s ' % (server.version, server.ports)
  35. print 'CGI extensions: %s' % server.cgi_ext
  36. # Serve connections until 'enter' key is pressed on a console
  37. sys.stdin.read(1)
  38. # Deleting server object stops all serving threads
  39. print 'Stopping server.'
  40. del server