example.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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):
  12. if info.uri != '/foo':
  13. return mongoose.MG_ERROR
  14. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  15. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  16. conn.printf('%s %s\n', info.request_method, info.uri)
  17. conn.printf('my_var: %s\n',
  18. conn.get_qsvar(info, 'my_var') or '<not set>')
  19. conn.printf('HEADERS: \n')
  20. for header in info.http_headers[:info.num_headers]:
  21. conn.printf(' %s: %s\n', header.name, header.value)
  22. return mongoose.MG_SUCCESS
  23. # This function is 404 error handler: it is called each time requested
  24. # document is not found by the server.
  25. def error_handler(conn, info):
  26. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  27. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  28. conn.printf('HTTP error: %d\n', info.status_code)
  29. return mongoose.MG_SUCCESS
  30. # Create mongoose object, and register '/foo' URI handler
  31. # List of options may be specified in the contructor
  32. server = mongoose.Mongoose(document_root='/tmp',
  33. new_request_handler=uri_handler,
  34. http_error_handler=error_handler,
  35. listening_ports='8080')
  36. print 'Starting Mongoose server, press enter to quit'
  37. sys.stdin.read(1)
  38. # Deleting server object stops all serving threads
  39. print 'Stopping server.'
  40. del server