f952e7648d4de978431cbfa2a95421a5727357b2
[it/otf.git] / a1-policy-manager-vth / app / helpers / action_helper.py
1 import json\r
2 import ast\r
3 from app.helpers import response_helper as ResponseHelper\r
4 from flask import current_app\r
5 from app.errors.bad_request_exception import BadRequestException\r
6 import requests\r
7 \r
8 def execute_action(request, response_dict, config):\r
9     headers = ResponseHelper.create_headers();\r
10     request_data = request.json\r
11     action_request = request_data.get("action").lower()\r
12     method = request_data.get("method").upper()\r
13     creds = ResponseHelper.get_credentials(request_data, config)\r
14 \r
15     proxies = ResponseHelper.get_proxies(config)\r
16     action = "services/keepalive" if action_request == "keepalive" else action_request\r
17     url = ResponseHelper.create_url(config=config, uri_path="/"+action)\r
18 #    ret_url = request.args.get('retURL')\r
19 \r
20 \r
21     json_req = ast.literal_eval(request_data["action_data"]["jsonBody"])\r
22     query_params = ast.literal_eval(request_data["action_data"]["query"])\r
23     current_app.logger.info("Requesting Url: {}, params: {}, body: {}, auth: {}, proxies: {}".format(url, query_params, json_req, creds, proxies))\r
24     try:\r
25         if(method == "GET"):\r
26             res = requests.get(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)\r
27         elif(method == "POST"):\r
28             res = requests.post(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)\r
29         elif(method == "PUT"):\r
30             res = requests.put(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)\r
31         elif(method == "DELETE"):\r
32             res = requests.delete(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)\r
33         else: \r
34             raise BadRequestException(406, "Method Not Supported")\r
35         response = {\r
36                 "status_code":res.status_code,\r
37                 "result": res.json()\r
38                 }\r
39     except(json.decoder.JSONDecodeError):\r
40         response = {\r
41                 "status_code":res.status_code,\r
42                 "result": res.reason\r
43                 }\r
44     except requests.exceptions.RequestException:\r
45         response = {\r
46                 "status_code":504,\r
47                 "result": "Something Happned"\r
48                 }\r
49     finally:\r
50         response_dict['vthResponse']['resultData'] = response\r
51  #       if ret_url is not None:\r
52  #           ResponseHelper.sendCallback(ret_url,response_dict)\r
53  #           return '',200\r
54         return response_dict\r