ariofrio/oration

View on GitHub
templates/azure/py/WorkerRole/app/main.py

Summary

Maintainability
F
1 wk
Test Coverage
"""
Sets up a standard set of routes according to the Cicero API.

Posts tasks to an Azure Queue, see backgroundworker.py or
BackgroundWorker.java. Retrieves data from Azure Blob Storage.

(Automatically generated by Oration.)
"""

import os
import sys

import logging
import base64

import json
import wsgiref.handlers
import webapp2

from azure import blob, get_container, queue, get_queue

# Enable HTTP debugging http://stackoverflow.com/q/5022945
import httplib
from urllib2 import HTTPError
httplib.HTTPConnection.debuglevel = 1

class TaskRoute(webapp2.RequestHandler):
  def get(self):
    id = self.request.get('id') or self.request.get('task_id')
    logging.info("Getting status of task " + id)

    result = None
    try:
      task_info = json.loads(blob.get_blob(get_container('tasks'), id))
      task_info['result'] = 'success'
      result = task_info
    except HTTPError as e:
      if e.code == 404:
        result = {'result': 'failure', 'reason': 'not found'}
      else:
        raise e, None, sys.exc_info()[2]
    self.response.out.write(json.dumps(result))

  def put(self):
    allowed_functions = ['{{ function_name }}']
    function = self.request.get('function') or self.request.get('f')

    key_length = 16
    id = self.request.get('id')
    if not id:
      id = base64.b64encode(os.urandom(key_length), '-_')
    output_location = self.request.get('output_location') or self.request.get('output')
    if not output_location:
      output_location = base64.b64encode(os.urandom(key_length), '-_')

    logging.info("Posting task " + id + " for function " + function)

    if function in allowed_functions:
      queue.put_message(get_queue('tasks'), 
          json.dumps({'function': function, 'id': id,
                      'output_location': output_location}))

      result = {'result': 'success', 'id': id,
                'output_location': output_location}
      self.response.out.write(json.dumps(result))
    else:
      reason = 'Cannot add a task for function type ' + str(function)
      result ={'result': 'failure', 'reason': reason}
      self.response.out.write(json.dumps(result))

  def post(self):
    self.put()

  def delete(self):
    logging.info("NOT cancelling task: not implemented")
    result = {'result': 'not implemented'}
    self.response.out.write(result)


class DataRoute(webapp2.RequestHandler):
  def get(self):
    location = self.request.get('location')
    logging.info("Getting data at location " + location)
    result = None
    try:
      output = json.loads(blob.get_blob(get_container('texts'), location))
      result = {'result': 'success', 'output': output['content']}
    except HTTPError as e:
      if e.code == 404:
        result = {'result': 'failure', 'reason': 'not found'}
      else:
        raise e, None, sys.exc_info()[2]
    self.response.out.write(json.dumps(result))

  def put(self):
    location = self.request.get('location')
    logging.info("Putting data into location " + location)
    blob.put_blob(get_container('texts'), location,
        json.dumps({'result': 'success',
                    'location': self.request.get('location'),
                    'content': self.request.get('content')}))
    self.response.out.write(json.dumps({'result': 'success'}))

  def delete(self):
    location = self.request.get('location')
    logging.info("Deleting data at location " + location)

    result = None
    try:
      blob.delete_blob(get_container('texts'), location)
      result = {'result': 'success'}
    except Exception:
      # TODO get the name of the exception here
      result = {'result': 'failure', 'reason': 'exception was thrown'} 

    self.response.out.write(result)

class IndexPage(webapp2.RequestHandler):
  def get(self):
    self.response.out.write("Hello!")

logging.getLogger().setLevel(logging.INFO)
app = webapp2.WSGIApplication([('/task', TaskRoute),
                              ('/data', DataRoute),
                              ('/', IndexPage),
                              ], debug=True)
def main():
  from rocket import Rocket
  port = int(os.environ.get('PORT', 9000))
  logging.info("Listening on port " + str(port))
  Rocket((os.environ.get('ADDRESS', '0.0.0.0'), port), 'wsgi', {'wsgi_app': app}).start()

if __name__ == '__main__':
  main()