1
1
import os
2
- import httplib2
2
+ import requests
3
3
from urllib import urlencode
4
4
from datetime import datetime
5
5
@@ -30,37 +30,35 @@ def __init__(self, http_response, content):
30
30
self .content = content
31
31
32
32
class HTTPBackend (object ):
33
- """
34
- Abstracts out an HTTP backend, but defaults to httplib2. Required arguments
35
- are `base_url` and `api_key`.
33
+ """ Abstracts out an HTTP backend. Required argument are `base_url` and
34
+ `api_key`. """
35
+ def __init__ (self ,
36
+ base_url ,
37
+ api_key ,
38
+ resource_name = None ,
39
+ timeout = None ,
40
+ test = False ,
41
+ version = None ):
36
42
37
- .. note::
38
- While `as_xml` is provided as a keyword argument, XML or input or output
39
- is not supported.
40
- """
41
- def __init__ (self ,base_url ,api_key ,as_xml = False ,resource_name = None ,timeout = None ,test = False ,version = None ):
42
43
self .base_url = base_url
44
+
43
45
if resource_name :
44
46
self .base_url = self .base_url + resource_name
45
47
46
- self .http = httplib2 .Http (timeout = timeout )
47
- self .as_xml = as_xml
48
+ self .http = requests .Session ()
49
+
50
+ self .as_xml = False
48
51
self .api_key = api_key
49
52
self .test = test
50
53
self .version = version
51
54
52
- def content_length (self ,body ):
53
- """
54
- Returns the content length as an int for the given `body` data. Used by
55
- PUT and POST requests to set the Content-Length header.
56
- """
57
- return str (len (body ))if body else "0"
55
+ # sets request headers for the entire session
56
+ self .http .headers .update (self .headers )
58
57
59
58
@property
60
59
def headers (self ):
61
- """ Returns default headers, by setting the Content-Type and Accepts
62
- headers.
63
- """
60
+ """ Returns default headers, by setting the Content-Type, Accepts,
61
+ User-Agent and API Key headers."""
64
62
content_type = 'xml' if self .as_xml else 'json'
65
63
66
64
headers = {
@@ -85,35 +83,14 @@ def encode(self, data):
85
83
else :
86
84
raise NotImplementedError ('Encoding as XML is not supported.' )
87
85
88
- def decode (self ,raw_body ):
89
- """
90
- Returns the JSON-encoded `raw_body` and decodes it to a `dict` (using
91
- `json.loads`).
92
-
93
- .. note::
94
- Decoding as XML is not supported.
95
- """
96
- if not self .as_xml :
97
- # only parse json when it exists, else just return None
98
- if not raw_body or raw_body == ' ' :
99
- return None
100
- else :
101
- return json .loads (raw_body )
102
- else :
103
- raise NotImplementedError ('Decoding as XML is not supported.' )
104
-
105
86
def delete (self ,url ,params = None ):
106
87
"""
107
88
Executes an HTTP DELETE request for the given URL
108
89
109
- params should be aurllib.urlencoded string
90
+ params should be adictionary
110
91
"""
111
- if params :
112
- url = '?' .join ([url ,params ])
113
-
114
- response ,content = self .http .request (url ,method = "DELETE" ,
115
- headers = self .headers )
116
- return self .process (response ,content )
92
+ response = self .http .delete (url ,params = params )
93
+ return self .process (response )
117
94
118
95
def get (self ,url ,data = None ):
119
96
"""
@@ -125,66 +102,58 @@ def get(self, url, data=None):
125
102
params = urlencode (data )
126
103
url = '?' .join ([url ,params ])
127
104
128
- response ,content = self .http .request (url ,method = "GET" ,
129
- headers = self .headers )
130
- return self .process (response ,content )
105
+ response = self .http .get (url ,headers = self .headers ,params = data )
106
+ return self .process (response )
131
107
132
108
def post (self ,url ,body = None ):
133
109
"""
134
110
Executes an HTTP POST request for the given URL
135
111
"""
136
- headers = self .headers
137
- headers ['Content-Length' ]= self .content_length (body )
138
- response ,content = self .http .request (url ,method = "POST" ,
139
- body = body ,
140
- headers = self .headers )
112
+ response = self .http .post (url ,data = body ,headers = self .headers )
141
113
142
- return self .process (response , content )
114
+ return self .process (response )
143
115
144
116
def put (self ,url ,data = None ,body = None ):
145
117
"""
146
118
Executes an HTTP PUT request for the given URL
147
119
"""
148
- headers = self .headers
149
- headers ['Content-Length' ]= self .content_length (body )
120
+ response = self .http .put (url ,params = data ,data = body ,headers = self .headers )
150
121
151
- if data :
152
- params = urlencode (data )
153
- url = '?' .join ([url ,params ])
122
+ return self .process (response )
154
123
155
- response ,content = self .http .request (url ,method = "PUT" ,
156
- body = body ,
157
- headers = headers )
158
-
159
- return self .process (response ,content )
160
-
161
- def process (self ,http_response ,content ):
162
- """
163
- Returns HTTP backend agnostic Response data
164
- """
124
+ def process (self ,response ):
125
+ """ Returns HTTP backend agnostic Response data. """
165
126
166
127
try :
167
- code = http_response .status
168
- body = self .decode (content )
169
- response = Response (code ,body ,content ,http_response )
170
-
171
- return response
128
+ code = response .status_code
129
+
130
+ # 204 - No Content
131
+ if code == 204 :
132
+ body = None
133
+ # add an error message to 402 errors
134
+ elif code == 402 :
135
+ body = {
136
+ "message" :"Payment Required" ,
137
+ "status" :"error"
138
+ }
139
+ else :
140
+ body = response .json ()
172
141
142
+ return Response (code ,body ,response .content ,response )
173
143
except ValueError :
174
- raise ZencoderResponseError (http_response ,content )
144
+ raise ZencoderResponseError (response ,content )
175
145
176
146
class Zencoder (object ):
177
147
""" This is the entry point to the Zencoder API """
178
148
def __init__ (self ,api_key = None ,api_version = None ,as_xml = False ,timeout = None ,test = False ):
179
149
"""
180
- Initializes Zencoder. You must have a validAPI_KEY .
150
+ Initializes Zencoder. You must have a valid`api_key` .
181
151
182
152
You can pass in the api_key as an argument, or set
183
153
`ZENCODER_API_KEY` as an environment variable, and it will use
184
- that, if api_key is unspecified.
154
+ that, if` api_key` is unspecified.
185
155
186
156
Set api_version='edge' to get the Zencoder development API. (defaults to 'v2')
187
- Set as_xml=True to get back xml data instead of the default json.
188
157
"""
189
158
if not api_version :
190
159
api_version = 'v2'