def post_to_slack(self, emoji, msg): if self._slack_conf.get('webhook_url', None): doc = { 'channel': self._slack_conf['channel'], 'username': '******', 'text': f":{emoji}:{msg}", 'icon_emoji': ':robot_face:', } post(self._slack_conf['webhook_url'], json=doc)
def process_item(self, item, spider): img = item['images'][0]['path'] item.pop('images') item.pop('image_urls') with open(f'{STORE_PATH}/{img}', 'rb') as file: post( url=BACKEND_CREATE_NEWS_URL, data=dict(item), files={'image': file} ) return item
def do_mopidy_call(self, mopidyaction): data = {"jsonrpc": "2.0", "id": 1, "method": mopidyaction} headers = {'content-type': 'application/json'} url = 'http://' + mpdServerUrl + ':6680/mopidy/rpc' data1 = json.dumps(data) return requests.post(url, data=data1, headers=headers).json()["result"]
def test_ds(self): f_id=self.config.get_value(self.file_path,'DynamicId','f_id') l_id=self.config.get_value(self.file_path,'DynamicId','l_id') url = '%s:%s/recruit.students/school/manage/enableOrDisableSchool' % (self.env['ip'], self.env['port']) json = [{"id":l_id, "disable":0, "schoolId":f_id}] response = post(url, None, json=json, cookies=self.cookies, headers=self.headers) assert response.status_code == 200 and (loads(response.text))['code'] == 1
def get_bank_list(self): payu_data = json.dumps(self.get_bank_list_payu_data()) result = post(url=settings.PAYU_URL, data=payu_data, headers={ 'content-type': 'application/json', 'accept': 'application/json' }) return self.bank_list_response(result)
def pse_payu_payment(self): self.validate_pse_payment_data() request_data = self.get_payu_pse_data() payu_data = json.dumps(request_data) result = post(url=settings.PAYU_URL, data=payu_data, headers=self.headers) result = result.json() return self.pse_response(result), result, request_data
def post(url, data=None, json=None, data_pass=None, callback=None, **kwargs): resp = api.post(url, data=data, json=json, **kwargs) resp.data_pass = data_pass resp._callback = callback return resp
def do_param_mopidy_call(self, method, params=None): data = {"jsonrpc": "2.0", "id": 1, "method": method} if not params == None: data["params"] = params headers = {'content-type': 'application/json'} url = 'http://' + mpdServerUrl + ':6680/mopidy/rpc' data1 = json.dumps(data) res = requests.post(url, data=data1, headers=headers).json() return res
def audios(request: HttpRequest): if request.method != 'POST': return Http404() data = {'id': request.POST['id']} files = [('audio', request.FILES['audio'].file)] response = HttpResponse( post(f'{base_url}/audios', data=data, files=files).content) response['Content-Type'] = 'application/json' log(request, response) return response
def start(request: HttpRequest): if request.method != 'POST': return Http404() json_parsed = request.body.decode('utf-8') unaccented_json_parsed = unidecode.unidecode(json_parsed) headers = {'Content-Type': 'application/json'} response = HttpResponse( post(f'{base_url}/start', data=unaccented_json_parsed, headers=headers).content) response['Content-Type'] = 'application/json' log(request, response) return response
def post(self, task, event, client): data = { "name": task.short_qualified_name, "identity": task.identity, "instance": task.task._instance.value, "hostname": gethostname(), "role": "client" if client else "worker", "event": event, } from requests.api import post r = post(self._uri, json=data) r.raise_for_status()
def tes_addschool(self): data = [('schoolName', 'caichang888'), ('listSchoolType[0].id', 2), ('canRecruit', 1), ('remark', 'hehe')] response = post( 'http://192.168.1.25:8080/recruit.students/school/manage/addSchoolInfo', data=data, cookies=self.cookie) text = response.text response_text = loads(text)['message'] assert response_text == '学校创建成功'
def test_asi(self): url = '%s:%s/recruit.students/school/manage/addSchoolInfo' % (self.env['ip'], self.env['port']) data = { 'schoolName':'实验中学3', 'listSchoolType[0].id':'3', 'canRecruit':'1', 'remark':'chong' } response = post(url, data=data, cookies=self.cookies) self.config.create_section(self.file_path,'DynamicId') self.config.create_value(self.file_path,'DynamicId','f_id','%s' % loads(response.text)['data']['id'] ) self.config.create_value(self.file_path,'DynamicId','l_id','%s' % loads(response.text)['data']['laccount'] ) assert response.status_code == 200 and (loads(response.text))['code'] == 1
def ganhar_experiencia(nome_treinador, apelido_pokemon, experiencia): # /treinador/<nome>/<apelido>/exp result = api.post(site_treinador + '/treinador/' + nome_treinador + '/' + apelido_pokemon + '/exp', None, json={'experiencia': experiencia}) if result.status_code == 404: if result.content.decode('utf-8') == "Treinador não existe.": raise TreinadorNaoCadastradoException() elif result.content.decode('utf-8') == "Pokémon não existe.": raise PokemonNaoCadastradoException() return True
def messages(request: HttpRequest): if request.method != 'POST': return Http404() json_parsed = request.body.decode('utf-8') delete_logs_if_needed(json_parsed) headers = {'Content-Type': 'application/json'} unaccented_json_parsed = unidecode.unidecode(json_parsed) response = HttpResponse( post(f'{base_url}/messages', data=unaccented_json_parsed, headers=headers).content) response['Content-Type'] = 'application/json' log(request, response) return response
def test_addSchool(self): url = 'http://192.168.1.5:8080/recruit.students/school/manage/addSchoolInfo' data = { 'schoolName': '蔡包子5', 'listSchoolType[0].id': '2', 'canRecruit': '1', 'remark': '3333' } logger.info('url为:' + url) response = post(url, data, cookies=self.cookies) logger.info('我的状态码为%s:' % response.status_code) logger.info('返回内容为%s:' % loads(response.text)) assert response.status_code == 200 and loads( response.text)['code'] == 1
def post(self, task, event, client): data = { "name": task.short_qualified_name, "identity": task.identity, "instance": task.task._instance.value, "hostname": gethostname(), "role": "client" if client else "worker", "event": event, } if hasattr(task, "logstash"): data["log"] = task.logstash r = post(self._uri, json=data) r.raise_for_status()
def post_comment_on_line(owner, repo, commit_sha, line_n, filename, message): """Posts commit comment on specified commit and line""" res = post(GIT_COMMENT_URL.format(host=host_api, owner=owner, repo=repo, commit_sha=commit_sha), auth=auth, json={ 'body': message, 'path': filename, 'position': line_n, }) assert res.status_code == 201, f'Got non 201 status, ' \ f'error message: {res.content}'
def get_travis_api_token(): url_to_send = "https://api.travis-ci.org/auth/github" headers = { "User-Agent": "Travis/BU-Tinker/2.0.1", "Accept": "application/vnd.travis-ci.2+json", "Host": "api.travis-ci.org", "Content-Type": "application/json", "Content-Length": "37" } data = { "github_token": app.config['GITHUB_TOKEN'] } r = Requests_API.post(url_to_send, json=data, headers=headers) r_dict = ast.literal_eval(r.content) return r_dict['access_token']
def upfile(username, password, zip_name=None): "上传" print "正在登录115.com" import re from hashlib import md5 from requests import sessions, api HEADERS = { "user_agent": "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", } s = sessions.session(headers=HEADERS) resp = s.request("POST", "https://passport.115.com/?ac=login", data={ "login[account]": username, "login[passwd]": password, "login[time]": "true" }) resp = s.request("GET", "http://115.com") try: user_cookie = re.search("var USER_COOKIE = [\"']([^'\"]+)[\"'];", resp.text).group(1) user_rsa1 = re.search("Core.CONFIG.FUpRsa1 = [\"']([^\"']+)[\"'];", resp.text).group(1) user_rsa2 = re.search("Core.CONFIG.FUpRsa2 = [\"']([^\"']+)[\"'];", resp.text).group(1) except AttributeError: print "Error Account.." token_time = str(int(time.time()*1000)) file_size = os.path.getsize(zip_name) token = md5(user_rsa1 + user_rsa2 + str(file_size) + token_time + user_rsa2 + user_rsa1).hexdigest() print "正在上传: %s 文件大小: %s 请稍后..." % (zip_name, file_size) resp = api.post("http://vipup.u.115.com/upload", data={ "FileName": zip_name, "cid": "2156432", #U115 directory "cookie": user_cookie, "aid": "1", "token": token, "time": token_time, "Upload": "Submit Query", }, files={ "Filedata": (zip_name.decode("u8"), open(zip_name)), }, headers={ "user-agent": "Adobe Flash Player 11", "x-flash-version": "11,3,300,265", }) print "上传成功" print resp.json
def http_file_upload(file_path, registration_id): upload_url = get_setting(Config.HPZ_FILE_UPLOAD_BASE_URL) + '/' + registration_id verify_certificate = not get_setting(Config.HPZ_IGNORE_CERTIFICATE) response = None with open(file_path, 'rb') as f: stream = __create_stream(file_path, f) headers = {'Content-Type': stream.content_type, 'File-Name': os.path.basename(file_path)} try: response = api.post(upload_url, data=stream, headers=headers, verify=verify_certificate) log.info("File uploaded to %s with status code %d" % (upload_url, response.status_code)) except ConnectionError as e: raise RemoteCopyError(msg=str(e)) except TypeError as e: # Known Bug in Python 3.3.0. We need to swallow the exception here log.warning("Caught Known Exception: " + str(e)) return response.status_code if response else None
def creditcard(self): self.card_association = self.get_creditcard_association() self.last_four_digits = self.get_last_four_digits() payu_request = self.get_payu_data() payu_data = json.dumps(payu_request) # result = post(url=settings.PAYU_URL, data=payu_data, headers=self.headers) # result = result.json() # if settings.PAYU_TEST and self.valid_test_user(): if settings.PAYU_TEST: result = self.test_response() else: result = post(url=settings.PAYU_URL, data=payu_data, headers=self.headers) result = result.json() return self.response(result), result, payu_request
def consulta_protocolo(protocolo, cpf): url = 'http://protocolosfpc.2rm.eb.mil.br/consulta_processo.php' _protocolo = int(protocolo) _cpf = str(cpf) cpf_formatado = '{}.{}.{}-{}'.format(_cpf[:3], _cpf[3:6], _cpf[6:9], _cpf[9:]) print(cpf_formatado) payload = { 'cpf_cnpj': 0, 'txt_cpf_cnpj': cpf_formatado, 'txt_protocolo': f'00{_protocolo}' } req = api.post(url, data=payload) res = req.text bs = BeautifulSoup(res, 'html.parser') erro_ao_localizar = bs.select_one('#div_msg > strong') if erro_ao_localizar: print(erro_ao_localizar.text) return None print('passou') status = bs.select_one( '#wrap > div > div > center:nth-child(6) > h3 > span').text cpf_requerente = bs.select_one( '#wrap > div > div > div > table:nth-child(4) > tbody > tr:nth-child(2) > td:nth-child(2)' ).text data_protocolo = bs.select_one( '#wrap > div > div > div > table:nth-child(4) > tbody > tr:nth-child(1) > td:nth-child(4)' ).text requerente = bs.select_one( '#wrap > div > div > div > table:nth-child(4) > tbody > tr:nth-child(2) > td:nth-child(4)' ).text subsecao = bs.select_one( '#wrap > div > div > div > table:nth-child(4) > tbody > tr:nth-child(3) > td:nth-child(2)' ).text servico = bs.select_one( '#wrap > div > div > div > table:nth-child(4) > tbody > tr:nth-child(3) > td:nth-child(4)' ).text return { 'status': status, 'data_protocolo': data_protocolo, 'cpf': cpf_requerente, 'requerente': requerente, 'subsecao': subsecao, 'servico': servico }
def tes_setRecruitTime(self): url = 'http://192.168.1.5:8080/recruit.students/school/manage/setStudentRecruitTime' json = [{ "id": "4601", "recruitStartTime": "2021-01-04", "recruitEndTime": "2021-01-12", "isStudentRecruitTime": "1" }] logger.info('url为:' + url) response = post(url, json=json, cookies=self.cookies, headers=self.headers) logger.info('我的状态码为%s:' % response.status_code) logger.info('返回内容为%s:' % loads(response.text)) print(response.text) assert response.status_code == 200 and loads( response.text)['code'] == 1
def url_post(self, url, data=None, json=None, **kwargs): """url post method :param kwargs: :rtype: object:requests.Response """ try: Log.info( 'post url {url} data {data} '.format(url=url, data=data, cookies=self.cookies, proxies=self._proxies)) return post(url=url, data=data, json=json, **kwargs) except HTTPError: Log.error('{url} http error'.format(url=url)) except ConnectTimeout: Log.error('{url} connect timeout'.format(url=url)) except ConnectionError: Log.error('{url} connect fail'.format(url=url)) except RequestException: Log.error('{url} request error'.format(url=url))
def tes_setstudentrecruilttime(self): json = [{ "id": "5671", "recruitStartTime": "2021-04-01", "recruitEndTime": "2021-04-09", "isStudentRecruitTime": "1" }] response = post( 'http://192.168.1.25:8080/recruit.students/school/manage/setStudentRecruitTime', json=json, cookies=self.cookies) text = response.text response_text = loads(text)['code'] assert response_text == 1
def do_mopidy_search(self, artist): data = { "jsonrpc": "2.0", "id": 1, "params": { 'query': { 'artist': [artist] } }, "exact": "True", "method": "core.library.search" } headers = {'content-type': 'application/json'} url = 'http://' + mpdServerUrl + ':6680/mopidy/rpc' data1 = json.dumps(data) res = requests.post(url, data=data1, headers=headers).json() return res["result"]
def check_paid(invoiceid): xmlTemplate = """ <?xml version="1.0" encoding="utf-8"?> <request method="invoice.get"> <invoice_id>{}</invoice_id> </request> """.format(invoiceid) rp = api.post( apiurl, auth=('authtoken', ''), data=xmlTemplate ) tree = ElementTree.fromstring(rp.text) amountpaid = round(float(tree[0][18].text)) if amountpaid == 0: return True else: return False
def tes_addSchool(self): url = 'http://192.168.1.5:8080/recruit.students/school/manage/addSchoolInfo' data = { 'schoolName': '蔡包子4', 'listSchoolType[0].id': '2', 'canRecruit': '1', 'remark': '3333' } cookies = {'JSESSIONID': '4C7F9900296CCF401EA453523988978F'} logger.info('url为:' + url) response = post(url, data, cookies=cookies) logger.info('我的状态码为%s:' % response.status_code) logger.info('返回内容为%s:' % loads(response.text)) # print(response) # print(response.text) # print(response.status_code) print(response.text) assert response.status_code == 200 and loads( response.text)['code'] == 1
def _post(self, path, json): """ Utility to simplify requests to afm and handle (translate) exceptions :param path: :param json: :return: """ try: r = post( self.afm_url + path, json=json ) if 400 <= r.status_code < 500: raise FatalError('AFM responded with client error status: {0}'.format(r.status_code)) elif 500 <= r.status_code < 600: raise TemporaryError('AFM responded with server error status: {0}'.format(r.status_code)) return r except RequestException as e: raise TemporaryError(e)
def pairing(self): if self.config['device_id'] == '': try: result = post( '{}/dispatch/devices/'.format(self.config['host']), { 'code': self.config['pairing_code'], 'name': self.config['device_name'] }) if result.status_code != 201: self.trigger('pairing_failure') else: device = result.json() self.config['device_id'] = device['id'] self.config['device_name'] = device['name'] self.save_config() self.trigger('pairing_success') except (KeyError): self.trigger('pairing_failure') else: self.trigger('pairing_success')
def post_pr_review(owner, repo, commit_sha, pull_number, message, event='COMMENT'): """Posts review comment on specified pull request and change it status""" review = { 'commit_id': commit_sha, 'body': message, 'event': event, } res = post(GIT_PULL_REVIEW_URL.format(host=host_api, owner=owner, repo=repo, pull_number=pull_number), json=review, auth=auth) assert res.status_code == 200, f'Got non 201 status, ' \ f'error message: {res.content}'
def test_addSchool(self): url = 'http://192.168.1.5:8080/recruit.students/school/manage/addSchoolInfo' data = { 'schoolName': '蔡包子40', 'listSchoolType[0].id': '2', 'canRecruit': '1', 'remark': '3333' } logger.info('url为:' + url) response = post(url, data, cookies=self.cookies) #print(response.text) logger.info('我的状态码为%s:' % response.status_code) logger.info('返回内容为%s:' % loads(response.text)) logger.info(loads(response.text)['data']['id']) logger.info(type(loads(response.text)['data']['id'])) #return loads(response.text)['data']['id'] self.config.create_section(self.file_path, 'DynamicId') self.config.create_value(self.file_path, 'DynamicId', 'id', "%s" % loads(response.text)['data']['id']) assert response.status_code == 200 and loads( response.text)['code'] == 1
def test_setRecruitTime(self): url = 'http://192.168.1.5:8080/recruit.students/school/manage/setStudentRecruitTime' json = [{ "id": "4601", "recruitStartTime": "2021-01-04", "recruitEndTime": "2021-01-12", "isStudentRecruitTime": "1" }] cookies = {'JSESSIONID': '4C7F9900296CCF401EA453523988978F'} headers = {'Content-Type': 'application/json'} logger.info('url为:' + url) response = post(url, json=json, cookies=cookies, headers=headers) logger.info('我的状态码为%s:' % response.status_code) logger.info('返回内容为%s:' % loads(response.text)) # print(response) # print(response.text) # print(response.status_code) print(response.text) assert response.status_code == 200 and loads( response.text)['code'] == 1
def post(self, **kwargs): response = api.post(self.url, headers=self.headers, **kwargs) self.handle_errors(response.status_code) return response
def rerun_travis_build(self, build_id): url_to_send = self.travis_api_url + "/builds/" + build_id + "/restart" r = Requests_API.post(url_to_send, headers=construct_authorized_post_headers()) return r.content
noRepeatSecs = 10 # ignore repeated scans spaced less than this station = None while True: img = cv.QueryFrame(capture) cv.CvtColor(img, gray, cv.CV_RGB2GRAY) if display: cv.ShowImage('qr', gray) cv.WaitKey(1) zbar_img = zbar.Image(width, height, 'Y800', gray.tostring()) scanner.scan(zbar_img) now = time.time() for symbol in zbar_img: if lastSeen.get(symbol.data, 0) < now - noRepeatSecs: if station is None: # or it's a replacement station card? station = symbol.data print "this station is now", station playSound('station-received.wav') else: playSound('scanned-person.wav') print "found", symbol.data, symbol.location post("https://gametag.bigast.com/scans", timeout=2, data={'game': station, 'qr': symbol.data}) lastSeen[symbol.data] = now