def post_signal(self, name): ir = self.config['IR'][name] message = json.dumps(ir) params = { 'clientkey': self.device['clientkey'], 'deviceid': self.device['deviceid'], 'message': message } web.post(self.IRKIT_API_ENDPOINT, data=params)
def create_time_entry(api_key, project, timeInMinutes): """Creates the given amount on the given project """ url = 'https://www.toggl.com/api/v8/time_entries' base64string = base64.encodestring('%s:%s' % (api_key, 'api_token')).replace('\n', '') headers = {'Authorization' : 'Basic ' + base64string, 'Content-Type': 'application/json' } timeInSec = int(timeInMinutes)*60 todayString = time.strftime("%Y-%m-%dT%H:%M:%S+02:00") log.debug('Logging ' + timeInMinutes + 'min for ' + todayString) payload = {'time_entry': {'description':'I was working dude!', 'created_with':'Alfred Toggl Workflow', 'start':todayString, 'duration': '{0}'.format(timeInSec), 'pid': '{0}'.format(project) }} #log.debug(payload) #log.debug(headers) r = web.post(url, data = json.dumps(payload), headers = headers) #log.debug(r.status_code) #log.debug(r.headers) #log.debug(r) # throw an error if request failed # Workflow will catch this and show it to the user r.raise_for_status() # Parse the JSON returned by toggl and return the projects result = r.json() return result
def newnb(url, path, copy=None): """Create new untitled notebook at 'path' Server base URL is 'url' Returns name of the new notebook file. """ # See IPython/html/services/notebooks/handlers.py for API details. # Compare directory contents before and after new notebook creation. names = [nb['name'] for nb in get_nblist(url, path) if nb['type'] == 'notebook'] arg = path if isinstance(arg, unicode): arg = arg.encode('utf-8') post_url = urljoin(url, 'api/notebooks', quote(arg)).strip('/') if copy is not None: data = json.dumps({'copy_from': copy}) else: data = '' try: resp = web.post(post_url, data=data) except URLError: raise URLError('Unable to reach %s. Try the "nbserver" keyword.' % url) resp.raise_for_status() new_contents = get_nblist(url, path) new_names = [nb['name'] for nb in new_contents if nb['type'] == 'notebook'] try: newnbname = list(set(new_names) - set(names))[0] except IndexError: raise RuntimeError('Notebook creation at %s appears to have failed.' % post_url) return newnbname
def logout(): data = { 'action': 'logout' } try: res = post(LOGIN_URL, data=data, timeout=1) notify(title=str(res.status_code), text=res.text) except URLError as e: notify(title=str(e.errno), text=str(e.reason))
def html_get(kw): r = web.post('http://soft.macx.cn/index.htm', data=dict(keyword=kw)) r.raise_for_status() reg = re.compile('<ul class="results ">.*?</ul>', flags=re.DOTALL + re.MULTILINE) match = reg.search(r.text) if match: return match.group(0) return None
def test_post_form(self): """POST Form data""" url = self.httpbin.url + '/post' r = web.post(url, data=self.data) self.assert_(r.status_code == 200) r.raise_for_status() form = r.json()['form'] for key in self.data: self.assert_(form[key] == self.data[key])
def main(wf): srvId = sys.argv[1] userId = os.getenv('userId') baseUrl = os.getenv('baseUrl') msgContent = wf.stored_data('wechat_send_content') url = baseUrl + 'send-message' data = {'userId': userId, 'content': msgContent, 'srvId': srvId} r = web.post(url=url, data=data) r.raise_for_status() wf.send_feedback()
def search(query): # search the ganks from gank.io url = 'http://gankio.herokuapp.com/search' # url = 'http://ganhuo.herokuapp.com/search' params = dict(keyword=query) r = web.post(url, params) # throw an error if request failed, Workflow will catch this and show it to the user r.raise_for_status() return r.json()
def fetch_tasks(): user = get_user() data = ''' <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <GetTasksAllocatedToEmployee xmlns="http://www.timelog.com/api/tlp/v1_6"> <initials>{initials}</initials> <token xmlns:d4p1="http://www.timelog.com/api/tlp/v1_3" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <d4p1:Initials>{initials}</d4p1:Initials> <d4p1:Expires>{expires}</d4p1:Expires> <d4p1:Hash>{hash}</d4p1:Hash> </token> </GetTasksAllocatedToEmployee> </s:Body> </s:Envelope> '''.format(initials=user.token.initials, expires=user.token.expires, hash=user.token.hash) headers = { 'Content-Type': 'text/xml', 'SOAPAction': 'GetTasksAllocatedToEmployeeRequest' } xml = web.post( "https://app1.timelog.com/arnsbomedia/WebServices/ProjectManagement/V1_6/ProjectManagementServiceSecure.svc", data=data, headers=headers).text foo = xml.encode('utf-8') ns = { 's': 'http://schemas.xmlsoap.org/soap/envelope/', 'a': 'http://www.timelog.com/api/tlp/v1_1', 'i': 'http://www.w3.org/2001/XMLSchema-instance' } root = ET.fromstring(foo) path = 's:Body/{http://www.timelog.com/api/tlp/v1_6}GetTasksAllocatedToEmployeeResponse/' path += '{http://www.timelog.com/api/tlp/v1_6}GetTasksAllocatedToEmployeeResult/' path += '{http://api.timelog.com}Return/' path += '{http://www.timelog.com/api/tlp/v1_6}Task' tasks = [] for elm in root.findall(path, ns): uuid = elm.find('{http://www.timelog.com/api/tlp/v1_6}TaskID', ns).text name = elm.find('{http://www.timelog.com/api/tlp/v1_6}Name', ns).text project = elm.find( '{http://www.timelog.com/api/tlp/v1_6}Details/{http://www.timelog.com/api/tlp/v1_6}ProjectHeader/{http://www.timelog.com/api/tlp/v1_6}Name', ns).text task = Task(id=uuid, name=name, project=project) tasks.append(task) return tasks
def lookup(ip): resp = web.post('https://www.ipip.net/ip.html', data={'ip': ip}, headers={'Referer': 'https://www.ipip.net/'}, timeout=3) resp.raise_for_status() info = OrderedDict() for key, pattern in patterns.items(): results = re.findall(pattern, resp.text) info[key] = results[0] if results else u'' return info
def connect(name, passwd): params = dict(opr='pwdLogin', userName=name, pwd=passwd) r = web.post(loginurl, params) r.raise_for_status() log.debug(r.status_code) # encoding 的值为 None # 不得不BS一下硬件公司的软件程序员的编码水平 # 没有 encoding ,JSON用单引号 log.debug(r.encoding) # 是哪个傻X在JSON里面使用单引号! jsonstr = unicode(r.content, 'utf8').replace("'", '"') result = json.loads(jsonstr) notify.notify(result['msg'], u'user: %s' % result['userName'])
def test_post_json(self): """POST request with JSON body""" url = BASE_URL + 'post' headers = {'content-type': 'application/json'} print('Posting JSON ...') r = web.post(url, headers=headers, data=json.dumps(self.data)) self.assert_(r.status_code == 200) data = r.json() pprint(data) self.assertEqual(data['headers']['Content-Type'], 'application/json') for key in self.data: self.assert_(data['json'][key] == self.data[key]) return
def add_www_ip(wf, ip='myip'): response = web.post(TAOBAO_IP_API, params={'ip': ip}).json() data = response['data'] if response['code'] == 0: wf.add_item( title=data['ip'], subtitle=u'{} {} {}'.format(data['country'], data['city'], data['isp']), arg=data['ip'], valid=True, icon=ICON_WEB) else: wf.add_item( title='unknown address', subtitle='WWW IP Address', icon=ICON_WEB)
def add(word_id): log.debug('word_id: ' + str(word_id)) if not is_authed(): notify('请授权后再添加!', '详情: https://ghui.me/post/2017/01/ishanbay/') do_auth() return 0 else: # do add params = dict(id=word_id, access_token=get_token()) r = web.post(LEARNING_URL, None, params) r.raise_for_status() if r.json()['status_code'] == 0: word = wf.stored_data('current_word') notify('添加成功', word + ' 已添加到生词本')
def test_post_json(self): """POST request with JSON body""" url = self.httpbin.url + '/post' headers = {'content-type': 'application/json'} print('Posting JSON ...') r = web.post(url, headers=headers, data=json.dumps(self.data)) self.assert_(r.status_code == 200) data = r.json() pprint(data) self.assertEqual(data['headers']['Content-Type'], 'application/json') for key in self.data: self.assert_(data['json'][key] == self.data[key]) return
def get_addressbook(token): url = 'http://ph.in.ruguoapp.com/api/phriction.document.search' data = { 'constraints[ids][0]': 14, 'attachments[content]': 1, 'api.token': token, } payload = urlencode(data) headers = {'Content-Type': "application/x-www-form-urlencoded"} res = web.post(url, data=payload, headers=headers) res.raise_for_status() result = res.json() return result['result']['data'][0]['attachments']['content']['content'][ 'raw']
def login(username, password): md5pwd = hexlify(md5(password.encode('latin-1')).digest()) data = { 'action': 'login', 'username': username, 'password': u'{MD5_HEX}' + md5pwd, 'ac_id': 1 } try: res = post(LOGIN_URL, data=data, timeout=1) notify(title=str(res.status_code), text=res.text) except URLError as e: notify(title=str(e.errno), text=str(e.reason))
def wrapper(): """`cached_data` can only take a bare callable (no args), so we need to wrap callables needing arguments in a function that needs none. """ try: wf.add_item('Getting employ information from server', valid=False, icon=ICON_INFO) r = web.post(url=GARMIN_URL, cookies=co, data=params) r.raise_for_status() return parse_html(r) except urllib2.HTTPError, err: os.remove(COOKIE_NAME)
def login(): res = web.post( 'http://codingcorp.coding.9.134.77.232.xip.io/api/v2/account/login', data=dict(enterprise_key, account, password, feie_password)) if res.status_code != 200: res.raise_for_status() return None pass cookie = res.headers['Set-Cookie'] # extract eid from eid=665ff54f-bd7e-48b1-9b35-dfc01a988537;Path=/;Domain=.codingcorp.coding.9.134.77.232.xip.io;HttpOnly regex = r"(?<=eid\=).*?(?=;)" matche = re.search(regex, cookie, re.MULTILINE) eid = matche.groups(0) return eid
def test_file_upload_without_form_data(self): """File upload w/o form data""" url = self.httpbin.url + '/post' files = {'file': {'filename': 'cönfüsed.gif', 'content': open(self.test_file, 'rb').read() }} r = web.post(url, files=files) self.assertEqual(r.status_code, 200) data = r.json() # image bindata = data['files']['file'] preamble = 'data:image/gif;base64,' self.assert_(bindata.startswith(preamble)) bindata = b64decode(bindata[len(preamble):]) self.assertEqual(bindata, open(self.test_file, 'rb').read())
def main(wf): AUTH_CODE = wf.stored_data('AUTH_CODE') APP_KEY = wf.stored_data('APP_KEY') log.info('AUTH_CODE: ' + AUTH_CODE) log.info('APP_KEY: ' + APP_KEY) start_time = time.time() elapsed_time = 0 token_url = 'https://api.ecobee.com/token' params = dict(grant_type='ecobeePin', code=AUTH_CODE, client_id=APP_KEY) log.debug('Making query to {} with params {}'.format(token_url, params)) code = 401 log.info('Starting Loop') # Run timer for 10 mins while (elapsed_time < 10 * 60) and code != 200: time.sleep(5) log.info('Elapsed time {}'.format(elapsed_time)) # Calculate elapsed time in seconds elapsed_time = int(time.time() - start_time) # Make request r = web.post(token_url, params) # Extract status code code = r.status_code log.info(token_url) log.info(params) log.info(r.status_code) if code == 200: log.info('Auth success') notify.notify('SUCCESS', 'Ecobee plugin authorization complete') wf.store_data('ACCESS_TOKEN', r.json()['access_token']) wf.store_data('REFRESH_TOKEN', r.json()['refresh_token']) else: log.debug('Auth timeout') notify.notify('Ecobee authorization: FAILED', 'The authorization task has timed out') log.info('Terminating background process')
def build_job(self, query=None): self.valid_setting() r = web.get(self.get_jenkins_url() + "/crumbIssuer/api/json", headers=self.append_auth_2_header()) crumb = r.json().get(u'crumb') job = self.parse_job_name_by_url(query) branch = self._workflow.settings.get('job_build_default_branch' + ':' + job) if not branch: branch = "test" data = {"branch": branch, "Jenkins-Crumb": crumb} r = web.post(query + '/buildWithParameters', data=data, headers=self.append_auth_2_header()) if r.status_code == 201: return True else: raise BuildFail
def main(wf): query = sys.argv[1] url = 'http://t.bdaily.club' params = json.dumps({"url": query}) r = web.post(url, data=params) r.raise_for_status() result = r.json() if result["msg"] == "ok": data = result["data"] wf.add_item(title=data["tiny_url"], subtitle="tiny url") for url in data["hash_urls"]: wf.add_item(title=url, subtitle="hash url") else: wf.add_item(title=result["msg"]) wf.send_feedback()
def post_json_to_ha(url, path, password, josn): url = url + '/api/services/' + path + '?api_password='******'url : '+ url + '\n') params = dict(count=100, format='json') #r = web.post(url, dict, data='{"entity_id": "' + entity_id + '"}'); sys.stderr.write('josn : '+ josn + '\n') r = web.post(url, params, josn, headers=None, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False) # throw an error if request failed # Workflow will catch this and show it to the user r.raise_for_status() result = r.json() sys.stderr.write('post result : '+ r.text + '\n') return result;
def queryTrans(queryStr): data = json.dumps({'text': queryStr}) res = web.post('https://lab.magiconch.com/api/nbnhhsh/guess', headers={'content-type': 'application/json'}, data=str(data)) if res.status_code != 200: return [u"错误" + res.status_code] resJson = res.json() if len(resJson) == 0: return [] if 'trans' in resJson[0]: return resJson[0]['trans'] if 'inputting' in resJson[0]: return resJson[0]['inputting']
def screenshots_parse(path=''): with open(path, 'rb') as img: image_data = img.read() base64_data = base64.b64encode(image_data) if len(base64_data) > 4 * 1024 * 1024: sys.stdout.write('图片必须小于4M') return result = web.post('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic', params={ 'access_token': get_access_token(), }, data={ 'image': base64_data, }).json() output(result)
def test_file_upload(self): """File upload""" url = self.httpbin.url + '/post' files = {'file': {'filename': 'cönfüsed.gif', 'content': open(self.test_file, 'rb').read(), 'mimetype': 'image/gif', }} r = web.post(url, data=self.data, files=files) self.assertEqual(r.status_code, 200) data = r.json() form = data['form'] for key in self.data: self.assertEqual(self.data[key], form[key]) # image bindata = data['files']['file'] preamble = 'data:image/gif;base64,' self.assert_(bindata.startswith(preamble)) bindata = b64decode(bindata[len(preamble):]) self.assertEqual(bindata, open(self.test_file, 'rb').read())
def get_exchange_rate(payload): r = post( "https://adsynth-ofx-quotewidget-prod.herokuapp.com/api/1", data=payload, headers={"Content-Type": "application/json"}, ) if r.status_code < 400: data = r.json() try: data["error"] raise Exception(data["error"]) except KeyError: pass exchange_rate = data["data"]["CurrentInterbankRate"] fetch_time = datetime.datetime.fromtimestamp( data["data"]["fetchTime"] // 1000).strftime("%Y-%m-%d %H:%M:%S") return exchange_rate, fetch_time else: raise NetworkError(r.status_code)
def add_log(log_url): """ Create a log """ url = urllib.quote(log_url) r = web.post( url="https://www.analogue.app/api/contents/parse?url={}".format(url), params=None, headers={ "authorization": "Token eyJhbGciOiJIUzI1NiJ9.eyJpZCI6ODUwMywiZXhwIjoxNTk0Nzg1MDY5fQ.qr9HFOlUUqNTV9WassFoVKUuS8fQ08aw05BmLaZzOUw", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36", "Content-Type": "application/json", "Accept": "*/*", "Origin": "https://www.analogue.app", "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty", "Referer": "https://www.analogue.app/alfred", "Accept-Language": "en-US,en;q=0.9", "Cookie": "ajs_group_id=null; ajs_anonymous_id=%22453c9e9b-20d9-464b-9b2f-544d08c4517c%22; ajs_user_id=%228503%22; _lr_uf_-9zropr=1f5d3d9a-7af1-478a-af9a-9bdd499187e6; amplitude_idundefinedanalogue.app=eyJvcHRPdXQiOmZhbHNlLCJzZXNzaW9uSWQiOm51bGwsImxhc3RFdmVudFRpbWUiOm51bGwsImV2ZW50SWQiOjAsImlkZW50aWZ5SWQiOjAsInNlcXVlbmNlTnVtYmVyIjowfQ==; _lr_tabs_-9zropr%2Fanalogue={%22sessionID%22:0%2C%22recordingID%22:%224-6ccf0dab-5235-4d33-a78a-0693d0268674%22%2C%22lastActivity%22:1588357409717}; _lr_hb_-9zropr%2Fanalogue={%22heartbeat%22:1588357409717}; mp_42c2d87f255cdb53a9581d2596fe60d6_mixpanel=%7B%22distinct_id%22%3A%20%228503%22%2C%22%24device_id%22%3A%20%22171a213b18430e-0029530280115b-39687506-13c680-171a213b185a21%22%2C%22mp_lib%22%3A%20%22Segment%3A%20web%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22%24user_id%22%3A%20%228503%22%2C%22mp_name_tag%22%3A%20%22hughmil3s%40gmail.com%22%2C%22type%22%3A%20%22consumer%22%2C%22id%22%3A%20%228503%22%2C%22%24email%22%3A%20%22hughmil3s%40gmail.com%22%2C%22%24first_name%22%3A%20%22Hugh%22%2C%22%24last_name%22%3A%20%22A.%20Miles%20II%22%2C%22%24name%22%3A%20%22Hugh%20A.%20Miles%20II%22%2C%22%24username%22%3A%20%22hugh%22%7D; amplitude_id_4bf7a5f993ab7a9311ed9393614f20c5analogue.app=eyJkZXZpY2VJZCI6IjAwNDJmZGM2LTY0OTktNDY4Yi1hZjFhLTEzOTFjOTI5MGFiYVIiLCJ1c2VySWQiOiI4NTAzIiwib3B0T3V0IjpmYWxzZSwic2Vzc2lvbklkIjoxNTg4MzU2NTY1NzE2LCJsYXN0RXZlbnRUaW1lIjoxNTg4MzU3NDE5MTA2LCJldmVudElkIjoxNTAsImlkZW50aWZ5SWQiOjQ3LCJzZXF1ZW5jZU51bWJlciI6MTk3fQ==", "Accept-Encoding": "gzip", }, cookies=None, files=None, auth=None, timeout=60, allow_redirects=False, stream=False, data=json.dumps({}), ) return "https://www.analogue.app/{}/{}/@{}".format( r.json()["content"]["form"], r.json()["content"]["slug"], r.json()["log"]["user"]["username"], )
def newnb(url, path, copy=None): """Create new untitled notebook at 'path' Server base URL is 'url' Returns name of the new notebook file. """ # See IPython/html/services/notebooks/handlers.py for API details. # Compare directory contents before and after new notebook creation. names = [ nb['name'] for nb in get_nblist(url, path) if nb['type'] == 'notebook' ] arg = path if isinstance(arg, unicode): arg = arg.encode('utf-8') post_url = urljoin(url, 'api/notebooks', quote(arg)).strip('/') if copy is not None: data = json.dumps({'copy_from': copy}) else: data = '' try: resp = web.post(post_url, data=data) except URLError: raise URLError('Unable to reach %s. Try the "nbserver" keyword.' % url) resp.raise_for_status() new_contents = get_nblist(url, path) new_names = [nb['name'] for nb in new_contents if nb['type'] == 'notebook'] try: newnbname = list(set(new_names) - set(names))[0] except IndexError: raise RuntimeError('Notebook creation at %s appears to have failed.' % post_url) return newnbname
def update(self, subject): """Mark the next episode as watched. :param str subject: the id of this anime :returns: TODO """ watched = self.watch_status(subject) sleep(1) eps = self.anime_episodes(subject) if watched < len(eps): url = ( 'https://api.bgm.tv/ep/' '{0}/status/watched?source=onAir'.format(eps[watched]) ) data = {'auth': self._auth} r = web.post(url, data=data) r.raise_for_status() result = r.json() if result['code'] == 200: episode = str(watched + 1) notify( "Bangumi", ( "Sucessfully mark episode {0} as watched!". format(episode) ) ) return episode else: notify( "Bangumi", "Error {0}: {1}".format(result['code'], result['error']) ) return -1
def _post_request(url, payload, headers): r = requests.post(url, data=payload, headers=headers) return r
def get_web_data(query): return web.post('https://namebeta.com/api/query', data={'q': query}).json()
def ajax_get(kw): r = web.post('http://soft.macx.cn/ajax_result.asp', data=dict(keyword=kw)) r.raise_for_status() return r.text
def main(wf): args = wf.args[0].split() if not args: return _get_menu() command, args = args[0], args[1:] if command not in COMMANDS: return _unknown_command(command) if not args: if command == AUTH_COMMAND: button, email = dialog.get_from_user( 'Sign in to Inoreader', 'Enter your email', extra_buttons='Sign up' ) if button == 'Ok': button, password = dialog.get_from_user( 'Sign in to Inoreader', 'Enter your password', ) response = web.post( 'https://www.inoreader.com/accounts/ClientLogin', data={ 'Email': email, 'Passwd': password } ) wf.logger.debug(response.status_code) if response.status_code == 200: wf.logger.debug(response.text) wf.settings['token'] = dict( line.split('=') for line in response.text.split() )['Auth'] elif button == 'Sign up': import webbrowser webbrowser.open('http://www.inoreader.com/') else: wf.add_item(COMMANDS[command], valid=False, icon=workflow.ICON_INFO) wf.send_feedback() return 0 if len(args) > 1: wf.add_item( 'Remove extra argument', valid=False, icon=workflow.ICON_ERROR ) wf.send_feedback() return 0 wf.add_item( 'Save', valid=True, arg='{} {}'.format(command, args[0].strip()), icon=workflow.ICON_SYNC ) wf.send_feedback() return 0
def createTask(inputName, inputContent, inputDue, inputPriority, inputTags, inputList): '''Creates a Task by sending it to the ClickUp API. ---------- @param str inputName: The user's input for the task title. @param str inputContent: The user's input for the task decsription. @param str inputDue: The user's input for the task due date. @param str inputPriority: The user's input for the task priority. @param str inputTags: The user's input for the task tags. @param str inputList: The user's input for the task list. ''' if DEBUG > 0: log.debug('[ Calling API to create task ]') if not inputList: inputListId = getConfigValue(confNames['confList']) else: # Get value of first key in dictionary {Name, Id} by converting to List. The dict will always contain a single list name+Id the user specified. inputListId = next(iter(inputList.items()))[1] # Get value for first key of dict if inputDue != 'None': if len(inputDue) == 26: # 2020-01-01T12:00:00.000000 inputDue = datetime.datetime.strptime(str(inputDue)[:len(inputDue) - 10], '%Y-%m-%d %H:%M') # Convert String to datetime. Remove seconds.milliseconds (e.g. :26.614286) from string else: # 2020-01-01T12:00:00 inputDue = datetime.datetime.strptime(str(inputDue)[:len(inputDue)], '%Y-%m-%d %H:%M:%S') inputDueMs = (inputDue - datetime.datetime.fromtimestamp(0)).total_seconds() * 1000.0 # Convert datetime into ms. Use fromtimestamp() to get local timezone instead of utcfromtimestamp() url = 'https://api.clickup.com/api/v2/list/' + inputListId + '/task' params = None headers = {} headers['Authorization'] = getConfigValue(confNames['confApi']) headers['Content-Type'] = 'application/json' data = {} data['name'] = inputName data['content'] = inputContent if inputDue != 'None': data['due_date'] = int(inputDueMs) data['due_date_time'] = True # Translated into true data['priority'] = inputPriority if inputPriority is not None else None # Translated into 'null' data['tags'] = inputTags if getConfigValue(confNames['confUser']): # Default assignee = current user data['assignees'] = [getConfigValue(confNames['confUser'])] if DEBUG > 1: log.debug(url) log.debug(headers) log.debug(data) try: import json request = web.post(url, params = params, data = json.dumps(data), headers = headers) request.raise_for_status() except: log.debug('Error on HTTP request') wf.add_item(title = 'Error connecting to ClickUp.', subtitle = 'Open configuration to check your parameters?', valid = True, arg = 'cu:config ', icon = 'error.png') wf.send_feedback() exit() result = request.json() if DEBUG > 1: log.debug('Response: ' + str(result)) # If user pressed 'opt' (optInput == true), we do not want to show a notification, as the task is opened in the browser hasUserNotPressedOpt = 'optInput' not in os.environ or os.environ['optInput'] == 'false' if getConfigValue(confNames['confNotification']) == 'true' and (hasUserNotPressedOpt): notify('Created: ' + inputName, formatNotificationText(inputContent, inputDue, inputTags, inputPriority, inputList, True)) elif os.environ['optInput'] and os.environ['optInput'] == 'true': print(result['url'])
def test_post_without_data(self): """POST request without data""" url = self.httpbin + '/post' r = web.post(url) self.assert_(r.status_code == 200) r.raise_for_status()
def __get_token(self): params = {'Subscription-Key': self.api_key} r = web.post(TOKEN_URL, params) r.raise_for_status() return 'Bearer' + ' ' + r.content
def post(self, action, params={}, data={}): url = self.HOST + action + '/' return web.post(url, params=params, data=data).json()
def add(word_id): data = {'access_token': TOKEN, 'id': word_id} r = web.post(ADD_URL, data=data) check_status(r) notify("Added to wordbook", word_id)
def note(word, notes): data = {'access_token': TOKEN, 'vocabulary': get_word_id(word), 'note': DELIMITER.join(notes).strip()} r = web.post(NOTE_URL, data=data) check_status(r) notify("Note added", word)
def load_response(self, params): response = web.post(IME.URL, params=params.__dict__) response.raise_for_status() return response