Advertisement
Guest User

Untitled

a guest
Jun 14th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. #!/usr/bin/python
  2. import json
  3. import psycopg2
  4. import urlparse
  5.  
  6. import actions
  7. from my_exceptions import HttpException
  8.  
  9. conn = psycopg2.connect("dbname=thumbtack_crawler user=journey4712 password=abcde")
  10. action_map = {
  11.     'checkIn':actions.CheckIn,
  12.     'checkOut':actions.CheckOut,
  13. }
  14.  
  15. class Response:
  16.     code_text = {
  17.         200: 'OK',
  18.         400: 'Invalid Request',
  19.         404: 'Not Found',
  20.     }
  21.     msg = ''
  22.  
  23.     def __init__(self, start_response):
  24.         self.code = 500
  25.         self.output_data = ['']
  26.         self.start_response = start_response
  27.  
  28.     def error(self, code, msg):
  29.         """
  30.        Sets up an HTTP error code
  31.        """
  32.         self.code = code
  33.         self.output_data.append('<h2>%d %s</h2>' % (code, msg))
  34.  
  35.     def exception(self, exception):
  36.         """
  37.  
  38.       Outputs an exception
  39.        """
  40.         if isinstance(exception, HttpException):
  41.             self.error(exception.code, exception.msg)
  42.         else:
  43.             self.error(500, exception)
  44.  
  45.     def output(self, msg, result='success'):
  46.         """
  47.        Outputs a json structure
  48.        """
  49.         self.code = 200
  50.         if type(msg) == 'string':
  51.             msg = {'message':msg}
  52.         self.output_data.append(json.dumps({'result':result, 'data':msg}))
  53.  
  54. def myapp(environ, start_response):
  55.     query = urlparse.parse_qs(environ["QUERY_STRING"])
  56.     response = Response(start_response)
  57.     if "r" not in query:
  58.         response.error(404, 'Route not specified\n')
  59.     elif query["r"][0] not in action_map:
  60.         response.error(404, 'Route not available: %s\n' % (query["r"][0],))
  61.     else:
  62.         action = action_map[query["r"][0]](conn, environ)
  63.         try:
  64.             action.run(query, response)
  65.         except HttpException as exception:
  66.             response.exception(exception)
  67.     start_response('%d %s' % (response.code, response.code_text[response.code]),
  68.         [('Content-Type', 'text/html; charset=utf-8')])
  69.     return response.output_data
  70.  
  71. if __name__ == '__main__':
  72.    from wsgiref.simple_server import make_server
  73.     make_server('', 4321, myapp).handle_request()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement