import json

import tornado.ioloop
import tornado.httpserver
import tornado.web

from backend.optimizer.utils import get_data
from backend.optimizer.optimize import optimize_portfolio

from tornado.options import define, options, parse_command_line

# Add command line flags
define("port", default=8000, help="run on the given port", type=int)
define("debug", default=False, help="run in debug mode")


class MainHandler(tornado.web.RequestHandler):
    """Handles post requests by responding with a JSON file."""
    @tornado.web.asynchronous
    def get(self):
        """Respond to GET requests for debugging purposes."""
        self.write("Success!")
        self.finish()

    @tornado.web.asynchronous
    def post(self):
        """Respond to POST requests with optimal allocations."""
        data = json.loads(self.request.body.decode('utf-8'))
        stock_params = dict(data)
        allocs = optimize_allocations(stock_params)
        self.write(allocs)
        self.finish()


def make_app():
    tornado.options.parse_command_line()
    return tornado.web.Application([
        (r"/", MainHandler)
    ])


def optimize_allocations(stock_params):
    """Call methods to get stock data and find optimal allocations."""
    prices = get_data(stock_params)
    allocs = optimize_portfolio(prices)
    return allocs


def main():
    """Runs application on httpserver with handler for '/'."""
    app = make_app()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()

@@ -503,24 +503,477 @@
 ON file.%22%22%22%0A
+    def set_default_headers(self):%0A        self.set_header('Access-Control-Allow-Origin', '*')%0A        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')%0A        self.set_header('Access-Control-Max-Age', 1000)%0A        #self.set_header('Access-Control-Allow-Headers', 'origin, x-csrftoken, content-type, accept')%0A        self.set_header('Access-Control-Allow-Headers', '*')%0A        self.set_header('Content-type', 'application/json')%0A%0A
     @tornado
@@ -982,32 +982,32 @@
 eb.asynchronous%0A
-
     def get(self
@@ -1328,16 +1328,26 @@
 s = dict
+_from_data
 (data)%0A 
@@ -1766,16 +1766,16 @@
 prices)%0A
-
     retu
@@ -1786,16 +1786,420 @@
 llocs%0A%0A%0A
+def dict_from_data(data):%0A    %22%22%22Maps data from POST request to a Python dictionary%22%22%22%0A    output = %7B%7D%0A    data = dict(data)%0A    mapping = %7B%22startDate%22: %22start_date%22,%0A               %22endDate%22: %22end_date%22,%0A               %22initialInvestment%22: %22principle%22%7D%0A    for k, v in data.items():%0A        if k in mapping:%0A            output%5Bmapping%5Bk%5D%5D = v%0A        else:%0A            output%5Bk%5D = v%0A    return output%0A%0A%0A
 def main

Enable CORS and add parsing.