web: hosts: Add HostController

master
Dustin 2015-12-31 22:56:42 -06:00
parent 83072c0db7
commit cd1835f4f6
2 changed files with 47 additions and 0 deletions

View File

@ -82,6 +82,7 @@ class Application(milla.Application):
self.dispatcher = r = routing.Router() self.dispatcher = r = routing.Router()
r.add_route('/', hosts.HostListController()) r.add_route('/', hosts.HostListController())
r.add_route('/{host_id}', hosts.HostController())
def make_request(self, environ): def make_request(self, environ):
request = super(Application, self).make_request(environ) request = super(Application, self).make_request(environ)

View File

@ -39,3 +39,49 @@ class HostListController(controllers.BaseController):
response.location = request.create_href('/{}'.format(host.id)) response.location = request.create_href('/{}'.format(host.id))
response.set_payload(None, host) response.set_payload(None, host)
return response return response
class HostController(controllers.BaseController):
def GET(self, request, host_id):
host = request.db.query(model.Host).get(host_id)
if not host:
raise milla.HTTPNotFound
response = request.ResponseClass()
response.set_payload(None, host)
return response
def PUT(self, request, host_id):
host = request.db.query(model.Host).get(host_id)
if not host:
raise milla.HTTPNotFound
if request.content_type == 'application/json':
data = request.json
else:
data = request.POST.copy()
for key, value in six.iteritems(data):
if hasattr(host, key):
try:
setattr(host, key, value.strip().lower())
except ValueError as e:
raise milla.HTTPBadRequest('{}'.format(e))
request.db.commit()
response = request.ResponseClass()
response.status_int = milla.HTTPNoContent.code
return response
def DELETE(self, request, host_id):
host = request.db.query(model.Host).get(host_id)
if not host:
raise milla.HTTPNotFound
request.db.delete(host)
request.db.commit()
response = request.ResponseClass()
response.status_int = milla.HTTPNoContent.code
return response