working on clientv2: vimhandler 62/6362/1
authorlombardofr <lombardo@everyup.it>
Tue, 26 Jun 2018 17:14:14 +0000 (19:14 +0200)
committerlombardofr <lombardo@everyup.it>
Thu, 19 Jul 2018 12:40:12 +0000 (14:40 +0200)
Change-Id: I0150e80551dd8437ac49ff32949c0ae1b28bed22
Signed-off-by: lombardofr <lombardo@everyup.it>
lib/osm/osmclient/clientv2.py
vimhandler/views.py

index bebeb26..0f30cbe 100644 (file)
@@ -381,7 +381,6 @@ class Client(object):
         return result
 
     def ns_create(self, token, ns_data):
-        token = self.get_token()
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
                    'Authorization': 'Bearer {}'.format(token['id'])}
@@ -543,6 +542,82 @@ class Client(object):
         result['data'] = r.text
         return result
 
+    def vim_list(self, token):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/yaml", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/vims".format(self._base_path)
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+
+        return result
+
+    def vim_delete(self, token, id):
+        result = {'error': True, 'data': ''}
+        headers = { "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/vims/{1}".format(self._base_path, id)
+        try:
+            r = requests.delete(_url, params=None, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        print r.status_code
+        if r.status_code == requests.codes.accepted:
+            result['error'] = False
+        else:
+            result['data'] = r.text
+        return result
+
+
+
+    def vim_get(self, token, id):
+
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/vims/{1}".format(self._base_path, id)
+
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
+    def vim_create(self, token, vim_data):
+
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/vims".format(self._base_path)
+
+        try:
+            r = requests.post(_url, json=vim_data, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        print r.status_code
+        if r.status_code == requests.codes.created:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
+
     @staticmethod
     def md5(f):
         hash_md5 = hashlib.md5()
index 28c264c..dc96dbe 100644 (file)
 
 from django.shortcuts import render, redirect
 from django.contrib.auth.decorators import login_required
-from django.http import JsonResponse
-from lib.osm.osmclient.client import Client
+from django.http import HttpResponse
+import json
+#from lib.osm.osmclient.client import Client
+from lib.osm.osmclient.clientv2 import Client
 import yaml
 import logging
 
@@ -28,11 +30,11 @@ log = logging.getLogger('view.py')
 @login_required
 def list(request, project_id):
     client = Client()
-    result = client.vim_list()
+    result = client.vim_list(request.session['token'])
     print result
     result = {
         "project_id": project_id,
-        "datacenters": result
+        "datacenters": result['data'] if result and result['error'] is False else []
     }
     return __response_handler(request, result, 'vim_list.html')
 
@@ -55,8 +57,8 @@ def create(request, project_id):
                 "vim_tenant_name",
                 "description"]
         vim_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_vim_dict.items()))
-        vim_data['config']={}
-        for k,v in new_vim_dict.items():
+        vim_data['config'] = {}
+        for k, v in new_vim_dict.items():
             if str(k).startswith('config_') and len(v) > 0:
                 config_key = k[7:]
                 vim_data['config'][config_key] = v
@@ -68,7 +70,7 @@ def create(request, project_id):
             except Exception as e:
                 # TODO return error on json.loads exception
                 print e
-        result = client.vim_create(vim_data)
+        result = client.vim_create(request.session['token'], vim_data)
         # TODO  'vim:show', to_redirect=True, vim_id=vim_id
         return __response_handler(request, result, 'projects:vims:list', to_redirect=True, project_id=project_id)
 
@@ -76,7 +78,7 @@ def create(request, project_id):
 def delete(request, project_id, vim_id=None):
     try:
         client = Client()
-        del_res = client.vim_delete(vim_id)
+        del_res = client.vim_delete(request.session['token'], vim_id)
     except Exception as e:
         log.exception(e)
     return __response_handler(request, {}, 'projects:vims:list', to_redirect=True, project_id=project_id)
@@ -84,18 +86,21 @@ def delete(request, project_id, vim_id=None):
 @login_required
 def show(request, project_id, vim_id=None):
     client = Client()
-    datacenter = client.vim_get(vim_id)
-    print datacenter
+    result = client.vim_get(request.session['token'], vim_id)
+    print result
+    if isinstance(result, dict) and 'error' in result and result['error']:
+        return render(request, 'error.html')
+
     return __response_handler(request, {
-        "datacenter": datacenter,
+        "datacenter": result['data'],
         "project_id": project_id
     }, 'vim_show.html')
 
 
 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
     raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
-    if 'application/json' in raw_content_types:
-        return JsonResponse(data_res)
+    if 'application/json' in raw_content_types or url is None:
+        return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
     elif to_redirect:
         return redirect(url, *args, **kwargs)
     else: