automatic reload on lists; new django decorator for ajax request
[osm/LW-UI.git] / vimhandler / 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 sf_t3d.decorators import login_required
19 from django.http import HttpResponse
20 import json
21 from lib.osm.osmclient.clientv2 import Client
22 import authosm.utils as osmutils
23 import yaml
24 import logging
25
26 logging.basicConfig(level=logging.DEBUG)
27 log = logging.getLogger('vimhandler.py')
28
29
30 @login_required
31 def list(request):
32 user = osmutils.get_user(request)
33 project_id = user.project_id
34 result = {'type': 'ns', 'project_id': project_id}
35 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
36 if 'application/json' not in raw_content_types:
37 return __response_handler(request, result, 'vim_list.html')
38 client = Client()
39 result_client = client.vim_list(user.get_token())
40 result["datacenters"] = result_client['data'] if result_client and result_client['error'] is False else []
41 return __response_handler(request, result, 'vim_list.html')
42
43
44 @login_required
45 def create(request):
46 user = osmutils.get_user(request)
47 project_id = user.project_id
48 result = {'project_id': project_id}
49 if request.method == 'GET':
50 return __response_handler(request, result, 'vim_create.html')
51 else:
52 new_vim_dict = request.POST.dict()
53 client = Client()
54 keys = ["schema_version",
55 "schema_type",
56 "name",
57 "vim_url",
58 "vim_type",
59 "vim_user",
60 "vim_password",
61 "vim_tenant_name",
62 "description"]
63 vim_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_vim_dict.items()))
64 vim_data['config'] = {}
65 for k, v in new_vim_dict.items():
66 if str(k).startswith('config_') and len(v) > 0:
67 config_key = k[7:]
68 vim_data['config'][config_key] = v
69 if 'additional_conf' in new_vim_dict:
70 try:
71 additional_conf_dict = yaml.safe_load(new_vim_dict['additional_conf'])
72 for k,v in additional_conf_dict.items():
73 vim_data['config'][k] = v
74 except Exception as e:
75 # TODO return error on json.loads exception
76 print e
77 result = client.vim_create(user.get_token(), vim_data)
78 # TODO 'vim:show', to_redirect=True, vim_id=vim_id
79 return __response_handler(request, result, 'vims:list', to_redirect=True, )
80
81 @login_required
82 def delete(request, vim_id=None):
83 user = osmutils.get_user(request)
84 try:
85 client = Client()
86 del_res = client.vim_delete(user.get_token(), vim_id)
87 except Exception as e:
88 log.exception(e)
89 return __response_handler(request, del_res, 'vims:list', to_redirect=True, )
90
91 @login_required
92 def show(request, vim_id=None):
93 user = osmutils.get_user(request)
94 project_id = user.project_id
95 client = Client()
96 result = client.vim_get(user.get_token(), vim_id)
97 print result
98 if isinstance(result, dict) and 'error' in result and result['error']:
99 return render(request, 'error.html')
100
101 return __response_handler(request, {
102 "datacenter": result['data'],
103 "project_id": project_id
104 }, 'vim_show.html')
105
106
107 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
108 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
109 if 'application/json' in raw_content_types or url is None:
110 return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
111 elif to_redirect:
112 return redirect(url, *args, **kwargs)
113 else:
114 return render(request, url, data_res)