def oauth_callback(self, params): if 'code' not in params: return None conn = HTTPSConnection("accounts.google.com") body = tools.encode_params({ "grant_type":"authorization_code", "code":params['code'], "client_id":secrets.GMAIL_CLIENT_ID, "client_secret":secrets.GMAIL_CLIENT_SECRET, "redirect_uri":secrets.BASE_REDIRECT_URL + "gmail", }) headers = { "Content-Type":"application/x-www-form-urlencoded", } conn.request("POST", "/o/oauth2/token", body, headers) resp = conn.getresponse() try: self.token = json.loads(resp.read())['access_token'] self.is_auth = True except (KeyError, ValueError): return None conn.close() conn = HTTPSConnection("www.googleapis.com") conn.request("GET","/oauth2/v1/tokeninfo?alt=json&access_token="+self.token,"",{}) resp = conn.getresponse() self.username = json.loads(resp.read())['email']
def pushover(message, token, user, title="JCVI: Job Monitor", \ priority=0, timestamp=None): """ pushover.net python API <https://pushover.net/faq#library-python> """ assert -1 <= priority <= 2, \ "Priority should be an int() between -1 and 2" if timestamp == None: from time import time timestamp = int(time()) retry, expire = (300, 3600) if priority == 2 \ else (None, None) conn = HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urlencode({ "token": token, "user": user, "message": message, "title": title, "priority": priority, "timestamp": timestamp, "retry": retry, "expire": expire, }), { "Content-type": "application/x-www-form-urlencoded" }) conn.getresponse()
def test_no_content_length(self): # "The presence of a message-body in a request is signaled by the # inclusion of a Content-Length or Transfer-Encoding header field in # the request's message-headers." # # Send a message with neither header and no body. Even though # the request is of method POST, this should be OK because we set # request.process_request_body to False for our handler. if self.scheme == "https": c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT)) else: c = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) c.request("POST", "/no_body") response = c.getresponse() self.body = response.fp.read() self.status = str(response.status) self.assertStatus(200) self.assertBody('Hello world!') # Now send a message that has no Content-Length, but does send a body. # Verify that CP times out the socket and responds # with 411 Length Required. if self.scheme == "https": c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT)) else: c = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) c.request("POST", "/") response = c.getresponse() self.body = response.fp.read() self.status = str(response.status) self.assertStatus(411)
def call( self, url, method, apiData = dict(), itemData = dict() ): # Step1: Retrieve csrfID conn = HTTPSConnection( self.host, self.port ) conn.connect() headers = { 'Host': self.host, 'Referer': 'https://%s/' % ( self.host ) } conn.request( 'GET', self.__buildGETUrl( url, itemData ), headers=self.__insertCookies( headers ) ) initialResponse = conn.getresponse() self.__setCookies( initialResponse ) formParser = PfSenseFormParser() formParser.parse( initialResponse ) # Step2: build form apiData and call the actual API if formParser.csrf: apiData[ '__csrf_magic' ] = formParser.csrf apiData.update( itemData ) if method == 'GET': conn.request( 'GET', self.__buildGETUrl( url, apiData ), headers=self.__insertCookies( headers ) ) elif method == 'POST': finalHeaders = self.__insertCookies( headers ) if formParser.formEncoding == "application/x-www-form-urlencoded": headers[ "Content-type" ] = formParser.formEncoding postEncoded = urlencode( apiData ) conn.request( 'POST', url, headers=finalHeaders, body=postEncoded ) else: # Multipart mime = email.mime.multipart.MIMEMultipart( 'form-data' ) for (name, data) in apiData.items(): if isinstance( data, email.mime.base.MIMEBase ): attachment = data else: attachment = email.mime.text.MIMEText( data, 'plain' ) if attachment.get_param( 'filename' ): attachment.add_header('Content-Disposition', 'form-data', name=name, filename=attachment.get_param( 'filename' ) ) attachment.del_param( 'filename' ) else: attachment.add_header('Content-Disposition', 'form-data', name=name ) mime.attach( attachment ) body = mime.as_string() # Content-type from mime now has the embedded boundary tag that is required for the multipart stuff to work headers[ "Content-type" ] = mime.get( 'Content-type' ) conn.request( 'POST', url, headers=finalHeaders, body=body ) else: raise ArgumentError( 'Bad API call: method must be either POST or GET' ) finalResponse = conn.getresponse() self.__setCookies( finalResponse ) return (finalResponse.status, finalResponse.read(), finalResponse.getheader( 'Content-type', 'text/html' ))
def login(self): conn = HTTPSConnection(WebAuthAuthenticator.LOGIN_HOST, 443) if not self.username or not self.password: raise errors.AuthenticationError("You need to specify a login and a password to authenticate") conn.request("GET", "/") resp = conn.getresponse() location = resp.getheader("Location", "") if location: url = urlparse.urlparse(location) query = urlparse.parse_qs(url.query) RT = query['RT'][0] ST = query['ST'][0] LC = '>' login = "******" params = urllib.urlencode({'RT': RT, 'ST': ST, 'LC': '>', 'login': "******", 'username' : self.username, 'password' : self.password }) conn.request('POST', '/login', params, { "Referer" : location }) resp = conn.getresponse() while True: location = resp.getheader("Location", "") for header, value in resp.getheaders(): if header == "set-cookie": cookie = Cookie.SimpleCookie(value) self.cookie.update(cookie) if resp.status in (302, 303) and location: conn = HTTPSConnection(WebAuthAuthenticator.LOGIN_HOST, 443) conn.request('GET', location) resp = conn.getresponse() continue break resp.read() self.authenticated = True self.clear_credentials() if 'webauth_at' in self.cookie: return True else: raise errors.InvalidAuthenticationMethod(method=self.__class__.__name__) return False
def test_post_multipart(self): alphabet = "abcdefghijklmnopqrstuvwxyz" # generate file contents for a large post contents = "".join([c * 65536 for c in alphabet]) # encode as multipart form data files=[('file', 'file.txt', contents)] content_type, body = encode_multipart_formdata(files) # post file if self.scheme == 'https': c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT)) else: c = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) c.putrequest('POST', '/post_multipart') c.putheader('Content-Type', content_type) c.putheader('Content-Length', str(len(body))) c.endheaders() c.send(body) response = c.getresponse() self.body = response.fp.read() self.status = str(response.status) self.assertStatus(200) self.assertBody(", ".join(["%s * 65536" % c for c in alphabet]))
def notify(self, message, event): if not mylar.PROWL_ENABLED: return http_handler = HTTPSConnection("api.prowlapp.com") data = { "apikey": mylar.PROWL_KEYS, "application": "Mylar", "event": event, "description": message.encode("utf-8"), "priority": mylar.PROWL_PRIORITY, } http_handler.request( "POST", "/publicapi/add", headers={"Content-type": "application/x-www-form-urlencoded"}, body=urlencode(data), ) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info(u"Prowl notifications sent.") return True elif request_status == 401: logger.info(u"Prowl auth failed: %s" % response.reason) return False else: logger.info(u"Prowl notification failed.") return False
def notify(self, message, event): if not headphones.PUSHOVER_ENABLED: return http_handler = HTTPSConnection("api.pushover.net") data = {'token': self.application_token, 'user': headphones.PUSHOVER_KEYS, 'title': event, 'message': message.encode("utf-8"), 'priority': headphones.PUSHOVER_PRIORITY } http_handler.request("POST", "/1/messages.json", headers = {'Content-type': "application/x-www-form-urlencoded"}, body = urlencode(data)) response = http_handler.getresponse() request_status = response.status logger.debug(u"Pushover response status: %r" % request_status) logger.debug(u"Pushover response headers: %r" % response.getheaders()) logger.debug(u"Pushover response body: %r" % response.read()) if request_status == 200: logger.info(u"Pushover notifications sent.") return True elif request_status >= 400 and request_status < 500: logger.info(u"Pushover request failed: %s" % response.reason) return False else: logger.info(u"Pushover notification failed.") return False
def notify(self, message, event): if not mylar.PUSHOVER_ENABLED: return http_handler = HTTPSConnection("api.pushover.net:443") data = { "token": mylar.PUSHOVER_APIKEY, "user": mylar.PUSHOVER_USERKEY, "message": message.encode("utf-8"), "title": event, "priority": mylar.PUSHOVER_PRIORITY, } http_handler.request( "POST", "/1/messages.json", body=urlencode(data), headers={"Content-type": "application/x-www-form-urlencoded"}, ) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info(u"Pushover notifications sent.") return True elif request_status == 401: logger.info(u"Pushover auth failed: %s" % response.reason) return False else: logger.info(u"Pushover notification failed.") return False
def _get_signin_token(self, creds): """ GET the generated Signin Token from the federation endpoint :param creds: credentials to pass to the federation endpoint :type creds: dict :return: signin token returned by the federation endpoint :rtype: str """ host = 'signin.aws.amazon.com' req_path = 'https://signin.aws.amazon.com/federation' \ '?Action=getSigninToken' \ '&Session=%s' % quote_plus(json.dumps(creds)) logger.debug('HTTPS GET request to %s: %s', host, req_path) conn = HTTPSConnection(host, 443) conn.request('GET', req_path) resp = conn.getresponse() logger.debug('Response: HTTP %s %s', resp.status, resp.reason) logger.debug('Headers: %s', resp.getheaders()) body = resp.read() logger.debug('Body: %s', body.strip()) if resp.status != 200: logger.critical('AWS Federation endpoint responded HTTP %s %s: %s', resp.status, resp.reason, body) raise RuntimeError('Error obtaining console signin credentials.') try: b = json.loads(body)['SigninToken'] except Exception: logger.critical( 'AWS Federation endpoint returned an invalid response: %s', body ) raise RuntimeError('Invalid response from AWS Federation endpoint.') return b
def getRemoteDBModifiedTS(): """ Performs a HEAD request to get the Last-Modified date-time of a database dump file and parses it into a UNIX timestamp. """ debug_msg = 'Unable to get timestamp of remote database dump - {0}' logging.info("Getting timestamp of database dump at '%s'", HOST + PATH) try: # Removing the scheme from the URL conn = HTTPSConnection(HOST[8:], timeout=TIMEOUT) conn.request('HEAD', PATH) except gaierror as e: logging.debug( debug_msg.format( "Cannot connect to '%s', error: %s"), HOST + PATH, e) exit(1) rsp = conn.getresponse() if rsp.status != 200: logging.debug( debug_msg.format('Server responded with: %d %s'), rsp.status, rsp.reason) exit(1) last_modified = rsp.getheader('last-modified', None) if last_modified is None: logging.debug(debug_msg.format( 'Response doesnt include Last-Modified Header')) exit(1) last_m_dt = datetime.strptime( last_modified.split(', ')[1], '%d %b %Y %H:%M:%S %Z') return timegm(last_m_dt.timetuple())
def notify(self, message = '', data = {}, listener = None): http_handler = HTTPSConnection("api.pushover.net:443") data = { 'user': self.conf('user_key'), 'token': self.app_token, 'message': toUnicode(message), 'priority': self.conf('priority') } http_handler.request('POST', "/1/messages.json", headers = {'Content-type': 'application/x-www-form-urlencoded'}, body = tryUrlencode(data) ) response = http_handler.getresponse() request_status = response.status if request_status == 200: log.info('Pushover notifications sent.') return True elif request_status == 401: log.error('Pushover auth failed: %s', response.reason) return False else: log.error('Pushover notification failed.') return False
def notify(self, message, event): if not headphones.CONFIG.PROWL_ENABLED: return http_handler = HTTPSConnection("api.prowlapp.com") data = {'apikey': headphones.CONFIG.PROWL_KEYS, 'application': 'Headphones', 'event': event, 'description': message.encode("utf-8"), 'priority': headphones.CONFIG.PROWL_PRIORITY} http_handler.request("POST", "/publicapi/add", headers={ 'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info(u"Prowl notifications sent.") return True elif request_status == 401: logger.info(u"Prowl auth failed: %s" % response.reason) return False else: logger.info(u"Prowl notification failed.") return False
def _send_notify(pushalotapi, message): http_handler = HTTPSConnection("pushalot.com") if not pushalotapi: pushalotapi = autosub.PUSHALOTAPI data = {'AuthorizationToken': pushalotapi, 'Title': "Auto-Sub", 'Body': message.encode('utf-8') } try: http_handler.request("POST", "/api/sendmessage", headers = {'Content-type': "application/x-www-form-urlencoded"}, body = urlencode(data)) except: log.error("Pushalot: notification failed.") return False response = http_handler.getresponse() request_status = response.status if request_status == 200: log.info("Pushalot: notification sent.") return True elif request_status == 410: log.error("Pushalot: Auth failed %s" % response.reason) return False else: log.error("Pushalot: notification failed.") return False
def notify(self, message, event, module=None): if not mylar.PUSHOVER_ENABLED: return if module is None: module = '' module += '[NOTIFIER]' http_handler = HTTPSConnection("api.pushover.net:443") data = {'token': mylar.PUSHOVER_APIKEY, 'user': mylar.PUSHOVER_USERKEY, 'message': message.encode("utf-8"), 'title': event, 'priority': mylar.PUSHOVER_PRIORITY } http_handler.request("POST", "/1/messages.json", body = urlencode(data), headers = {'Content-type': "application/x-www-form-urlencoded"} ) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info(module + ' Pushover notifications sent.') return True elif request_status == 401: logger.info(module + 'Pushover auth failed: %s' % response.reason) return False else: logger.info(module + ' Pushover notification failed.') return False
class CMSWeb (object): def __init__ (self): self.URL_CMSWEB_BASE='cmsweb.cern.ch' self.URL_PHEDEX_BLOCKREPLICAS='/phedex/datasvc/json/prod/blockreplicas' self.URL_DBS_DATASETS='/dbs/prod/global/DBSReader/datasets' self.URL_DBS_FILES='/dbs/prod/global/DBSReader/files' self.URL_DBS_RUNS='/dbs/prod/global/DBSReader/runs' self.URL_DBS_BLOCKS='/dbs/prod/global/DBSReader/blocks' self.conn = HTTPSConnection(self.URL_CMSWEB_BASE, cert_file='/tmp/x509up_u{0}'.format(getuid()), timeout=30) self.reply_cache = {} self.last_result = "" self.errors = 0 def __del__(self): self.conn.close () def get_cmsweb_data(self, url): self.last_result = url if url in self.reply_cache: return True, self.reply_cache[url] msg ="" try: self.conn.request('GET', url) msg = self.conn.getresponse() if msg.status!=200: self.errors = self.errors + 1 print 'Result: {0} {1}: {2}'.format(msg.status, msg.reason, url) return False, {} self.reply_cache[url]=json.loads(msg.read()) return True, self.reply_cache[url] except Exception, e: print "Error:", e, url self.errors = self.errors + 1 return False, {}
def notify(self, message, event, module=None): if not mylar.PROWL_ENABLED: return if module is None: module = '' module += '[NOTIFIER]' http_handler = HTTPSConnection("api.prowlapp.com") data = {'apikey': mylar.PROWL_KEYS, 'application': 'Mylar', 'event': event, 'description': message.encode("utf-8"), 'priority': mylar.PROWL_PRIORITY } http_handler.request("POST", "/publicapi/add", headers = {'Content-type': "application/x-www-form-urlencoded"}, body = urlencode(data)) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info(module + ' Prowl notifications sent.') return True elif request_status == 401: logger.info(module + ' Prowl auth failed: %s' % response.reason) return False else: logger.info(module + ' Prowl notification failed.') return False
def send(hook_url, message, **kwargs): headers = { "Content-type": "application/json" } http_key = kwargs.pop("http_key", None) if not http_key and hasattr(settings, 'HTTP_KEY'): http_key = settings.HTTP_KEY headers["Authorization"] = "key={}".format(http_key) kwargs["msg"] = message up = urlparse(hook_url) if up.scheme == 'https': http = HTTPSConnection(up.netloc) else: http = HTTPConnection(up.netloc) http.request( "POST", up.path, headers=headers, body=dumps(kwargs)) response = http.getresponse() if response.status != 200: raise HTTPError(response.reason) return True
def _send_notify(pushbulletapi, message): http_handler = HTTPSConnection("api.pushbullet.com") if not pushbulletapi: pushbulletapi = autosub.PUSHBULLETAPI mydata = {'type': 'note'.encode('utf-8'), 'title': 'Auto-Sub'.encode('utf-8'), 'body': message.encode('utf-8') } try: http_handler.request('POST', '/v2/pushes', body=json.dumps(mydata), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % pushbulletapi}) except: log.error("Pushbullet: notification failed.") return False response = http_handler.getresponse() request_status = response.status if request_status == 200: log.info("Pushbullet: notification sent.") return True elif request_status == 401: log.error("Pushbullet: No valid access token provided") return False elif request_status == 403: log.error("Pushbullet: The access token is not valid for that request") return False else: log.error("Pushbullet: notification failed with error") return False
def _probe_geonode_wms(self, raw_url): url = urlsplit(raw_url) if url.scheme == 'https': conn = HTTPSConnection(url.hostname, url.port) else: conn = HTTPConnection(url.hostname, url.port) conn.request('GET', '/api/ows_endpoints/', '', {}) response = conn.getresponse() content = response.read() status = response.status content_type = response.getheader("Content-Type", "text/plain") # NEW-style OWS Enabled GeoNode if status == 200 and 'application/json' == content_type: try: _json_obj = json.loads(content) if 'data' in _json_obj: data = _json_obj['data'] for ows_endpoint in data: if 'OGC:OWS' == ows_endpoint['type']: return ows_endpoint['url'] + '?' + url.query except BaseException: pass # OLD-style not OWS Enabled GeoNode _url = "%s://%s/geoserver/ows" % (url.scheme, url.netloc) return _url
def _sendPushalot(self, pushalot_authorizationtoken=None, event=None, message=None, force=False): if not sickrage.srCore.srConfig.USE_PUSHALOT and not force: return False sickrage.srCore.srLogger.debug("Pushalot event: " + event) sickrage.srCore.srLogger.debug("Pushalot message: " + message) sickrage.srCore.srLogger.debug("Pushalot api: " + pushalot_authorizationtoken) http_handler = HTTPSConnection("pushalot.com") data = {'AuthorizationToken': pushalot_authorizationtoken, 'Title': event.encode('utf-8'), 'Body': message.encode('utf-8')} try: http_handler.request("POST", "/api/sendmessage", headers={'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) except (SSLError, HTTPException, socket.error): sickrage.srCore.srLogger.error("Pushalot notification failed.") return False response = http_handler.getresponse() request_status = response.status if request_status == 200: sickrage.srCore.srLogger.debug("Pushalot notifications sent.") return True elif request_status == 410: sickrage.srCore.srLogger.error("Pushalot auth failed: %s" % response.reason) return False else: sickrage.srCore.srLogger.error("Pushalot notification failed.") return False
def send(token, title, **kwargs): """ Site: https://boxcar.io/ API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api Desc: Best app for system administrators """ headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), } data = { "user_credentials": token, "notification[title]": from_unicode(title), "notification[sound]": "notifier-2" } for k, v in kwargs.items(): data['notification[%s]' % k] = from_unicode(v) http = HTTPSConnection(kwargs.pop("api_url", "new.boxcar.io")) http.request( "POST", "/api/notifications", headers=headers, body=urlencode(data)) response = http.getresponse() if response.status != 201: raise BoxcarError(response.reason) return True
def notify(self, message="", data={}, listener=None): if self.isDisabled(): return http_handler = HTTPSConnection("api.prowlapp.com") data = { "apikey": self.conf("api_key"), "application": self.default_title, "description": toUnicode(message), "priority": self.conf("priority"), } http_handler.request( "POST", "/publicapi/add", headers={"Content-type": "application/x-www-form-urlencoded"}, body=tryUrlencode(data), ) response = http_handler.getresponse() request_status = response.status if request_status == 200: log.info("Prowl notifications sent.") return True elif request_status == 401: log.error("Prowl auth failed: %s", response.reason) return False else: log.error("Prowl notification failed.") return False
def _getDailymotionAPI(self, vid): self.logger.debug("Retrieving video information from the Dailymotion API.") con = HTTPSConnection("api.dailymotion.com", timeout=10) params = {"fields", "title,duration,allow_embed"} data = None try: try: con.request("GET", "/video/%s?fields=title,duration,allow_embed" % (vid)) data = con.getresponse().read() except SSLError as e: # There is a bug in OpenSSL 1.0.1 which affects Python 2.7 on systems that rely on it. # Attempt to use curl as a fallback. # Curl must be installed for this to work. # This is the worst hack I have ever coded. # Since vid is a valid video id there is no risk of any attack. self.logger.warning("SSL Error, attempting to use curl as a fallback.") try: data = subprocess.check_output(["curl", "-k", "-s", "-m 10", "https://api.dailymotion.com/video/%s?fields=title,duration,allow_embed" % (vid)]) except Exception as e: self.logger.warning("Curl fallback failed.") data = "SSL Failure" raise e # Do this last and separately to avoid catching it elsewhere. data = json.loads(data) except Exception as e: # Many things can go wrong with an HTTP request or during JSON parsing self.logger.warning("Error retrieving Dailymotion API information.") self.logger.debug(e) finally: con.close() return data
def notify(self, message, event): if not headphones.PUSHBULLET_ENABLED: return http_handler = HTTPSConnection("api.pushbullet.com") data = {'device_iden': headphones.PUSHBULLET_DEVICEID, 'type': "note", 'title': "Headphones", 'body': message.encode("utf-8") } http_handler.request("POST", "/api/pushes", headers = {'Content-type': "application/x-www-form-urlencoded", 'Authorization' : 'Basic %s' % base64.b64encode(headphones.PUSHBULLET_APIKEY + ":") }, body = urlencode(data)) response = http_handler.getresponse() request_status = response.status logger.debug(u"PushBullet response status: %r" % request_status) logger.debug(u"PushBullet response headers: %r" % response.getheaders()) logger.debug(u"PushBullet response body: %r" % response.read()) if request_status == 200: logger.info(u"PushBullet notifications sent.") return True elif request_status >= 400 and request_status < 500: logger.info(u"PushBullet request failed: %s" % response.reason) return False else: logger.info(u"PushBullet notification failed serverside.") return False
def notify(self, message = '', data = {}): if self.isDisabled(): return http_handler = HTTPSConnection('api.prowlapp.com') data = { 'apikey': self.conf('api_key'), 'application': self.default_title, 'description': toUnicode(message), 'priority': self.conf('priority'), } http_handler.request('POST', '/publicapi/add', headers = {'Content-type': 'application/x-www-form-urlencoded'}, body = urlencode(data) ) response = http_handler.getresponse() request_status = response.status if request_status == 200: log.info('Prowl notifications sent.') return True elif request_status == 401: log.error('Prowl auth failed: %s' % response.reason) return False else: log.error('Prowl notification failed.') return False
def doLogin(self): """ Perform login, raise exception if something wrong """ self.api_url = None self.auth_token = None uri = urlparse.urlparse(self.auth_url) headers = dict() headers['x-auth-user'] = self.api_user headers['x-auth-key'] = self.api_key conn = HTTPSConnection(uri.hostname, uri.port) conn.request('GET', self.auth_url, '', headers) response = conn.getresponse() buff = response.read() # 401 == Auth failed if response.status == 401: raise RackSpaceAuthenticationFailedException() # TODO: check codes and return more informative exceptions if response.status != 204: raise RackSpaceException() for header in response.getheaders(): if header[0].lower() == "x-server-management-url": self.api_url = header[1] if header[0].lower() == "x-auth-token": self.auth_token = header[1] conn.close() if self.auth_token is None or self.api_url is None: # Invalid response raise RackSpaceException()
def USCWebGISGeocoder(address, locality, region, zipcode, apiKey): uscwebgisUrl = "/Services/Geocode/WebService/GeocoderWebServiceHttpNonParsed_V02_96.aspx?" queryParams = { 'zip' : zipcode, 'apiKey' : apiKey, 'version' : '2.96', 'format' : 'csv', } if not address is None: queryParams['streetAddress'] = address if not locality is None: queryParams['city'] = locality if not region is None: queryParams['state'] = region requestUrl = uscwebgisUrl + urlencode(queryParams) conn = HTTPSConnection('webgis.usc.edu') geocodeRequest = conn.request('GET', requestUrl) response = conn.getresponse() if response.status != 200: raise LocationNotFoundError('Status code was not 200') parsedData = response.read().split(',') if parsedData[2] != "200": raise LocationNotFoundError('results contained error') return (float(parsedData[3]) , float(parsedData[4]))
def request(action, param=None, **params): """ 发送请求数据 """ if param: params.update(param) params = signature(params) logger.info("%s : params:%s", action, params) if PROXY: conn = HTTPSConnection(PROXY) conn.set_tunnel(API_SITE, 443) else: conn = HTTPSConnection(API_SITE) conn.request(API_METHOD, '/api/' + action + '/', urllib.urlencode(params), {"Content-type": "application/x-www-form-urlencoded"}) response = conn.getresponse() result = response.read() conn.close() if response.status < 200 or response.status >= 300: raise Exception(result) else: data = json.loads(result.decode('utf8')) logger.debug('%s : result:%s', action, data) if data.get('code') != 0: raise Exception("api error:", data.get('message')) data = data.get('data') if data is None: raise Exception('response data is none') return data
def request(self, method, endpoint, headers=None, **params): url = "https://api.pingdom.com/api/{version}/{endpoint}".format( **dict( username=self.username, password=self.password, version=self.version, endpoint=endpoint ) ) if headers is None: headers = dict() if 'Account-Email' not in headers: headers['Account-Email'] = self.account if 'App-Key' not in headers: headers['App-Key'] = self.apikey if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' if 'Authorization' not in headers: headers['Authorization'] = 'Basic %s' % base64.encodestring( "{username}:{password}".format(username=self.username, password=self.password) ) conn = HTTPSConnection('api.pingdom.com', context=ctx) conn.request( method, "/api/{version}/{endpoint}".format(version=self.version, endpoint=endpoint), headers=headers ) response = conn.getresponse() body = response.read() return json.loads(body)
def query(query, args): """Query the eve online API and return a result object.""" query = _make_query_string(query, args) con = HTTPSConnection('api.eveonline.com') con.request('GET', query) response = con.getresponse() if response.status != 200: raise APIError("HTTPS GET failed") return objectify.fromstring(response.read())
def get_response(url): '''Return response object from URL''' try: conn = HTTPSConnection(url, timeout=CONN_TIMEOUT) conn.request('HEAD', '/') return conn.getresponse() except socket.error, e: log(str(e)) return None
def auth_checker(access_token): # Do a simple api request using the access token connection = HTTPSConnection('api.hubapi.com') connection.request( 'GET', '/contacts/v1/lists/all/contacts/all?count=1&offset=0&access_token=%s' % access_token) result = connection.getresponse() return result.status
def _sendProwl(prowl_api=None, prowl_priority=None, event=None, message=None, force=False): title = "LazyLibrarian" # suppress notifications if the notifier is disabled but the notify options are checked if not lazylibrarian.CONFIG['USE_PROWL'] and not force: return False if prowl_api is None: prowl_api = lazylibrarian.CONFIG['PROWL_APIKEY'] if prowl_priority is None: prowl_priority = lazylibrarian.CONFIG['PROWL_PRIORITY'] message = message.encode(lazylibrarian.SYS_ENCODING) logger.debug(u"Prowl: title: " + title) logger.debug(u"Prowl: event: " + event) logger.debug(u"Prowl: message: " + message) data = { 'event': event, 'description': message, 'application': title, 'apikey': prowl_api, 'priority': prowl_priority } try: http_handler = HTTPSConnection("api.prowlapp.com") http_handler.request( "POST", "/publicapi/add", headers={'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.info('Prowl notifications sent.') return True elif request_status == 401: logger.info('Prowl auth failed: %s' % response.reason) return False else: logger.info('Prowl notification failed.') return False except Exception as e: logger.warn('Error sending to Prowl: %s' % e) return False
def build_insult(self, user_id): """mattbas.org is an awesome insult generator!""" response_user = self.app_client.api_call("users.info", user=user_id) print(response_user) user_name = response_user["user"]["name"] insult_api_conn = HTTPSConnection("insult.mattbas.org") insult_api_conn.request("GET", "/api/insult.json?who=%s" % user_name) insult_api_response = json.loads(insult_api_conn.getresponse().read()) return insult_api_response["insult"]
def get_best_server(self, servers=None): """Perform a speedtest.net "ping" to determine which speedtest.net server has the lowest latency """ if not servers: if not self.closest: servers = self.get_closest_servers() servers = self.closest results = {} for server in servers: cum = [] url = os.path.dirname(server['url']) urlparts = urlparse('%s/latency.txt' % url) printer('%s %s/latency.txt' % ('GET', url), debug=True) for _ in range(0, 3): try: if urlparts[0] == 'https': h = HTTPSConnection(urlparts[1]) else: h = HTTPConnection(urlparts[1]) headers = {'User-Agent': USER_AGENT} start = timeit.default_timer() h.request("GET", urlparts[2], headers=headers) r = h.getresponse() total = (timeit.default_timer() - start) except HTTP_ERRORS: e = get_exception() printer('%r' % e, debug=True) cum.append(3600) continue text = r.read(9) if int(r.status) == 200 and text == 'test=test'.encode(): cum.append(total) else: cum.append(3600) h.close() avg = round((sum(cum) / 6) * 1000.0, 3) results[avg] = server try: fastest = sorted(results.keys())[0] except IndexError: raise SpeedtestBestServerFailure('Unable to connect to servers to ' 'test latency.') best = results[fastest] best['latency'] = fastest self.results.ping = fastest self.results.server = best self.best.update(best) printer(best, debug=True) return best
def retrieve_apikey(self, providerkey=None, token=None): """ Get an API key from a registration token retrieved in retrieve/token. The user must have approved your request first, or you will get an error response. The parameters are : - providerkey (required) : your provider API key. - token (required): the token returned from retrieve_token. This returns a dictionary such as: {'apikey': u'16b776682332cf11102b67d6db215821f2c233a3', 'code': u'200', 'remaining': u'999', 'resetdate': u'1299535575'} """ h = Https(API_DOMAIN) data = {'apikey': self.apikey} if providerkey is not None: data['providerkey'] = providerkey else: raise Exception("Provider Key is required for retrieving API key") if token is not None: data['token'] = token else: raise Exception("Token is required for retrieving API key.\ Call retrieve_token to request it.") h.request("GET", "/publicapi/retrieve/apikey?" + urlencode(data), headers=self.headers) request = h.getresponse() request_status = request.status if request_status == 200: dom = minidom.parseString(request.read()) code = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('code') remaining = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('remaining') resetdate = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('resetdate') users_api_key = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('retrieve')[0].\ getAttribute('apikey') return dict(apikey=users_api_key, code=code, remaining=remaining, resetdate=resetdate) else: self._relay_error(request_status)
def getAuthToken(username, password): requestUrl = "/udj/auth" conn = HTTPSConnection('www.udjplayer.com:4898') params = urlencode({'username': username, 'password': password}) authRequest = conn.request('POST', requestUrl, params) response = conn.getresponse() data = response.read() response = json.loads(data) return (response["ticket_hash"], response["user_id"])
def get_resp(crn, term): h = HTTPSConnection('selfservice.mypurdue.purdue.edu') h.request( 'GET', '/prod/bzwsrch.p_schedule_detail?crn=' + str(crn) + '&term=' + str(term)) resp = h.getresponse() if resp.status == 200: return resp raise ParserException('Response incorrect, code: %s' % resp.status)
def _sendProwl(self, prowl_api=None, prowl_priority=None, event=None, message=None, force=False): if not sickbeard.USE_PROWL and not force: return False if prowl_api == None: prowl_api = sickbeard.PROWL_API if prowl_priority == None: prowl_priority = sickbeard.PROWL_PRIORITY title = "Sick Beard" logger.log(u"Prowl title: " + title, logger.DEBUG) logger.log(u"Prowl event: " + event, logger.DEBUG) logger.log(u"Prowl message: " + message, logger.DEBUG) logger.log(u"Prowl api: " + prowl_api, logger.DEBUG) logger.log(u"Prowl priority: " + prowl_priority, logger.DEBUG) http_handler = HTTPSConnection("api.prowlapp.com") data = { 'apikey': prowl_api, 'application': title, 'event': event, 'description': message.encode('utf-8'), 'priority': prowl_priority } try: http_handler.request( "POST", "/publicapi/add", headers={'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) except (SSLError, HTTPException): logger.log(u"Prowl notification failed.", logger.ERROR) return False response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.log(u"Prowl notifications sent.", logger.DEBUG) return True elif request_status == 401: logger.log(u"Prowl auth failed: %s" % response.reason, logger.ERROR) return False else: logger.log(u"Prowl notification failed.", logger.ERROR) return False
def _send_prowl(prowl_api=None, prowl_priority=None, event=None, message=None, force=False): if not sickbeard.USE_PROWL and not force: return False if prowl_api is None: prowl_api = sickbeard.PROWL_API if len(prowl_api) == 0: return False if prowl_priority is None: prowl_priority = sickbeard.PROWL_PRIORITY title = sickbeard.PROWL_MESSAGE_TITLE logger.log( u"PROWL: Sending notice with details: title=\"{0!s}\" event=\"{1!s}\", message=\"{2!s}\", priority={3!s}, api={4!s}" .format(title, event, message, prowl_priority, prowl_api), logger.DEBUG) http_handler = HTTPSConnection("api.prowlapp.com") data = { 'apikey': prowl_api, 'application': title, 'event': event, 'description': message.encode('utf-8'), 'priority': prowl_priority } try: http_handler.request( "POST", "/publicapi/add", headers={'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) except (SSLError, HTTPException, socket.error): logger.log(u"Prowl notification failed.", logger.ERROR) return False response = http_handler.getresponse() request_status = response.status if request_status == 200: logger.log(u"Prowl notifications sent.", logger.INFO) return True elif request_status == 401: logger.log(u"Prowl auth failed: {0!s}".format(response.reason), logger.ERROR) return False else: logger.log(u"Prowl notification failed.", logger.ERROR) return False
def dorequest(self, timeout=TIMEOUT, HttpMethod="POST", parsexsams=True): """ Sends the request to the database node and returns a result.Result instance. The request uses 'POST' requests by default. If the request fails or if stated in the parameter 'HttpMethod', 'GET' requests will be performed. The returned result will be parsed by default and the model defined in 'specmodel' will be populated by default (parseexams = True). """ self.xml = None #self.get_xml(self.Source.Requesturl) url = self.baseurl + self.querypath urlobj = urlsplit(url) if urlobj.scheme == 'https': conn = HTTPSConnection(urlobj.netloc, timeout=timeout) else: conn = HTTPConnection(urlobj.netloc, timeout=timeout) conn.putrequest(HttpMethod, urlobj.path + "?" + urlobj.query) conn.endheaders() try: res = conn.getresponse() except socket.timeout: # error handling has to be included self.status = 408 self.reason = "Socket timeout" raise TimeOutError self.status = res.status self.reason = res.reason if not parsexsams: if res.status == 200: result = r.Result() result.Content = res.read() elif res.status == 400 and HttpMethod == 'POST': # Try to use http-method: GET result = self.dorequest(HttpMethod='GET', parsexsams=parsexsams) else: result = None else: if res.status == 200: self.xml = res.read() result = r.Result() result.Xml = self.xml result.populate_model() elif res.status == 400 and HttpMethod == 'POST': # Try to use http-method: GET result = self.dorequest(HttpMethod='GET', parsexsams=parsexsams) else: result = None return result
def getsid(): """Connetti al cpanel per ottenere l'id di sessione""" # La procedura e' necessaria per ottenere i cookie, # che chiameremo PSI e SID # PSI corrisponde al PHPSESSID= , presente nella risposta di /x-login, # mentre SID corrisponde al cookie che viene rilasciato nel body della pagina /godns global sid,psi # Prepara l'header ed effettua una POST a cp.tophost.it/x-login, # fornisci le credenziali e ottieni PHPSESSID= dall'header, # che verra' inserito su "psi" headersauth = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} auth = urllib.urlencode([('user',''+userid),('pass',''+passwd)]) conn = HTTPSConnection('cp.tophost.it') conn.request('POST', '/x-login', auth, headersauth) r=conn.getresponse() psi=r.getheader('Set-Cookie').split(';')[0].replace('PHPSESSID=','') conn.close # Prepara l'header ed effettua una GET a /x-httpsstatus, # necessaria per determinare il cookie "nodo" # che si trovera' nell'header headers_httpstatus = {'Cookie': 'PHPSESSID='+psi+'; logged_cp='+userid} conn = HTTPSConnection('cp.tophost.it') conn.request('GET', '/x-httpsstatus', headers=headers_httpstatus) x_httpsstatus=conn.getresponse() node=x_httpsstatus.getheader('set-cookie').split(';')[0] conn.close() # Prepara l'header ed effettua una GET a /godns, # necessaria per determinare il cookie "sid" # che sara' presente nella pagina come dato hidden headers_godns = {'Cookie': 'PHPSESSID='+psi+'; logged_cp='+userid+'; '+node} conn = HTTPSConnection('cp.tophost.it') conn.request('GET', '/godns', headers=headers_godns) godns=conn.getresponse() page=godns.read() bound='<input type=hidden name=sid value=' s=page.find(bound); e=page.find('>',s) sid=page[s+len(bound):e].replace('"','') conn.close() return sid,psi
def collect_posts(collect_url): """Get posts from url.""" conn = HTTPSConnection("graph.facebook.com") conn.request("GET", collect_url) res = conn.getresponse() if res.status != 200: print "Get postids failed {STATUS}".format(STATUS=res.status) else: return json.load(res)
def make_request(self): u = urlparse(g.authorizenetapi) conn = HTTPSConnection(u.hostname, u.port) conn.request("POST", u.path, self.toXML().encode('utf-8'), {"Content-type": "text/xml"}) res = conn.getresponse() res = self.handle_response(res.read()) conn.close() return res
def then_i_expect_proxying_https_http(step): c = HTTPSConnection('localhost') c.request("GET", "/") response = c.getresponse() data = response.read() clear_nginx_includes() create_api() assert data == world.expected_response, data
def http_request(url, method, data=None, headers=None): scheme, netloc, path, query, fragment = urlsplit(url) if scheme == 'https': conn = HTTPSConnection(netloc) else: conn = HTTPConnection(netloc) conn.request(method, "%s?%s" % (path, query), data, headers=headers) response = conn.getresponse() response.get = response.getheader # NOTE: monkey-patch return response, response.read()
def post(self, application=None, event=None, description=None, priority=0, providerkey=None): """ Post a notification.. You must provide either event or description or both. The parameters are : - application ; The name of your application or the application generating the event. - providerkey (optional) : your provider API key. Only necessary if you have been whitelisted. - priority (optional) : default value of 0 if not provided. An integer value ranging [-2, 2] representing: -2. Very Low -1. Moderate 0. Normal 1. High 2. Emergency (note : emergency priority messages may bypass quiet hours according to the user's settings) - event : the name of the event or subject of the notification. - description : a description of the event, generally terse. """ # Create the http object h = Https(API_DOMAIN) # Perform the request and get the response headers and content data = { 'apikey': self.apikey, 'application': application, 'event': event, 'description': description, 'priority': priority } if providerkey is not None: data['providerkey'] = providerkey h.request("POST", "/publicapi/add", headers=self.headers, body=urlencode(data)) response = h.getresponse() request_status = response.status if request_status == 200: return True elif request_status == 401: raise Exception("Auth Failed: %s" % response.reason) else: raise Exception("Failed")
def _request(self, url, method): scheme, host = urlparse(url)[:2] scheme = scheme.lower() proxies = getproxies_environment() if scheme in proxies: scheme, host = urlparse(proxies[scheme])[:2] scheme = scheme.lower() kwargs = {} if version_info[1] >= 6: kwargs['timeout'] = self.timeout else: socket.setdefaulttimeout(self.timeout) if scheme == "https": conn = HTTPSConnection(host, **kwargs) else: conn = HTTPConnection(host, **kwargs) headers = {} if method == 'GET': headers['Range'] = 'bytes=0-%s' % self.max_size try: try: conn.request(method.upper(), url_to_bytestring(url), headers=headers) response = conn.getresponse() data = response.read(self.max_size) conn.close() except socket.error, e: raise HTTPException(e.message or e.args[1]) finally: if version_info[1] < 6: socket.setdefaulttimeout(None) contenttype = response.getheader('Content-Type', None) if contenttype: match = re.search('^charset=([a-zA-Z0-9-]+)', contenttype) try: if match: data = data.decode(match.group(1)) elif contenttype.startswith('text/'): data = data.decode('utf-8') except UnicodeDecodeError: guessed = detect(data) if guessed['confidence'] > 0.5: charset = guessed['encoding'] # Common guessing mistake: if charset.startswith('ISO-8859') and '\x92' in data: charset = 'windows-1252' data = unicode(data, charset, errors='replace') return response.status, response.reason, data, response.getheaders()
def http_get(self, url): connection = HTTPSConnection(self.__get_random_proxy(), context=_create_unverified_context()) connection.request(method='GET', url=url, headers={'Proxy-Authorization': 'Basic ' + self.get_auth_token()}) response = connection.getresponse() return {'status': response.status, 'reason': response.reason, 'data': response.read()}
def sendMessage(id, msgStr): try: conn = HTTPSConnection(url) conn.request( "GET", bot + "sendMessage?chat_id=" + str(id) + "&text=" + msgStr + "&disable_web_page_preview=true") res = conn.getresponse().read() conn.close() except: print "Msg send fail" return
def _do_request(self, http_method, path, body=None, parameters=None): """ Generic HTTP/S connection method. """ full_path = self._session_base_path + path #If any parameters were given, tack them on to the end of the path. if parameters: full_path += '?' + urlencode(parameters) conn = None response = None try: #TO DO: Rewrite to facilitate connection pooling. if self._secure: conn = HTTPSConnection(self._host) else: conn = HTTPConnection(self._host) try: conn.request(http_method, full_path, body, self._headers) except: raise TembooError( 'An error occurred connecting to the Temboo server. Verify that your Temboo Account Name is correct, and that you have a functioning network connection' ) response = conn.getresponse() body = response.read().decode('utf-8') #Any 200-series response means success. if 200 <= response.status < 300: return json.loads(body) #401 errors are appkeyname/appkey errors if response.status == 401: msg = json.loads(body)['error'] raise TembooCredentialError(msg) #404 errors are "object not found" (or permissions errors) #NOTE: Malformed URIs can result in a 404, too, but the #body text won't be a JSON string. if response.status == 404 and body.startswith("{"): msg = json.loads(body)['error'] raise TembooObjectNotAccessibleError(msg, path) #Any response < 200 or >= 300 means an error. msg = 'Bad HTTP response code. ({0})'.format(response.status) raise TembooHTTPError(msg, response.status, response.reason, body) finally: if conn is not None: conn.close()
def __get_session_json(self): conn = HTTPSConnection(self.host) path = '/session' conn.request('POST', path, self.params, headers=self.headers) response = conn.getresponse() data = response.read() if response.status != 200 and response.status != 201: emsg = 'WeaveRegisterService: Failed with status %d: %s. Password and login correct?' % (response.status, response.reason) self.logger.info(emsg) raise ValueError(emsg) return json.loads(data)
def requestHarvest(day_of_year, year): conn = HTTPSConnection(host) conn.request("GET", "/daily/%d/%d" % (day_of_year, year), None, harvestApiHeaders) raw_response = conn.getresponse() body = raw_response.read().decode('utf-8') conn.close() if raw_response.status > 206: print("Unexpected response %d, %s" % (raw_response.status, body)) exit() return json.loads(body)
def make_request(self, uri=None, proto='HTTP', request_type='GET', headers=None, output_format='raw', return_type=False): valid_request_types = ['GET', 'POST', 'PUT', 'DELETE'] if request_type.upper() not in valid_request_types: logger.debug(u"HTTP request made but unsupported request type given.") return None if uri: if proto.upper() == 'HTTPS': handler = HTTPSConnection(self.host, self.port, timeout=10) else: handler = HTTPConnection(self.host, self.port, timeout=10) if uri.find('?') > 0: token_string = '&X-Plex-Token=' + self.token else: token_string = '?X-Plex-Token=' + self.token try: if headers: handler.request(request_type, uri + token_string, headers=headers) else: handler.request(request_type, uri + token_string) response = handler.getresponse() request_status = response.status request_content = response.read() content_type = response.getheader('content-type') except IOError, e: logger.warn(u"Failed to access uri endpoint %s with error %s" % (uri, e)) return None if request_status == 200: if output_format == 'dict': output = helpers.convert_xml_to_dict(request_content) elif output_format == 'json': output = helpers.convert_xml_to_json(request_content) elif output_format == 'xml': output = helpers.parse_xml(request_content) else: output = request_content if return_type: return output, content_type return output else: logger.warn(u"Failed to access uri endpoint %s. Status code %r" % (uri, request_status)) return []
def get_website_source(add=''): if add == '': raise NameError('Have no website address yet') conn = HTTPSConnection(add) conn.request('GET', '/the-thao-c101.html') r = conn.getresponse() if str(r.status) == '200': return r.read() else: return '' conn.close()
def retrieve_token(self, providerkey=None): """ Get a registration token for use in retrieve/apikey and the associated URL for the user to approve the request. The parameters are : - providerkey (required) : your provider API key. This returns a dictionary such as: {'code': u'0', 'remaining': u'999', 'resetdate': u'1299535575', 'token': u'60fd568423e3cd337b45172be91cabe46b94c200', 'url': u'https://www.prowlapp.com/retrieve.php?token=60fd5684'} """ h = Https(API_DOMAIN) data = {'apikey': self.apikey} if providerkey is not None: data['providerkey'] = providerkey h.request("GET", "/publicapi/retrieve/token?" + urlencode(data), headers=self.headers) request = h.getresponse() request_status = request.status if request_status == 200: dom = minidom.parseString(request.read()) code = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('code') remaining = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('remaining') resetdate = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('success')[0].\ getAttribute('resetdate') token = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('retrieve')[0].\ getAttribute('token') url = dom.getElementsByTagName('prowl')[0].\ getElementsByTagName('retrieve')[0].\ getAttribute('url') return dict(token=token, url=url, code=code, remaining=remaining, resetdate=resetdate) else: self._relay_error(request_status)
def post_multipart(host, selector, fields, files): content_type, body = encode_multipart_formdata(fields, files) h = HTTPSConnection(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body.encode('utf-8')))) h.putheader('User-Agent', 'sms-python') h.endheaders() h.send(body.encode('utf-8')) resp = h.getresponse() return resp.status, resp.reason, resp.read().decode()
def _sendProwl(self, prowl_api=None, prowl_priority=None, event=None, message=None, force=False): if not sickrage.srCore.srConfig.USE_PROWL and not force: return False if prowl_api is None: prowl_api = sickrage.srCore.srConfig.PROWL_API if prowl_priority is None: prowl_priority = sickrage.srCore.srConfig.PROWL_PRIORITY title = "SiCKRAGE" sickrage.srCore.srLogger.debug( "PROWL: Sending notice with details: event=\"%s\", message=\"%s\", priority=%s, api=%s" % (event, message, prowl_priority, prowl_api)) http_handler = HTTPSConnection("api.prowlapp.com") data = { 'apikey': prowl_api, 'application': title, 'event': event, 'description': message.encode('utf-8'), 'priority': prowl_priority } try: http_handler.request( "POST", "/publicapi/add", headers={'Content-type': "application/x-www-form-urlencoded"}, body=urlencode(data)) except (SSLError, HTTPException, socket.error): sickrage.srCore.srLogger.error("Prowl notification failed.") return False response = http_handler.getresponse() request_status = response.status if request_status == 200: sickrage.srCore.srLogger.info("Prowl notifications sent.") return True elif request_status == 401: sickrage.srCore.srLogger.error("Prowl auth failed: %s" % response.reason) return False else: sickrage.srCore.srLogger.error("Prowl notification failed.") return False
def checkPageStatus(host): try: sponge.logger.debug("Trying {}...", host) connection = HTTPSConnection(host) connection.request("GET", "/") response = connection.getresponse() sponge.logger.debug("Host {} status: {}", host, response.status) return str(response.status) except Exception, e: sponge.logger.debug("Host {} error: {}", host, e) return "ERROR"