WIM handler
[osm/LW-UI.git] / wimhandler / views.py
1 # Copyright 2018 EveryUP Srl
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from django.shortcuts import render, redirect
16 from sf_t3d.decorators import login_required
17 from django.http import HttpResponse
18 import json
19 from lib.osm.osmclient.clientv2 import Client
20 import authosm.utils as osmutils
21 import yaml
22 import logging
23
24 logging.basicConfig(level=logging.DEBUG)
25 log = logging.getLogger('wimhandler.py')
26
27
28 @login_required
29 def list(request):
30 user = osmutils.get_user(request)
31 project_id = user.project_id
32 result = {'type': 'ns', 'project_id': project_id}
33 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
34 if 'application/json' not in raw_content_types:
35 return __response_handler(request, result, 'wim_list.html')
36 client = Client()
37 result_client = client.wim_list(user.get_token())
38 result["datacenters"] = result_client['data'] if result_client and result_client['error'] is False else []
39 return __response_handler(request, result, 'wim_list.html')
40
41 @login_required
42 def create(request):
43 user = osmutils.get_user(request)
44 project_id = user.project_id
45 result = {'project_id': project_id}
46 if request.method == 'GET':
47 return __response_handler(request, result, 'wim_create.html')
48 else:
49 new_wim_dict = request.POST.dict()
50 client = Client()
51 keys = ["schema_version",
52 "schema_type",
53 "name",
54 "description",
55 "wim_url",
56 "wim_type",
57 "user",
58 "password",
59 "wim",
60 "description"]
61 wim_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_wim_dict.items()))
62 wim_data['config'] = {}
63 for k, v in new_wim_dict.items():
64 if str(k).startswith('config_') and len(v) > 0:
65 config_key = k[7:]
66 wim_data['config'][config_key] = v
67 if 'additional_conf' in new_wim_dict:
68 try:
69 additional_conf_dict = yaml.safe_load(new_wim_dict['additional_conf'])
70 for k,v in additional_conf_dict.items():
71 wim_data['config'][k] = v
72 except Exception as e:
73 # TODO return error on json.loads exception
74 print e
75 result = client.wim_create(user.get_token(), wim_data)
76 return __response_handler(request, result, 'wims:list', to_redirect=True, )
77
78 @login_required
79 def delete(request, wim_id=None):
80 user = osmutils.get_user(request)
81 try:
82 client = Client()
83 del_res = client.wim_delete(user.get_token(), wim_id)
84 except Exception as e:
85 log.exception(e)
86 return __response_handler(request, del_res, 'wims:list', to_redirect=True, )
87
88 @login_required
89 def show(request, wim_id=None):
90 user = osmutils.get_user(request)
91 project_id = user.project_id
92 client = Client()
93 result = client.wim_get(user.get_token(), wim_id)
94 if isinstance(result, dict) and 'error' in result and result['error']:
95 return render(request, 'error.html')
96
97 return __response_handler(request, {
98 "wim": result['data'],
99 "project_id": project_id
100 }, 'wim_show.html')
101
102 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
103 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
104 if 'application/json' in raw_content_types or url is None:
105 return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
106 elif to_redirect:
107 return redirect(url, *args, **kwargs)
108 else:
109 return render(request, url, data_res)