def __init__(self, server, key=None, secret=None, client_name="", client_type="web", token=None, token_secret=None, save_token=None, secure=False): """ This will initate the pump.io library == required == server = this is the server you're going to connect to (microca.st, pumpity.net, etc...) == optional == key = This is your client key secret = this is the client secret client_name = this is the name of the client client_type = the type of your client (defaults to 'web') token = This is the token if you've already authenticated by oauth before (default None) token_secret = this is your token secret if you've already athenticated before (default None) save_token = this is a callback (func/method) which is called to save token and token_secret when they've been got (default None) secure = Use https or not """ if "@" in server: # it's a web fingerprint! self.nickname, self.server = server.split("@") else: self.server = server self.nickname = None # should be set with <instance>.set_nickname(<nickname>) if secure: self.proto = "https://" else: self.proto = "http://" # oauthy stuff if not (key and secret): # okay we should assume then we're dynamically registrering a client self.consumer = oauth.OAuthConsumer( client_name=client_name, client_type=client_type, server="{proto}{server}{endpoint}".format( proto=self.proto, server=self.server, endpoint=self.URL_CLIENT_REGISTRATION)) else: self.consumer = oauth.OAuthConsumer(key, secret) self.pump = urllib.request.build_opener() if not (token and token_secret): # we need to make a new oauth request self.oauth_request() # this does NOT return access tokens but None else: self.token = token self.token_secret = token_secret self.oauth_token = oauth.OAuthToken(self.token, self.token_secret)
def __init__(self): try: config_file = open('unfollowr.conf') except: Logger().warning( 'Can\'t open config file "unfollowr.conf", exiting') exit() config = ConfigParser.ConfigParser() config.readfp(config_file) # configuring logger try: loglevel = config.get('logger', 'loglevel') if not loglevel in ['debug', 'warning', 'info']: raise Logger().set_loglevel(loglevel) except: pass # configuring credentails self.user = config.get('unfollowr', 'username') self.password = config.get('unfollowr', 'password') self.twitter = BasicAuthTwitterAPI(self.user, self.password) self.oauth_consumer = oauth.OAuthConsumer( config.get('oauth', 'consumer'), config.get('oauth', 'consumer_secret')) if not self.twitter.verify_credentials(): Logger().warning( 'Twitter auth info incorrect. Check your config file!') exit() self.dbstore = DBStore(config.get('mysql', 'host'), config.get('mysql', 'user'), config.get('mysql', 'passwd'), config.get('mysql', 'database')) self.__create_datadirs(['followers', 'oauth', 'stats'])
def handle_lrs_login(self, data): c = Client(request_endpoint=LRS_INITIATE_ENDPOINT, token_endpoint=LRS_ACCESS_TOKEN_ENDPOINT, resource_endpoint=LRS_RESOURCE_ENDPOINT, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, oauth_verifier=data['oauth_verifier']) handler_token = mc.get("token") access_token, access_token_secret = c.fetch_access_token( token=handler_token) access_token = oauth.OAuthToken(access_token, access_token_secret) consumer = oauth.OAuthConsumer(CLIENT_ID, CLIENT_SECRET) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=access_token, http_method='GET', http_url=LRS_RESOURCE_ENDPOINT) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) headers = oauth_request.to_header() headers['X-Experience-API-Version'] = '1.0' response = requests.get(oauth_request.get_normalized_http_url(), headers=headers, verify=False) self.dump_data(response.content)
def __init__(self, consumer_key=None, consumer_secret=None, oauth_token=None, oauth_token_secret=None): # Consumer Key and Secret of the app, used for Basic Auth requests self._consumer_key = consumer_key self._consumer_secret = consumer_secret if self._consumer_key and self._consumer_secret: base64string = base64.b64encode( '%s:%s' % (self._consumer_key, self._consumer_secret)) self._basic_auth_header = "Basic %s" % base64string # token and secret that allow access to users data. Used for oauth requests self._oauth_token = oauth_token self._oauth_token_secret = oauth_token_secret if self._oauth_token and self._oauth_token_secret: self._access_token = oauth.OAuthToken(self._oauth_token, self._oauth_token_secret) else: self._access_token = None self._consumer = oauth.OAuthConsumer(self._consumer_key, self._consumer_secret) self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
def __init__(self, consumer_key, resource_token, resource_secret): resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % ( resource_secret, resource_token, ) self.resource_token = oauth.OAuthToken.from_string(resource_tok_string) self.consumer_token = oauth.OAuthConsumer(consumer_key, "")
def open_request(consumer_key, consumer_secret): """ returns request url and JustinClient object the object will need to obtain access token on first use """ consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) url = "http://%s/oauth/request_token" % JustinApi.addr request = oauth.OAuthRequest.from_consumer_and_token(consumer, None, http_method='GET', http_url=url) request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None) connection = httplib.HTTPConnection(JustinApi.addr) connection.request('GET', request.http_url, headers=request.to_header()) result = connection.getresponse().read() token = oauth.OAuthToken.from_string(result) auth_request = oauth.OAuthRequest.from_token_and_callback( token=token, callback='http://localhost/', http_url='http://%s/oauth/authorize' % JustinApi.addr) return auth_request.to_url(), JustinApi( consumer_key=consumer_key, consumer_secret=consumer_secret, request_token_str=result)
def do_oauth(weibo_type): config = ConfigParser.ConfigParser() config.read('config.ini') #get config server = config.get(weibo_type, 'server') port = config.getint(weibo_type, 'port') request_token_url = config.get(weibo_type, 'request_token_url') authorize_url = config.get(weibo_type, 'authorize_url') access_token_url = config.get(weibo_type, 'access_token_url') app_key = config.get(weibo_type, 'app_key') app_secret = config.get(weibo_type, 'app_secret') callback_url = config.get('common', 'callback_url') #setup client = BaseOAuthClient(server, port, request_token_url, access_token_url, authorize_url) consumer = oauth.OAuthConsumer(app_key, app_secret) signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, callback=callback_url, http_url=client.request_token_url) oauth_request.sign_request(signature_method_hmac_sha1, consumer, None) print 'REQUEST (via headers)' print 'parameters: %s' % str(oauth_request.parameters) token = client.fetch_request_token(oauth_request) print 'GOT' print 'key: %s' % str(token.key) print 'secret: %s' % str(token.secret) print 'callback confirmed? %s' % str(token.callback_confirmed)
def __init__(self, server, port=80, path='', consumer_key='', consumer_secret='', https=False): self.server, self.port = server, port self.path = path self.consumer_key, self.consumer_secret = consumer_key, consumer_secret self.request_token_url = self.REQUEST_TOKEN_URL self.access_token_url = self.ACCESS_TOKEN_URL self.authorization_url = self.AUTHORIZATION_URL if https: self.connection = httplib.HTTPSConnection('%s:%d' % (self.server, self.port)) else: self.connection = httplib.HTTPConnection("%s:%d" % (self.server, self.port)) self.consumer = oauth.OAuthConsumer(self.consumer_key, self.consumer_secret) self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT( ) self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1( )
def on_twitter_auth_clicked(self, widget, data=None): self.winsize = self.window.get_size() web = webkit.WebView() web.get_settings().set_property("enable-plugins", False) web.load_html_string(_("<p>Please wait...</p>"), "file:///") self.consumer = oauth.OAuthConsumer(*resources.get_twitter_keys()) request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_method="POST", callback="http://gwibber.com/0/auth.html", http_url="https://api.twitter.com/oauth/request_token") request.sign_request(sigmeth, self.consumer, token=None) tokendata = urllib2.urlopen(request.http_url, request.to_postdata()).read() self.token = oauth.OAuthToken.from_string(tokendata) url = "http://api.twitter.com/oauth/authorize?oauth_token=" + self.token.key web.load_uri(url) web.set_size_request(550, 400) web.connect("title-changed", self.on_twitter_auth_title_change) self.scroll = gtk.ScrolledWindow() self.scroll.add(web) self.pack_start(self.scroll, True, True, 0) self.show_all() self.ui.get_object("vbox1").hide() self.ui.get_object("vbox_advanced").hide() self.dialog.infobar.set_message_type(gtk.MESSAGE_INFO)
def main(): #build base consumer object with oauth keys and sign using HMAC-SHA1 base_consumer = oauth.OAuthConsumer(common.consumer_key, common.consumer_secret) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() #create and sign request token fetch request object request_rt = oauth.OAuthRequest.from_consumer_and_token( base_consumer, callback=common.callback_url, http_url=common.request_token_endpoint) request_rt.sign_request(signature_method_hmac_sha1, base_consumer, None) #obtain request token token_read = urllib.urlopen(request_rt.to_url()) token_string = token_read.read() #parse request token into individual parameters token_params = cgi.parse_qs(token_string) oauth_token = token_params['oauth_token'][0] oauth_token_secret = token_params['oauth_token_secret'][0] #generate cookie with request token key and secret to pass through authorization process cookie = Cookie.Cookie() cookie_token = 'token=%s&token_secret=%s' % (oauth_token, oauth_token_secret) cookie['request_token'] = cookie_token cookie['timestamp'] = time.time() print cookie #redirect user to authorization endpoint print "Location: %s?oauth_token=%s" % (common.authorize_endpoint, oauth_token)
def _dispatch(self, uri, method, body=None): body = self._validate_verb(method, body) resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % ( self.secret, self.key) resource_token = oauth.OAuthToken.from_string(resource_tok_string) consumer_token = oauth.OAuthConsumer(self.consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=self.maas_url, parameters={'oauth_nonce': uuid.uuid4().get_hex()}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() url = "%s%s" % (self.maas_url, uri) http = httplib2.Http() LOG.debug("Sending request to: %s" % url) response, content = http.request(url, method, body=body, headers=headers) self._check_response(response) body = json.loads(content) return body
def makeClient(self): loaded = False access_token = None try: access_token = pickle.load(open(ACCESS_TOKEN_PATH)) loaded = True except: pass consumer = oauth.OAuthConsumer('anonymous', 'anonymous') client = SpotCloud(self.options._host, consumer, access_token=access_token) if not client.access_token: client.fetch_oauth_request_token() authorization_url = client.get_oauth_authorize_url() print 'Please confirm token on page %s and press Enter' % authorization_url try: raw_input() except KeyboardInterrupt: sys.exit(0) try: client.fetch_oauth_access_token() except KeyError: sys.exit('Unauthorized') access_token = client.access_token if not loaded: pickle.dump(client.access_token, open(ACCESS_TOKEN_PATH, 'w')) return client
def __init__(self, consumer_key=None, consumer_secret=None, access_token=None, username=None, password=None, default_headers=None, client_name='Python'): if (not consumer_key and not consumer_secret) and (not username and not password): raise ValueError( 'Must provide either consumer_key and secret or username and password.' ) if consumer_key and consumer_secret: self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.access_token = access_token self.sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1() else: self.consumer = None self.access_token = None self.sig_method = None self.client_name = client_name self._user_uuid = None self.username = username self.password = password
def __init__(self, client_or_app, engine='httplib'): self.requestTimeout = 0 self.agent = "ZClient/%s" % zclient.__version__ if 'app' in client_or_app: self.app = client_or_app['app'] self.client = client_or_app else: self.app = client_or_app self.client = None self.request_token_url = 'http://%s/oauth/request_token' % self.app[ 'host'] self.authorization_url = 'http://%s/oauth/authorize' % self.app['host'] self.access_token_url = 'http://%s/oauth/access_token' % self.app[ 'host'] self.connection = httplib.HTTPConnection(self.app['host']) #self.signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() if self.app['ckey']: self.consumer = oauth.OAuthConsumer(self.app['ckey'], self.app['csec']) else: # requests without OAuth self.consumer = None self._getPage = getattr(self, '_getPage_%s' % engine)
def yahoo(self, title=None, analyze=True, start='0'): q = title if title is None and request: q = request.args['q'] if start == "0" and request: start = request.args['start'] if request and request.args.get("analyze", {}) == "false": analyze = False URL = "http://yboss.yahooapis.com/ysearch/news" OAUTH_CONSUMER_KEY = "dj0yJmk9RHp0ckM1NnRMUmk1JmQ9WVdrOVdUbHdOMkZLTTJVbWNHbzlNakV5TXpReE1EazJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0xMg--" OAUTH_CONSUMER_SECRET = "626da2d06d0b80dbd90799715961dce4e13b8ba1" pr("here") data = { "q": q, "start": start, "sort": "date", "age": "1000d", "format":"json" } consumer = oauth.OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET) signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=None, http_method='GET', http_url=URL, parameters=data) oauth_request.sign_request(signature_method_hmac_sha1, consumer, "") complete_url = oauth_request.to_url() response = urllib.urlopen(complete_url).read() stories = json.loads(response).get("bossresponse").get("news", {}).get("results") if stories is not None: for story in stories: normalize(story, self.normalizers['yahoo']) if analyze is True: analyzeStory(story) return json.dumps(stories, default=dthandler)
def on_statusnet_auth_clicked(self, widget, data=None): self.winsize = self.window.get_size() web = webkit.WebView() web.get_settings().set_property("enable-plugins", False) web.load_html_string(_("<p>Please wait...</p>"), "file:///") self.consumer = oauth.OAuthConsumer("anonymous", "anonymous") request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_method="POST", callback="http://gwibber.com/0/auth.html", parameters={"source": "Gwibber"}, http_url=self.url_prefix + "/api/oauth/request_token") request.sign_request(sigmeth, self.consumer, token=None) tokendata = urllib2.urlopen(request.http_url, request.to_postdata()).read() self.token = oauth.OAuthToken.from_string(tokendata) url = self.url_prefix + "/api/oauth/authorize?mode=desktop&oauth_token=" + self.token.key web.load_uri(url) #web.set_size_request(500, 420) web.set_size_request(550, 400) web.connect("title-changed", self.on_statusnet_auth_title_change) scroll = gtk.ScrolledWindow() scroll.add(web) self.pack_start(scroll, True, True, 0) self.show_all() self.ui.get_object("vbox1").hide() self.ui.get_object("vbox_advanced").hide()
def _request(self, url, parameters=None, method='GET', force_api_version=None): if not parameters: parameters = None else: parameters = self._filter_params(parameters) signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() consumer = oauth.OAuthConsumer(self.oauth_key, self.oauth_secret) if self.api_server[:3] == "127": protocol = "http://" else: protocol = "https://" if force_api_version: api_version = force_api_version else: api_version = self.api_version url = '%s%s/%s/%s' % (protocol, self.api_server, api_version, url) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_url=url, http_method=method, parameters=parameters) oauth_request.sign_request(signature_method, consumer, None) if method == "GET": url = oauth_request.to_url() f = urllib.urlopen(url) else: url = oauth_request.get_normalized_http_url() f = urllib.urlopen(url, oauth_request.to_postdata()) s = f.read() return s
def _twitter_api(self, path, params, post=False): consumer = oauth.OAuthConsumer( 'BahWsa9ynBogaXxRoJPX5Q', '5bWdyET8iFpFUlpFuFJV02NOILoKEn5u6jt7TwXoXI') token = oauth.OAuthToken( '116458525-eI3WNzzatAm4S7DjYzX5fjOCr1wGyY0NtrOdfOqk', 'H0I2F1cvL8Z421isUW4nARTgEC0nbDBFCmF4lLoE') client = oauth.OAuthClient(consumer, token) url = "http://api.twitter.com/1/%s.json" % path body = urlencode(params) if post: method = 'POST' else: method = 'GET' oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, http_method=method, http_url=url, parameters=params) oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) body = None if post: body = oauth_request.to_postdata() else: url = oauth_request.to_url() handle = urllib2.urlopen(url, body) content = handle.read() return (simplejson.loads(content))
def perform_API_request(site, uri, method, key, secret, consumer_key): resource_tok_string = "oauth_token_secret=%s&oauth_token=%s" % (secret, key) resource_token = oauth.OAuthToken.from_string(resource_tok_string) consumer_token = oauth.OAuthConsumer(consumer_key, "") oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer_token, token=resource_token, http_url=site, parameters={'oauth_nonce': uuid.uuid4().hex}) oauth_request.sign_request(oauth.OAuthSignatureMethod_PLAINTEXT(), consumer_token, resource_token) headers = oauth_request.to_header() url = "%s%s" % (site, uri) http = httplib2.Http() return http.request(url, method, body=None, headers=headers) # API key = '<consumer_key>:<key>:<secret>' # response = perform_API_request( # 'http://192.168.3.51/MAAS/api/2.0', '/nodes/?op=list', 'GET', 'FmLaaNZjXQUf76qC5E', '4bbAQaP9aqhSK7JrrdKLKF5qpLynPHSc', # 'Rm9L8J3cwfmt5WZe9V') # # print(response)
def consumer(): try: return consumer._consumer except AttributeError: consumer._consumer = oauth.OAuthConsumer(TWITTERAUTH_KEY, TWITTERAUTH_SECRET) return consumer._consumer
def __init__(self, consumer_key, consumer_secret, access_type, locale=None): """Initialize a DropboxSession object. Your consumer key and secret are available at https://www.dropbox.com/developers/apps Args: access_type: Either 'dropbox' or 'app_folder'. All path-based operations will occur relative to either the user's Dropbox root directory or your application's app folder. locale: A locale string ('en', 'pt_PT', etc.) [optional] The locale setting will be used to translate any user-facing error messages that the server generates. At this time Dropbox supports 'en', 'es', 'fr', 'de', and 'ja', though we will be supporting more languages in the future. If you send a language the server doesn't support, messages will remain in English. Look for these translated messages in rest.ErrorResponse exceptions as e.user_error_msg. """ assert access_type in [ 'dropbox', 'app_folder' ], "expected access_type of 'dropbox' or 'app_folder'" self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.token = None self.request_token = None self.signature_method = oauth.OAuthSignatureMethod_PLAINTEXT() self.root = 'sandbox' if access_type == 'app_folder' else 'dropbox' self.locale = locale
def __init__(self): """Create the objects we need to connect to an OAuth server""" self.connection = httplib.HTTPConnection(API_SERVER) self.connection.set_debuglevel(100) self.consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET) self.signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT() self.signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
def __init__(self, consumer_key=None, consumer_secret=None, service_key=None, access_token=None): """ An object for interacting with the Twitpic API. The arguments listed below are generally required for most calls. Args: consumer_key: Twitter API Key [optional] consumer_secret: Twitter API Secret [optional] access_token: Authorized access_token in string format. [optional] service_key: Twitpic service key used to interact with the API. [optional] NOTE: The TwitPic OAuth Client does NOT support fetching an access_token. Use your favorite Twitter API Client to retrieve this. """ self.server = self.SERVER self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.service_key = service_key self.format = self.FORMAT if access_token: self.access_token = oauth.OAuthToken.from_string(access_token)
def doRequest(method, params): global config consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY) token = oauth.OAuthToken(config['telldus']['token'], config['telldus']['tokenSecret']) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, http_method='GET', http_url="http://api.telldus.com/json/" + method, parameters=params) oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) headers = oauth_request.to_header() headers['Content-Type'] = 'application/x-www-form-urlencoded' conn = httplib.HTTPConnection("api.telldus.com:80") conn.request('GET', "/json/" + method + "?" + urllib.urlencode(params, True).replace('+', '%20'), headers=headers) response = conn.getresponse() return json.load(response)
def setup_transport(self): self.r_server = redis.Redis(**self.r_config) consumer = oauth.OAuthConsumer(self.consumer_key, self.consumer_secret) token = oauth.OAuthToken(self.access_token, self.access_token_secret) self.twitter = twitter.TwitterFeed(consumer=consumer, token=token) yield self.start_tracking_terms() self.start_checking_for_replies()
def __init__(self, consumer_key, consumer_secret, access_type): assert access_type in ['kuaipan', 'app_folder'] self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.root = access_type self.request_token = None self.token = None
def getAccessToken(): global config consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY) token = oauth.OAuthToken(config['requestToken'], config['requestTokenSecret']) request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, http_method='GET', http_url='http://api.telldus.com/oauth/accessToken') request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) conn = httplib.HTTPConnection('api.telldus.com:80') conn.request(request.http_method, request.to_url(), headers=request.to_header()) resp = conn.getresponse() if resp.status != 200: print 'Error retreiving access token, the server replied:\n%s' % resp.read( ) return token = oauth.OAuthToken.from_string(resp.read()) config['requestToken'] = None config['requestTokenSecret'] = None config['token'] = str(token.key) config['tokenSecret'] = str(token.secret) print 'Authentication successful, you can now use tdtool' saveConfig()
def init(self, SensorPollDelay, TempUnits): self.SUPPORTED_METHODS = self.TELLSTICK_TURNON | self.TELLSTICK_TURNOFF | self.TELLSTICK_DIM self.consumer = oauth.OAuthConsumer(self.PUBLIC_KEY, self.PRIVATE_KEY) self.token = oauth.OAuthToken(self.config['telldus']['token'], self.config['telldus']['tokenSecret']) self.SensorPollDelay = SensorPollDelay self.TempUnits = TempUnits
def __init__(self, consumer_key, consumer_secret, signature_method=None): self.consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) if signature_method == None: signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1() self.signature_method = signature_method self.__opener = urllib2.build_opener() self.__request_token = None
def send_post_request(self, url, parameters): """Sends an OAuth request for a protected resource in the dashboard. Use this when you want to report new data to the dashboard. You must have called the read_required_files method prior to calling this method, since that method will read in the consumer secret and access token we need to make the OAuth request. These concepts are described in the class description. The server is expected to respond with HTTP status 200 and a completely empty response if the call failed. The server may put diagnostic information in the response. Args: url: An absolute url within the dashboard domain, for example http://webrtc-dashboard.appspot.com/add_coverage_data. parameters: A dict which maps from POST parameter names to values. Raises: FailedToReportToDashboard: If the dashboard didn't respond with HTTP 200 to our request or if the response is non-empty. """ consumer = oauth.OAuthConsumer(self.consumer_key_, self.consumer_secret_) access_token = oauth.OAuthToken.from_string(self.access_token_string_) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=access_token, http_method='POST', http_url=url, parameters=parameters) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method_hmac_sha1, consumer, access_token) connection = httplib.HTTPConnection(constants.DASHBOARD_SERVER) headers = {'Content-Type': 'application/x-www-form-urlencoded'} connection.request('POST', url, body=oauth_request.to_postdata(), headers=headers) response = connection.getresponse() connection.close() if response.status != 200: message = ('Failed to report to %s: got response %d (%s)' % (url, response.status, response.reason)) raise FailedToReportToDashboard(message) # The response content should be empty on success, so check that: response_content = response.read() if response_content: message = ('Dashboard reported the following error: %s.' % response_content) raise FailedToReportToDashboard(message)