def create_pet_simple(self, auth_key: json, pet_id: str, name: str, animal_type: str, age: str) -> json: """Метод позволяет добавить информацию о новом питомце без фотографии""" data = MultipartEncoder(fields={ 'name': name, 'animal_type': animal_type, 'age': age, }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + 'api/pets', headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except json.decoder.JSONDecodeError: result = res.text print(result) return status, result
def add_new_pet_simple(self, auth_key: json, name: str, animal_type: str, age: str) -> json: """Метод отправляет (постит) на сервер данные о добавляемом питомце без фотографии и возвращает статус запроса на сервер и результат в формате JSON с данными добавленного питомца""" data = MultipartEncoder(fields={ 'name': name, 'animal_type': animal_type, 'age': age }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + 'api/create_pet_simple', headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except json.decoder.JSONDecodeError: result = res.text print(result) return status, result
def add_new_pet_without_photo(self, auth_key: json, name: str, animal_type: str, age: str) -> json: data = MultipartEncoder(fields={ 'name': name, 'animal_type': animal_type, 'age': age, }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + 'api/create_pet_simple', headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except json.decoder.JSONDecodeError: result = res.text print(result) return status, result
def save(self): payload = MultipartEncoder( fields={ 'metadata': json.dumps(self.meta), 'model': (os.path.basename(self.archive), open(self.archive, 'rb'), 'application/octet-stream') }) if self.links is not None: url = self.links['self']['href'] else: url = "{}/models".format(cfg.host) r = cfg.conn.post(url, data=payload, headers={'Content-Type': payload.content_type}) r.raise_for_status() doc = r.json() self.id = doc["properties"]["id"] self.links = doc["properties"]["links"] del doc["properties"]["links"] self.meta.update(doc['properties']) self.refresh(meta=self.meta) return self
def add_photo_of_pet(self, auth_key: json, pet_id: str, pet_photo: str) -> json: """This method allows to add photo of a pet.""" data = MultipartEncoder(fields={ 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg') }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + f'api/pets/set_photo/{pet_id}', headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except: result = res.text return status, result
def update_pet_photo(self, auth_key: json, pet_id: str, pet_photo: str) -> json: """Добавляет фото к питомцу, созданному быстро (без фото): Метод отправляет запрос на сервер о обновлении фото питомуа по указанному ID и возвращает статус запроса и result в формате JSON с обновлённыи данными питомца""" data = MultipartEncoder(fields={ 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg') }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + 'api/pets/set_photo/' + pet_id, headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except json.decoder.JSONDecodeError: result = res.text return status, result
def _upload_img(src): try: file = requests.get(src, verify=False).content split = str(src).split('/') name = split[len(split) - 1] lens = len(file) multipart_encoder = MultipartEncoder( fields={ 'id': 'WU_FILE_0', 'type': 'image/jpeg', 'name': 'name', 'lastModifiedDate': time.strftime("%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)", time.localtime()), 'size': str(lens), 'upfile': (name, file, 'application/octet-stream') }, boundary='----WebKitFormBoundary' + str(random.randint(1e28, 1e29 - 1))) img_headers['Content-Type'] = multipart_encoder.content_type print( requests.options(upload_url, verify=False).content.decode('utf-8')) up_part = requests.post(upload_url, data=multipart_encoder, headers=img_headers, verify=False).content.decode('utf-8') jsons = json.loads(up_part) print(jsons) return jsons except Exception as e: print(e) return None
def test_submit_comment_success_email(self, mock_post): mock_post.return_value = {'response': 'fake_response'} data = { 'comment_on': u'FAKE_DOC_NUM', 'general_comment': u'FAKE_COMMENT', 'first_name': u'FAKE_FIRST', 'last_name': u'FAKE_LAST', 'email': u'FAKE_EMAIL' } response = submit_comment(QueryDict(urlencode(data))) act_args, act_kwargs = mock_post.call_args self.assertEqual(act_args[0], 'FAKE_URL?api_key=FAKE_API_KEY&D=FAKE_DOC_NUM') exp_data_field = data exp_data_field['organization'] = u'NA' exp_data = MultipartEncoder(fields=exp_data_field) self.assertTrue(act_kwargs.get('data'), exp_data) self.assertEqual(act_kwargs.get('data').fields, exp_data.fields) self.assertTrue(act_kwargs.get('headers').has_key('Content-Type')) self.assertIn('multipart/form-data', act_kwargs.get('headers').get('Content-Type'))
def get_messages(channel_id, first_message_time, last_message_time): url = f'{WORKSPACE_URL}/api/conversations.history' multipart_data = MultipartEncoder( fields={ 'channel': channel_id, 'limit': '1000', 'token': TOKEN, 'oldest': f'{first_message_time[:10]}', 'latest': f'{int(last_message_time[:10]) + 1}', }) headers = { 'Content-Type': multipart_data.content_type, 'cookie': COOKIE, } get_msgs = requests.post(url, data=multipart_data, headers=headers, verify=False) messages = get_msgs.json()['messages'] return messages
def send_html_report(): logger.info("sending html task report to webex teams") job_id = get_job_id() job_url = get_url(job_id) msg = "Job Summary Report for {} job id {} ({})".format( router_name, job_id, job_url) m = MultipartEncoder({ 'roomId': room_id, 'text': msg, 'files': ('SummaryReport.html', open('TaskLog.html', 'rb'), 'application/html') }) r = requests.post('https://api.ciscospark.com/v1/messages', data=m, headers={ 'Authorization': 'Bearer {}'.format(token), 'Content-Type': m.content_type }) logger.info("Response from Webex Teams: {}".format(r.text))
async def test_validate_many_text(async_client): # Arrange fields = [] for name in JSON_RESPONSES.keys(): filename = TEST_FILE_DIR / name file = ('files', (filename.name, open(filename, 'rb'), 'text/plain')) fields.append(file) fields.append(('checkers', 'ags')) fields.append(('std_dictionary', 'v4_1')) fields.append(('fmt', 'text')) mp_encoder = MultipartEncoder(fields=fields) # Act async with async_client as ac: response = await ac.post( '/validate/', headers={'Content-Type': mp_encoder.content_type}, data=mp_encoder.to_string()) # Assert assert response.status_code == 200 assert 'text/plain' in response.headers['content-type'] for log in PLAIN_TEXT_RESPONSES.values(): assert log.strip() in response.text
async def get(self): phone = self.get_argument('phone') pic_code = self.get_argument('pic_code') if not re.match(r'^1[34578][0-9]{9}$', phone): return await self.finish({'status': 402}) elif await redis.get(pic_code.lower()): try: await objects.get(Users, phone=phone) except Users.DoesNotExist: randnum = random.randint(10000, 99999) await redis.set(phone, randnum, expire=120) fetch_body = { 'apiKey': settings['apikey'], 'phoneNum': phone, 'templateID': '10634', 'params': f'[{randnum}]' } body = MultipartEncoder( fields=fetch_body, boundary='wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T').to_string() send_response = await AsyncHTTPClient().fetch( "https://api.apishop.net/communication/sms/send", headers={ 'Content-Type': 'multipart/form-data; boundary=wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T' }, method='POST', body=body) if json.loads(send_response.body.decode())['desc'] == '请求成功': return await self.finish({'status': 200}) else: return await self.finish({'status': 502}) else: return await self.finish({'status': 403}) else: return await self.finish({'status': 401})
def formData(path): name = getName(path) return MultipartEncoder( fields={ 'txt_title': name * (50 // len(name)), 'sel_filetype': '3', # nota all value should be str 'txt_tag': '工具书籍', 'sel_primary': '15', 'sel_subclass': '15013', 'sel_score': '3', 'txt_desc': name * 20, 'txt_userfile': (os.path.basename(path), open(path, 'rb'), 'application/X-zip-compressed') } # 'txt_userfile': (os.path.basename(path) ,open(path, 'rb'),'text/plain') # boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1)) )
def in_order(return_dict, iter_val): for i in range(iter_val): img = open('f.jpg', 'rb') mp_encoder = MultipartEncoder( fields={ # plain file object, no filename or mime type produces a # Content-Disposition header with just the part name 'file': ('f.jpg', img, 'image/jpg'), 'text': 'Behold the glory of Christopher Daniel Fregly', 'timestamp': 'Wed, 16 Oct 2019 21:12:18 GMT', 'lat': '29.8233', 'lng': '-95.4142' }) start_time = timeit.default_timer() # r = requests.post(url = url, data = json.dumps(data), headers = headers) r = requests.post( url, data= mp_encoder, # The MultipartEncoder is posted as data, don't use files=...! # The MultipartEncoder provides the content-type header with the boundary: headers={'content-type': mp_encoder.content_type}) elapsed = timeit.default_timer() - start_time img.close() return_dict.append(elapsed)
def import_image(self, infile, sync=False): '''**Description** Import an image archive **Arguments** - infile: An image archive file - sync: Whether the import should be synchronous or asynchronous **Success Return Value** If synchronous, A JSON object representing the image that was imported. ''' try: m = MultipartEncoder(fields={ 'archive_file': (infile, open(infile, 'rb'), 'text/plain') }) if sync: url = self.url + "/api/scanning/v1/anchore/import/images" else: url = self.url + "/api/scanning/v1/import/images" headers = { 'Authorization': 'Bearer ' + self.token, 'Content-Type': m.content_type } res = requests.post(url, data=m, headers=headers, verify=self.ssl_verify) if not self._checkResponse(res): return [False, self.lasterr] return [True, res.json() if sync else res.content] except Exception as err: print(err)
def post_api_pets(self, auth_key, name, animal_type, age, pet_photo): data = MultipartEncoder( fields={ 'name': name, 'animal_type': animal_type, 'age': age, 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg') }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + 'api/pets', headers=headers, data=data) status = res.status_code result = '' try: result = res.json() except: result = res.text print(result) return status, result
def copy_shock_node(self, ctx, shock_id): token = ctx['token'] if token is None: raise ValueError('Authentication token required!') header = {'Authorization': 'Oauth {}'.format(token)} source_id = shock_id if not source_id: raise ValueError('Must provide shock ID') mpdata = MultipartEncoder(fields={'copy_data': source_id}) header['Content-Type'] = mpdata.content_type response = requests.post( # copy_attributes only works in 0.9.13+ self.shock_url + '/node?copy_indexes=1', headers=header, data=mpdata, allow_redirects=True) self.check_shock_response( response, ('Error copying Shock node {}: ' ).format(source_id)) shock_data = response.json()['data'] shock_id = shock_data['id'] del header['Content-Type'] r = requests.get(self.shock_url + '/node/' + source_id, headers=header, allow_redirects=True) errtxt = ('Error downloading attributes from shock ' + 'node {}: ').format(shock_id) self.check_shock_response(r, errtxt) attribs = r.json()['data']['attributes'] if attribs: files = {'attributes': ('attributes', json.dumps(attribs).encode('UTF-8'))} response = requests.put( self.shock_url + '/node/' + shock_id, headers=header, files=files, allow_redirects=True) self.check_shock_response( response, ('Error setting attributes on Shock node {}: ' ).format(shock_id)) return shock_id
def make_mulitpart_form(self, fields, aio=False): """Create a multipart form to be used across the Symphony API, that works for both requests and the asynchronous aiohttp. Requests basically uses requests-toolbelt, but it's a little bit more involved for aiohttp. The output of this is expected to be passed to either execute_rest_request or execute_rest_request_async depending whether aio was true""" if aio: # This appears to be the canonical way to use aiohttp to pass mulipart data into the API # in the same way that MultipartEncoder does for Requests. # aiohttp.FormData does appear to work because of the way the Symphony API demands a boundary # in the header. aiohttp.MultipartWriter.append_form doesn't appear to work because it # encodes as a application/x-www-form-urlencoded that Symphony doesn't appear to like for # attachments with aiohttp.MultipartWriter("form-data") as data: for k, v in fields.items(): if len(v) == 1: part = data.append(v) part.set_content_disposition("form-data", name=k) if len(v) == 3: filename, file_object, content_type = v part = data.append(file_object, {'Content-Type': content_type}) part.set_content_disposition('form-data', name=k, filename=filename) headers = { 'Content-Type': 'multipart/form-data; boundary=' + data.boundary } else: data = MultipartEncoder(fields=fields) headers = {'Content-Type': data.content_type} return {"data": data, "headers": headers}
def uploadImagetoStaticServer(cookies, dtsg, image): try: print("\033[0;32m[+]\033[0m Uploading image to static server") url = 'https://upload.facebook.com/ajax/react_composer/attachments/photo/upload?__a=1&fb_dtsg=' + dtsg data = MultipartEncoder( fields={ 'profile_id': cookies['c_user'], 'source': '8', 'waterfallxapp': 'comet', 'farr': ('filename', open(image, 'rb'), 'image/' + image[-3:]), 'upload_id': 'jsc_c_a0' }, boundary='---------------------------368542852711876012201108144481' ) headers['Content-Type'] = data.content_type r = req.post(url, data=data, headers=headers, cookies=cookies) locale = r.text.find('"photoID":"') photoID = r.text[locale + 11:locale + 27] print("\033[0;32m[+]\033[0m Image uploaded to the static server") return photoID except: print( "\033[1;31m[+]\033[0m Error when uploading image to static server") exit()
def post_localfile(at, roomId, filename, text='', toPersonId='', toPersonEmail=''): openfile = open(filename, 'rb') filename = ntpath.basename(filename) payload = {'roomId': roomId, 'files': (filename, openfile, 'image/jpg')} if text: payload['text'] = text if toPersonId: payload['toPersonId'] = toPersonId if toPersonEmail: payload['toPersonEmail'] = toPersonEmail m = MultipartEncoder(fields=payload) headers = {'Authorization': _fix_at(at), 'Content-Type': m.content_type} resp = requests.request("POST", url=_url('/messages'), data=m, headers=headers) file_dict = json.loads(resp.text) file_dict['statuscode'] = str(resp.status_code) return file_dict
def push_file(self, local_path, remote_path): data = { 'filename': self._create_path_from_root(remote_path), 'accountId': self.account_id } response = requests.get(self.host_url + '/corpus/exists', params=data) if response.status_code == 200 and "true" in str(response.content): raise RuntimeError("Cannot push file: %s already exists" % remote_path) with open(local_path, "rb") as f: data = f.read() if local_path.endswith(".txt"): format_path = 'text/bitext' elif local_path.endswith(".tmx"): format_path = 'application/x-tmx+xml' else: raise ValueError( 'Cannot push %s, only support format of the corpus (application/x-tmx+xml, ' 'text/bitext)' % local_path) mp_encoder = MultipartEncoder( [ ('accountId', self.account_id), ('format', format_path), ('importOptions', '{"cleanFormatting": true, "removeDuplicates":true}'), ('filename', self._create_path_from_root(remote_path)), ('corpus', data) ] ) response = requests.post(self.host_url + '/corpus/import', data=mp_encoder, headers={'Content-Type': mp_encoder.content_type}) if response.status_code != 200: raise ValueError( "Cannot import file '%s' in '%s'." % (local_path, remote_path)) return response.json()
def save(self): """Save this command and result via the API.""" # Force record this command as success to avoid Build reporting errors # on commands that are just for checking purposes and do not interferes # in the Build if self.record_as_success: log.warning('Recording command exit_code as success') self.exit_code = 0 data = { 'build': self.build_env.build.get('id'), 'command': self.get_command(), 'description': self.description, 'output': self.output, 'exit_code': self.exit_code, 'start_time': self.start_time, 'end_time': self.end_time, } if self.build_env.project.has_feature(Feature.API_LARGE_DATA): # Don't use slumber directly here. Slumber tries to enforce a string, # which will break our multipart encoding here. encoder = MultipartEncoder( {key: str(value) for key, value in data.items()}) resource = api_v2.command resp = resource._store['session'].post( resource._store['base_url'] + '/', data=encoder, headers={ 'Content-Type': encoder.content_type, }) log.debug('Post response via multipart form: %s', resp) else: resp = api_v2.command.post(data) log.debug('Post response via JSON encoded data: %s', resp)
def add_photo_for_pet(self, auth_key: json, pet_id: str, pet_photo: str) -> json: """Метод отправляет (постит) на сервер фото питомца и возвращает статус запроса на сервер и результат в формате JSON с данными добавленного питомца""" data = MultipartEncoder(fields={ 'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'images/jpeg') }) headers = { 'auth_key': auth_key['key'], 'Content-Type': data.content_type } res = requests.post(self.base_url + '/api/pets/set_photo/' + pet_id, headers=headers, data=data) status = res.status_code result = "" try: result = res.json() except json.decoder.JSONDecodeError: result = res.text print(result) return status, result
def request(self, method, url, params=None, json=None, data=None, streaming=False): """Make a request to rest API and return response as json.""" params = params or {} json = json or {} data = data or {} if self.api_entry_point.endswith('/') and url.startswith('/'): url = '{}{}'.format(self.api_entry_point, url[1:]) else: url = '{}{}'.format(self.api_entry_point, url) method = method.upper() if method not in ['GET', 'POST']: raise ValueError("method should be in ['GET', 'POST']") if method == 'POST' and streaming: # Create new data with encoder encoder = MultipartEncoder(fields=data) multi_data = MultipartEncoderMonitor(encoder, None) headers = self.session.headers.copy() headers['Content-Type'] = multi_data.content_type resp = self.session.request(method, url, params=params, json=json, data=multi_data, headers=headers) else: resp = self.session.request(method, url, params=params, json=json, data=data) if not resp.ok: raise requests.exceptions.HTTPError( 'Error while trying to do a {} at {}. Reason is {}\nResponse content: {}'.format(method, url, resp.reason, resp.text), response=resp.status_code, request=url) try: return resp.json() except Exception: return resp.content
person = '*****@*****.**' images = { 'ayb': config['IMAGES']['AYB'], 'developer': config['IMAGES']['Developer'], 'afx': config['IMAGES']['Afx'], 'automation': config['IMAGES']['Automation'], 'hephaestus': config['IMAGES']['Hephaestus'], 'turk': config['IMAGES']['Turk'], 'matters': config['IMAGES']['Matters'], 'lunch': config['IMAGES']['Lunch'], 'garfield': config['IMAGES']['Garfield'], 'towel': config['IMAGES']['Towel'] } m = MultipartEncoder({ 'roomId': room, 'text': ('only the clients are broken fyi... webex service is working fine at API layer. Everyone go ahead and switch to code.' ), }) r = requests.post('https://api.ciscospark.com/v1/messages', data=m, headers={ 'Authorization': 'Bearer {auth}'.format(auth=aAuth), 'Content-Type': m.content_type }) print(r.text)
if more == "n": break else: more = input("Please enter a y or n: ") for device in devices: text = device["addresses"] """curl --request POST \ --header "Authorization: Bearer ACCESS_TOKEN" \ --header "Content-Type: application/json" \ --data '{"roomId":"Y2lzY29zcGFyazovL3VzL1JPT00vMDNjMTc2YTAtY2M0ZC0xMWVhLTg5ZDEtNTE2YzQ2OTliZmI1","text":"addresses"}' \ https://webexapis.com/v1/messages""" m = MultipartEncoder({ 'roomId': 'Y2lzY29zcGFyazovL3VzL1JPT00vMDNjMTc2YTAtY2M0ZC0xMWVhLTg5ZDEtNTE2YzQ2OTliZmI1', 'text': "addresses", }) r = requests.post('https://webexapis.com/v1/messages', data=m, headers={ 'Authorization': 'Bearer ACCESS_TOKEN', 'Content-Type': m.content_type }) #token = "NDQzYTYwZTMtOTg0My00MTExLTgxNjAtYzA3YTNmZjA1ZTBjZGZiZTIzYzItMTE5_PF84_consumer" #URL = "https://webexapis.com/v1/messages" #roomId = "Y2lzY29zcGFyazovL3VzL1JPT00vMDNjMTc2YTAtY2M0ZC0xMWVhLTg5ZDEtNTE2YzQ2OTliZmI1" #response = addresses
pass pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=10) data = requests.get(sys.argv[3], auth=('admin', JENKINS_TOKEN)) for x in data.text.split('\n'): pdf.cell(200, 10, txt=x, ln=1, align='L') pdf.output("buildresults_" + sys.argv[5] + ".pdf") m = MultipartEncoder( { 'roomId': WEBEX_TEAMS_ROOM_ID, 'markdown': f'## A new CI/CD build in {sys.argv[1]} branch has just finished!\n' + \ f' --- \n' + \ f'* **BUILD:** {sys.argv[2]}\n' + \ f'* **LOGS:** Click [HERE]({sys.argv[3]}) or review the attached PDF.\n' + \ f'* **STATUS:** {sys.argv[4]}.', 'files': ("buildresults_" + sys.argv[5] + ".pdf", open("buildresults_" + sys.argv[5] + ".pdf", 'rb'), 'application/pdf') } ) message = requests.post('https://api.ciscospark.com/v1/messages', data=m, headers={ 'Authorization': f'Bearer {WEBEX_TEAMS_ACCESS_TOKEN}', 'Content-Type': m.content_type }) #Send final result code as message for Jenkins to catch in the build logs print(message)
def webwxuploadmedia(self, image_name): url = 'https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json' # 计数器 self.media_count = self.media_count + 1 # 文件名 file_name = image_name # MIME格式 # mime_type = application/pdf, image/jpeg, image/png, etc. mime_type = mimetypes.guess_type(image_name, strict=False)[0] # 微信识别的文档格式,微信服务器应该只支持两种类型的格式。pic和doc # pic格式,直接显示。doc格式则显示为文件。 media_type = 'pic' if mime_type.split('/')[0] == 'image' else 'doc' # 上一次修改日期 lastModifieDate = 'Thu Mar 17 2016 00:55:10 GMT+0800 (CST)' # 文件大小 file_size = os.path.getsize(file_name) # PassTicket pass_ticket = self.pass_ticket # clientMediaId client_media_id = str(int(time.time() * 1000)) + \ str(random.random())[:5].replace('.', '') # webwx_data_ticket webwx_data_ticket = '' for item in self.cookie: if item.name == 'webwx_data_ticket': webwx_data_ticket = item.value break if (webwx_data_ticket == ''): return "None F**k Cookie" uploadmediarequest = json.dumps( { "BaseRequest": self.BaseRequest, "ClientMediaId": client_media_id, "TotalLen": file_size, "StartPos": 0, "DataLen": file_size, "MediaType": 4 }, ensure_ascii=False).encode('utf8') multipart_encoder = MultipartEncoder( fields={ 'id': 'WU_FILE_' + str(self.media_count), 'name': file_name, 'type': mime_type, 'lastModifieDate': lastModifieDate, 'size': str(file_size), 'mediatype': media_type, 'uploadmediarequest': uploadmediarequest, 'webwx_data_ticket': webwx_data_ticket, 'pass_ticket': pass_ticket, 'filename': (file_name, open(file_name, 'rb'), mime_type.split('/')[1]) }, boundary='-----------------------------1575017231431605357584454111' ) headers = { 'Host': 'file2.wx.qq.com', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:42.0) Gecko/20100101 Firefox/42.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'https://wx2.qq.com/', 'Content-Type': multipart_encoder.content_type, 'Origin': 'https://wx2.qq.com', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache' } r = requests.post(url, data=multipart_encoder, headers=headers) response_json = r.json() if response_json['BaseResponse']['Ret'] == 0: return response_json return None
def setUp(self): self.parts = [('field', 'value'), ('other_field', 'other_value')] self.boundary = 'this-is-a-boundary' self.instance = MultipartEncoder(self.parts, boundary=self.boundary)
def test_handles_uncode_strings(self): s = b'this is a unicode string: \xc3\xa9 \xc3\xa1 \xc7\xab \xc3\xb3' m = MultipartEncoder([('field', s.decode('utf-8'))]) assert m.read() is not None