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