|
2 | 2 |
|
3 | 3 | import ConfigParser |
4 | 4 | import cookielib |
| 5 | +import mimetypes |
| 6 | +import random |
5 | 7 |
|
6 | 8 | # json module is not supported in versions of Python < 2.6 so try to load the |
7 | 9 | # simplejson module instead. Note that as of simplejson v2.1.1, Python 2.4 |
|
24 | 26 |
|
25 | 27 | import urlparse |
26 | 28 |
|
27 | | -__version__ = '0.2.0' |
| 29 | +__version__ = '0.2.1' |
28 | 30 |
|
29 | 31 | REQUEST_TOKEN_URL = 'https://sso.openx.com/api/index/initiate' |
30 | 32 | ACCESS_TOKEN_URL = 'https://sso.openx.com/api/index/token' |
@@ -296,6 +298,40 @@ def delete(self, url): |
296 | 298 | return json.loads('[]') |
297 | 299 | return json.loads(res.read()) |
298 | 300 |
|
| 301 | + def upload_creative(self, account_id, file_path): |
| 302 | + """""" |
| 303 | + # Thanks to nosklo for his answer on SO: |
| 304 | + # http://stackoverflow.com/a/681182 |
| 305 | + boundary = '-----------------------------' + str(int(random.random()*1e10)) |
| 306 | + parts = [] |
| 307 | + |
| 308 | + # Set account ID part. |
| 309 | + parts.append('--' + boundary) |
| 310 | + parts.append('Content-Disposition: form-data; name="account_id"') |
| 311 | + parts.append('') |
| 312 | + parts.append(str(account_id)) |
| 313 | + |
| 314 | + # Set creative contents part. |
| 315 | + parts.append('--' + boundary) |
| 316 | + parts.append('Content-Disposition: form-data; name="userfile"; filename="%s"' % file_path) |
| 317 | + parts.append('Content-Type: %s' % mimetypes.guess_type(file_path)[0] or 'application/octet-stream') |
| 318 | + parts.append('') |
| 319 | + # TODO: catch errors with opening file. |
| 320 | + parts.append(open(file_path, 'r').read()) |
| 321 | + |
| 322 | + parts.append('--' + boundary + '--') |
| 323 | + parts.append('') |
| 324 | + |
| 325 | + body = '\r\n'.join(parts) |
| 326 | + |
| 327 | + # TODO: refactor Client.request. |
| 328 | + # TODO: Catch errors in attempt to upload. |
| 329 | + headers = {'content-type': 'multipart/form-data; boundary=' + boundary} |
| 330 | + url = self._resolve_url('/a/creative/uploadcreative') |
| 331 | + req = urllib2.Request(url, headers=headers, data=body) |
| 332 | + res = urllib2.urlopen(req) |
| 333 | + |
| 334 | + return json.loads(res.read()) |
299 | 335 |
|
300 | 336 | def client_from_file(file_path='.ox3rc', env=None): |
301 | 337 | """Return an instance of ox3apiclient.Client with data from file_path. |
|
0 commit comments