web: hosts: Add HostController
parent
83072c0db7
commit
cd1835f4f6
|
@ -82,6 +82,7 @@ class Application(milla.Application):
|
|||
self.dispatcher = r = routing.Router()
|
||||
|
||||
r.add_route('/', hosts.HostListController())
|
||||
r.add_route('/{host_id}', hosts.HostController())
|
||||
|
||||
def make_request(self, environ):
|
||||
request = super(Application, self).make_request(environ)
|
||||
|
|
|
@ -39,3 +39,49 @@ class HostListController(controllers.BaseController):
|
|||
response.location = request.create_href('/{}'.format(host.id))
|
||||
response.set_payload(None, host)
|
||||
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
|
||||
|
|
Loading…
Reference in New Issue