example.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. # Handle /show and /form URIs.
  9. def uri_handler(conn, info):
  10. if info.uri == '/show':
  11. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  12. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  13. conn.printf('%s %s\n', info.request_method, info.uri)
  14. if info.request_method == 'POST':
  15. content_len = conn.get_header('Content-Length')
  16. post_data = conn.read(int(content_len))
  17. my_var = conn.get_var(post_data, 'my_var')
  18. else:
  19. my_var = conn.get_qsvar(info, 'my_var')
  20. conn.printf('my_var: %s\n', my_var or '<not set>')
  21. conn.printf('HEADERS: \n')
  22. for header in info.http_headers[:info.num_headers]:
  23. conn.printf(' %s: %s\n', header.name, header.value)
  24. return mongoose.MG_SUCCESS
  25. elif info.uri == '/form':
  26. conn.write('HTTP/1.0 200 OK\r\n'
  27. 'Content-Type: text/html\r\n\r\n'
  28. 'Use GET: <a href="/show?my_var=hello">link</a>'
  29. '<form action="/show" method="POST">'
  30. 'Use POST: type text and submit: '
  31. '<input type="text" name="my_var"/>'
  32. '<input type="submit"/>'
  33. '</form>')
  34. return mongoose.MG_SUCCESS
  35. else:
  36. return mongoose.MG_ERROR
  37. # Invoked each time HTTP error is triggered.
  38. def error_handler(conn, info):
  39. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  40. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  41. conn.printf('HTTP error: %d\n', info.status_code)
  42. return mongoose.MG_SUCCESS
  43. # Create mongoose object, and register '/foo' URI handler
  44. # List of options may be specified in the contructor
  45. server = mongoose.Mongoose(document_root='/tmp',
  46. new_request_handler=uri_handler,
  47. http_error_handler=error_handler,
  48. listening_ports='8080')
  49. print 'Starting Mongoose server, press enter to quit'
  50. sys.stdin.read(1)
  51. # Deleting server object stops all serving threads
  52. print 'Stopping server.'
  53. del server