sdn controllers: list, create, show
[osm/LW-UI.git] / sdnctrlhandler / views.py
1 #
2 # Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 from django.shortcuts import render, redirect
18 from django.contrib.auth.decorators import login_required
19 from django.http import JsonResponse
20 from lib.osm.osmclient.client import Client
21 import logging
22
23 logging.basicConfig(level=logging.DEBUG)
24 log = logging.getLogger('view.py')
25
26
27 @login_required
28 def list(request, project_id):
29 client = Client()
30 result = client.sdn_list()
31
32 result = {
33 'project_id': project_id,
34 'sdns': result
35 }
36 return __response_handler(request, result, 'sdn_list.html')
37
38
39 @login_required
40 def create(request, project_id):
41 result = {'project_id': project_id}
42 if request.method == 'GET':
43 return __response_handler(request, result, 'sdn_create.html')
44 else:
45 new_sdn_dict = request.POST.dict()
46 client = Client()
47 keys = ["name",
48 "type",
49 "version",
50 "dpid",
51 "ip",
52 "port",
53 "user",
54 "password"]
55 sdn_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_sdn_dict.items()))
56 sdn_data['port'] = int(sdn_data['port'])
57
58 result = client.sdn_create(sdn_data)
59
60 return __response_handler(request, result, 'projects:sdns:list', to_redirect=True, project_id=project_id)
61
62
63 @login_required
64 def delete(request, project_id, sdn_id=None):
65 try:
66 client = Client()
67 del_res = client.sdn_delete(sdn_id)
68 except Exception as e:
69 log.exception(e)
70 return __response_handler(request, {}, 'projects:sdns:list', to_redirect=True, project_id=project_id)
71
72
73 @login_required
74 def show(request, project_id, sdn_id=None):
75 client = Client()
76 datacenter = client.sdn_get(sdn_id)
77 return __response_handler(request, {
78 "sdn": datacenter
79 }, project_id=project_id)
80
81
82 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
83 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
84 if 'application/json' in raw_content_types:
85 return JsonResponse(data_res)
86 elif to_redirect:
87 return redirect(url, *args, **kwargs)
88 else:
89 return render(request, url, data_res)