mongoose.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # Copyright (c) 2004-2009 Sergey Lyubka
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20. #
  21. # $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $
  22. """
  23. This module provides python binding for the Mongoose web server.
  24. There are two classes defined:
  25. Connection: - wraps all functions that accept struct mg_connection pointer
  26. as first argument
  27. Mongoose: wraps all functions that accept struct mg_context pointer as
  28. first argument. All valid option names, settable via mg_set_option(),
  29. are settable/gettable as the attributes of the Mongoose object.
  30. In addition to those, two attributes are available:
  31. 'version': string, contains server version
  32. 'options': array of all known options.
  33. Creating Mongoose object automatically starts server, deleting object
  34. automatically stops it. There is no need to call mg_start() or mg_stop().
  35. """
  36. import ctypes
  37. import os
  38. class mg_header(ctypes.Structure):
  39. """A wrapper for struct mg_header."""
  40. _fields_ = [
  41. ('name', ctypes.c_char_p),
  42. ('value', ctypes.c_char_p),
  43. ]
  44. class mg_request_info(ctypes.Structure):
  45. """A wrapper for struct mg_request_info."""
  46. _fields_ = [
  47. ('request_method', ctypes.c_char_p),
  48. ('uri', ctypes.c_char_p),
  49. ('http_version', ctypes.c_char_p),
  50. ('query_string', ctypes.c_char_p),
  51. ('post_data', ctypes.c_char_p),
  52. ('remote_user', ctypes.c_char_p),
  53. ('remote_ip', ctypes.c_long),
  54. ('remote_port', ctypes.c_int),
  55. ('post_data_len', ctypes.c_int),
  56. ('status_code', ctypes.c_int),
  57. ('num_headers', ctypes.c_int),
  58. ('http_headers', mg_header * 64),
  59. ]
  60. class Connection(object):
  61. """A wrapper class for all functions that take
  62. struct mg_connection * as the first argument."""
  63. def __init__(self, mongoose, connection):
  64. self.m = mongoose
  65. self.conn = connection
  66. def get_header(self, name):
  67. val = self.m.dll.mg_get_header(self.conn, name)
  68. return ctypes.c_char_p(val).value
  69. def get_var(self, name):
  70. var = None
  71. pointer = self.m.dll.mg_get_var(self.conn, name)
  72. if pointer:
  73. # Make a copy and free() the returned pointer
  74. var = '' + ctypes.c_char_p(pointer).value
  75. self.m.dll.mg_free(pointer)
  76. return var
  77. def printf(self, fmt, *args):
  78. val = self.m.dll.mg_printf(self.conn, fmt, *args)
  79. return ctypes.c_int(val).value
  80. def write(self, data):
  81. val = self.m.dll.mg_write(self.conn, data, len(data))
  82. return ctypes.c_int(val).value
  83. class Mongoose(object):
  84. """A wrapper class for Mongoose shared library."""
  85. # Exceptions for __setattr__ and __getattr__: these attributes
  86. # must not be treated as Mongoose options
  87. _private = ('dll', 'ctx', 'version', 'callbacks')
  88. def __init__(self, **kwargs):
  89. dll_extension = os.name == 'nt' and 'dll' or 'so'
  90. self.dll = ctypes.CDLL('_mongoose.%s' % dll_extension)
  91. start = self.dll.mg_start
  92. self.ctx = ctypes.c_voidp(self.dll.mg_start()).value
  93. self.version = ctypes.c_char_p(self.dll.mg_version()).value
  94. self.callbacks = []
  95. for name, value in kwargs.iteritems():
  96. self.__setattr__(name, value)
  97. def __setattr__(self, name, value):
  98. """Set Mongoose option. Raises ValueError in option not set."""
  99. if name in self._private:
  100. object.__setattr__(self, name, value)
  101. else:
  102. code = self.dll.mg_set_option(self.ctx, name, value)
  103. if code != 1:
  104. raise ValueError('Cannot set option [%s] '
  105. 'to [%s]' % (name, value))
  106. def __getattr__(self, name):
  107. """Get Mongoose option."""
  108. if name in self._private:
  109. return object.__getattr__(self, name)
  110. else:
  111. val = self.dll.mg_get_option(self.ctx, name)
  112. return ctypes.c_char_p(val).value
  113. def __del__(self):
  114. """Destructor, stop Mongoose instance."""
  115. self.dll.mg_stop(self.ctx)
  116. def _make_c_callback(self, python_callback):
  117. """Return C callback from given Python callback."""
  118. # Create a closure that will be called by the shared library.
  119. def _cb(connection, request_info, user_data):
  120. # Wrap connection pointer into the connection
  121. # object and call Python callback
  122. conn = Connection(self, connection)
  123. python_callback(conn, request_info.contents, user_data)
  124. # Convert the closure into C callable object
  125. c_callback = ctypes.CFUNCTYPE(ctypes.c_voidp, ctypes.c_voidp,
  126. ctypes.POINTER(mg_request_info), ctypes.c_voidp)(_cb)
  127. # Store created callback in the list, so it is kept alive
  128. # during context lifetime. Otherwise, python can garbage
  129. # collect it, and C code will crash trying to call it.
  130. self.callbacks.append(c_callback)
  131. return c_callback
  132. def set_uri_callback(self, uri_regex, python_callback, user_data):
  133. self.dll.mg_set_uri_callback(self.ctx, uri_regex,
  134. self._make_c_callback(python_callback), user_data)
  135. def set_auth_callback(self, uri_regex, python_callback, user_data):
  136. self.dll.mg_set_auth_callback(self.ctx, uri_regex,
  137. self._make_c_callback(python_callback), user_data)
  138. def set_error_callback(self, error_code, python_callback, user_data):
  139. self.dll.mg_set_error_callback(self.ctx, error_code,
  140. self._make_c_callback(python_callback), user_data)
  141. def set_log_callback(self, python_callback):
  142. self.dll.mg_set_log_callback(self.ctx,
  143. self._make_c_callback(python_callback))