Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import json
- import psycopg2
- import urlparse
- import actions
- from my_exceptions import HttpException
- conn = psycopg2.connect("dbname=thumbtack_crawler user=journey4712 password=abcde")
- action_map = {
- 'checkIn':actions.CheckIn,
- 'checkOut':actions.CheckOut,
- }
- class Response:
- code_text = {
- 200: 'OK',
- 400: 'Invalid Request',
- 404: 'Not Found',
- }
- msg = ''
- def __init__(self, start_response):
- self.code = 500
- self.output_data = ['']
- self.start_response = start_response
- def error(self, code, msg):
- """
- Sets up an HTTP error code
- """
- self.code = code
- self.output_data.append('<h2>%d %s</h2>' % (code, msg))
- def exception(self, exception):
- """
- Outputs an exception
- """
- if isinstance(exception, HttpException):
- self.error(exception.code, exception.msg)
- else:
- self.error(500, exception)
- def output(self, msg, result='success'):
- """
- Outputs a json structure
- """
- self.code = 200
- if type(msg) == 'string':
- msg = {'message':msg}
- self.output_data.append(json.dumps({'result':result, 'data':msg}))
- def myapp(environ, start_response):
- query = urlparse.parse_qs(environ["QUERY_STRING"])
- response = Response(start_response)
- if "r" not in query:
- response.error(404, 'Route not specified\n')
- elif query["r"][0] not in action_map:
- response.error(404, 'Route not available: %s\n' % (query["r"][0],))
- else:
- action = action_map[query["r"][0]](conn, environ)
- try:
- action.run(query, response)
- except HttpException as exception:
- response.exception(exception)
- start_response('%d %s' % (response.code, response.code_text[response.code]),
- [('Content-Type', 'text/html; charset=utf-8')])
- return response.output_data
- if __name__ == '__main__':
- from wsgiref.simple_server import make_server
- make_server('', 4321, myapp).handle_request()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement