web: hosts: Implement host list controller
parent
dc9c5ef137
commit
70e283f1c6
|
@ -1,4 +1,5 @@
|
|||
from __future__ import unicode_literals
|
||||
from . import hosts
|
||||
from milla.dispatch import routing
|
||||
import functools
|
||||
import jinja2
|
||||
|
@ -73,6 +74,8 @@ class Application(milla.Application):
|
|||
def setup_routes(self):
|
||||
self.dispatcher = r = routing.Router()
|
||||
|
||||
r.add_route('/', hosts.HostListController())
|
||||
|
||||
def make_request(self, environ):
|
||||
request = super(Application, self).make_request(environ)
|
||||
default_format = VariedResponse.default_content_type
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
from __future__ import unicode_literals
|
||||
from . import controllers, model
|
||||
import logging
|
||||
import milla
|
||||
import six
|
||||
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HostListController(controllers.BaseController):
|
||||
|
||||
def GET(self, request):
|
||||
response = request.ResponseClass()
|
||||
response.set_payload(None, request.db.query(model.Host).all())
|
||||
return response
|
||||
|
||||
def POST(self, request):
|
||||
if request.content_type == 'application/json':
|
||||
data = request.json
|
||||
else:
|
||||
data = request.POST.copy()
|
||||
|
||||
if 'macaddr' not in data:
|
||||
raise milla.HTTPBadRequest('MAC address is required')
|
||||
host = model.Host()
|
||||
for key, value in six.iteritems(data):
|
||||
if value and hasattr(host, key):
|
||||
try:
|
||||
setattr(host, key, value.strip().lower())
|
||||
except ValueError as e:
|
||||
raise milla.HTTPBadRequest('{}'.format(e))
|
||||
request.db.add(host)
|
||||
request.db.commit()
|
||||
log.info('Successfully created host {}'.format(host.macaddr))
|
||||
|
||||
response = request.ResponseClass()
|
||||
response.status_int = milla.HTTPCreated.code
|
||||
response.location = request.create_href('/{}'.format(host.id))
|
||||
response.set_payload(None, host)
|
||||
return response
|
Loading…
Reference in New Issue