Package tlib :: Package base :: Module ApiMockServer |
[hide private]
[frames] | no frames]

# Source Code for Module tlib.base.ApiMockServer

     1  import BaseHTTPServer
     2  from SimpleHTTPServer import SimpleHTTPRequestHandler
     3  import socket
     4  import json
     5  from SocketServer import ThreadingMixIn
     6  import struct
     7  import os
     8
     9
    10 -class _MyHandler(SimpleHTTPRequestHandler):
    11      """
    12      Class for handling POST and GET request to our mock server.  To be used with the ApiMockServer
    13      """
    14
    15 -    def __init__(self, req, client_addr, server):
    16          SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
    17
    18 -    def do_GET(self):
    19          """
    20          Handles the GET requests for retrieving the mock data that was last stored in memory
    21
    22          Returns : (json) 'warning' = "No data in memory" if nothing has been previously stored.  Returns a mock json if
    23          something was previously stored.
    24          """
    25          self.send_response(200)
    26          self.send_header("Content-type", "text/json")
    27          self.end_headers()
    28          output = {}
    29
    30          if not self.server.jsonData or 'warning' in self.server.jsonData:
    31              output["warning"] = "No data in memory"
    32          else:
    33              output = self.server.jsonData
    34
    35          self.wfile.write(json.dumps(output))
    36
    37      #noinspection PyPep8Naming
    38 -    def do_POST(self):
    39          """
    40          Handles the POST request for putting a mock json response into memory for later retrieval with GET
    41
    42          Returns : (json) 'data' = 'Data has been saved to memory' if the data sent successfully saved.
    43          """
    44          try:
    45              self.send_response(200)
    46              self.send_header("Content-type", "text/json")
    47              length = int(self.headers.getheader('content-length'))
    48              data = self.rfile.read(length)
    49              self.server.jsonData = json.loads(data)
    50              self.end_headers()
    51              self.wfile.write('Data has been saved to memory')
    52          except ValueError:
    53              self.server.logger.error("The data sent to ApiMockServer was not in json format.  nothing saved")
    54              self.send_error(400, 'Not a json object. Data has not been saved to memory')
    55
    56
    57 -class ApiMockServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):
    58
    59      server_address = ('0.0.0.0', 8000)
    60      json_data = {}
    61      logger = None
    62      my_ip = None
    63
    64 -    def __init__(self, logger):
    65
    66          BaseHTTPServer.HTTPServer.__init__(self, self.server_address, _MyHandler)
    67          self.logger = logger
    68          self.my_ip = self.get_lan_ip()
    69
    70      @staticmethod
    71 -    def get_interface_ip(ifname):
    72          s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    73          #noinspection PyUnresolvedReferences
    74          return socket.inet_ntoa(fcntl.ioctl(
    75                                  s.fileno(),
    76                                  0x8915, struct.pack('256s', ifname[:15])
    77                                  )[20:24])
    78
    79 -    def get_lan_ip(self):
    80          ip = socket.gethostbyname(socket.gethostname())
    81          if ip.startswith("127.") and os.name != "nt":
    82              interfaces = ["eth0", "eth1", "eth2", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0"]
    83
    84              for ifname in interfaces:
    85                  try:
    86                      ip = self.get_interface_ip(ifname)
    87                      break
    88
    89                  except IOError:
    90                      pass
    91          return ip
    92