example.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 EventHandler(event, conn):
  10. info = conn.info
  11. if event == mongoose.HTTP_ERROR:
  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('HTTP error: %d\n', info.status_code)
  15. return True
  16. elif event == mongoose.NEW_REQUEST and info.uri == '/show':
  17. conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
  18. conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
  19. conn.printf('%s %s\n', info.request_method, info.uri)
  20. if info.request_method == 'POST':
  21. content_len = conn.get_header('Content-Length')
  22. post_data = conn.read(int(content_len))
  23. my_var = conn.get_var(post_data, 'my_var')
  24. else:
  25. my_var = conn.get_var(info.query_string, 'my_var')
  26. conn.printf('my_var: %s\n', my_var or '<not set>')
  27. conn.printf('HEADERS: \n')
  28. for header in info.http_headers[:info.num_headers]:
  29. conn.printf(' %s: %s\n', header.name, header.value)
  30. return True
  31. elif event == mongoose.NEW_REQUEST and info.uri == '/form':
  32. conn.write('HTTP/1.0 200 OK\r\n'
  33. 'Content-Type: text/html\r\n\r\n'
  34. 'Use GET: <a href="/show?my_var=hello">link</a>'
  35. '<form action="/show" method="POST">'
  36. 'Use POST: type text and submit: '
  37. '<input type="text" name="my_var"/>'
  38. '<input type="submit"/>'
  39. '</form>')
  40. return True
  41. elif event == mongoose.NEW_REQUEST and info.uri == '/secret':
  42. conn.send_file('/etc/passwd')
  43. return True
  44. else:
  45. return False
  46. # Create mongoose object, and register '/foo' URI handler
  47. # List of options may be specified in the contructor
  48. server = mongoose.Mongoose(EventHandler,
  49. document_root='/tmp',
  50. listening_ports='8080')
  51. print ('Mongoose started on port %s, press enter to quit'
  52. % server.get_option('listening_ports'))
  53. sys.stdin.read(1)
  54. # Deleting server object stops all serving threads
  55. print 'Stopping server.'
  56. del server