summaryrefslogtreecommitdiff
path: root/opendc/api/v1/simulations/endpoint.py
blob: ff66929039579af8971f383d720f29c5cbe40117 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from datetime import datetime

from opendc.models.authorization import Authorization
from opendc.models.datacenter import Datacenter
from opendc.models.path import Path
from opendc.models.section import Section
from opendc.models.simulation import Simulation
from opendc.models.user import User
from opendc.util import database, exceptions
from opendc.util.rest import Response

def POST(request):
    """Create a new simulation, and return that new simulation."""

    # Make sure required parameters are there

    try:
        request.check_required_parameters(
            body = {
                'simulation': {
                    'name': 'string'
                }
            }
        )

    except exceptions.ParameterError as e:
        return Response(400, e.message)

    # Instantiate a Simulation

    simulation_data = request.params_body['simulation']

    simulation_data['datetimeCreated'] = database.datetime_to_string(datetime.now())
    simulation_data['datetimeLastEdited'] = database.datetime_to_string(datetime.now())

    simulation = Simulation.from_JSON(simulation_data)

    # Insert this Simulation into the database

    simulation.insert()

    # Instantiate an Authorization and insert it into the database

    authorization = Authorization(
        user_id             = User.from_google_id(request.google_id).id, 
        simulation_id       = simulation.id,
        authorization_level = 'OWN'
    )

    authorization.insert()

    # Instantiate a Path and insert it into the database

    path = Path(
        simulation_id    = simulation.id,
        datetime_created = database.datetime_to_string(datetime.now())
    )

    path.insert()

    # Instantiate a Datacenter and insert it into the database

    datacenter = Datacenter(
        starred = 0,
        simulation_id = simulation.id
    )

    datacenter.insert()

    # Instantiate a Section and insert it into the database

    section = Section(
        path_id = path.id,
        datacenter_id = datacenter.id,
        start_tick = 0
    )

    section.insert()

    # Return this Simulation

    return Response(
        200,
        'Successfully created {}.'.format(simulation),
        simulation.to_JSON()
    )