Skip to content

Commit

Permalink
Cleanup do_request and support empty response.
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelkuty committed Jul 8, 2016
1 parent 3f2a38f commit d79fbdc
Showing 1 changed file with 21 additions and 27 deletions.
48 changes: 21 additions & 27 deletions horizon_contrib/api/base.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@

import json
import logging

import requests

from horizon import messages
from requests import exceptions
from django.conf import settings
from horizon import messages
from .response import ListResponse, DictResponse

from .response import DictResponse, ListResponse

LOG = logging.getLogger("client.base")

Expand All @@ -33,35 +34,28 @@ def do_request(self, path, method="GET", params={}, headers={},
if not method == 'GET' and path[-1] != '/':
path = path + '/'

if method == "GET":
response = requests.get(path, headers=headers, **kw)
elif method == "POST":
headers["Content-Type"] = "application/json"
response = requests.post(
path,
data=json.dumps(params),
headers=headers,
**kw)
elif method == "PUT":
headers["Content-Type"] = "application/json"
response = requests.put(
path,
data=json.dumps(params),
headers=headers,
**kw)
elif method == "DELETE":
response = requests.delete(
path,
data=json.dumps(params),
headers=headers,
**kw)
return response
# for legacy clients which expect this
if method in ("POST", "PUT"):
headers.update({"Content-Type": "application/json"})

return requests.request(url=path,
method=method,
data=json.dumps(params) if params else None,
headers=headers,
**kw)

def process_response(self, response, request):
'''process response and handle statues and exceptions'''

if response.status_code <= 204:
result = response.json()

try:
result = response.json()
except ValueError:
# handle JSONDecodeError
# handle empty response
result = {}

if "error" in result:
msg = result.get("error")
# populate exception
Expand Down

0 comments on commit d79fbdc

Please sign in to comment.