def upload(url, path, fields=None, headers=None, use_json=False): if modutil.exists('pycurl'): import pycurl url = stringutil.u2s(url) path = stringutil.u2s(path) if not os.path.exists(path): raise Exception('File "%s" not found.' % path) buffer = StringIO.StringIO() c = pycurl.Curl() c.setopt(c.POST, 1) c.setopt(c.HEADER, 1) c.setopt(c.WRITEFUNCTION, buffer.write) c.setopt(c.URL, url) field_list = [('file', (c.FORM_FILE, path))] if fields is not None: for k,v in fields.items(): if use_json: v = json2.dumps(v) field_list.append((k, v)) c.setopt(c.HTTPPOST, field_list) if headers is not None: header_list = [] for k, v in headers.items(): header = '%s: %s' % (k, v) header = str(header) # header may be unicode, which is un-acceptable for curl header_list.append(header) c.setopt(c.HTTPHEADER, header_list) c.perform() code = c.getinfo(pycurl.HTTP_CODE) c.close() if code != 200: raise CodedError('UPLOAD_FAILED', 'Failed to upload file %s.' % path) resp = buffer.getvalue() if use_json: json = resp.splitlines()[-1] json = unicode(json, 'utf-8') resp = json2.loads(json) return resp else: raise ModNotFoundError('pycurl')
def _process_resp(resp, resp_headers, use_json): ''' >>> headers = CiDict() no mime type, should return raw response >>> _process_resp('abc', {}, False) 'abc' charset not found, should use raw response >>> header = Dict(value='application/json', params=Dict()) >>> headers['Content-Type'] = header >>> _process_resp('abc', headers, False) 'abc' mime type is json, but use_json is False, should not decode by json >>> header = Dict(value='application/json', params=Dict(charset='utf-8')) >>> headers['Content-Type'] = header >>> _process_resp('abc', headers, False) u'abc' mime type is json, and use_json is True, should decode by json >>> header = Dict(value='application/json', params=Dict(charset='utf-8')) >>> headers['Content-Type'] = header >>> _process_resp('"abc"', headers, True) u'abc' ''' content_type_header = resp_headers.get('content-type') if content_type_header is not None: mime, charset = _parse_content_type_header(content_type_header) if mime == 'text/html': charset = _parse_html_charset(resp) or charset if charset is not None: resp = unicode(resp, charset, 'ignore') if use_json and mime == 'application/json': resp = json2.loads(resp) return resp
def upload_video(self, file, folder_id, title): r = self.createVideo(folderId=folder_id, title=title) rslt = httputil.upload(r.uploadUrl, file) if 'error' in rslt: raise CodedError(rslt.error, rslt.message) return json2.loads(r.media)
def handle(self, d): Context.curctx().header('Content-Type', 'application/json; charset=utf-8') for k in d: d[k] = json2.loads(d[k]) return super(json_handler, self).handle(d)