Пример #1
0
    def __init__(self, api_key=None, api_secret=None, oauth_token=None, \
                oauth_token_secret=None, callback_url='', headers=None):

        self.api_key = api_key and u'%s' % api_key
        self.api_secret = api_secret and u'%s' % api_secret
        self.oauth_token = oauth_token and u'%s' % oauth_token
        self.oauth_token_secret = oauth_token_secret and u'%s' % oauth_token_secret
        self.callback_url = callback_url

        self.request_token_url = 'http://api-public.netflix.com/oauth/request_token'
        self.access_token_url = 'http://api-public.netflix.com/oauth/access_token'
        self.authorize_url = 'https://api-user.netflix.com/oauth/login'

        self.old_api_base = 'http://api.netflix.com/'
        self.api_base = 'http://api-public.netflix.com/'

        default_headers = {'User-agent': 'Python-Netflix v%s' % __version__}
        self.headers = default_headers.update(headers or {})

        self.client = requests.session(headers=self.headers)
        self.auth = None

        if self.api_key is not None and self.api_secret is not None:
            self.auth = OAuth1(self.api_key, self.api_secret,
                               signature_type='auth_header')

        if self.oauth_token is not None and self.oauth_token_secret is not None:
            self.auth = OAuth1(self.api_key, self.api_secret,
                               self.oauth_token, self.oauth_token_secret,
                               signature_type='auth_header')

        if self.auth is not None:
            self.client = requests.session(headers=self.headers, auth=self.auth)
Пример #2
0
def callback():
    # Extract parameters from callback URL
    data = dict(parse_qsl(urlparse(request.url).query))
    resource_owner = data.get(u'oauth_token').decode(u'utf-8')
    verifier = data.get(u'oauth_verifier').decode(u'utf-8')
    token_secret = session["token_secret"]

    # Request the access token
    client = OAuth1(app.config["CLIENT_KEY"],
                    resource_owner_key=resource_owner,
                    resource_owner_secret=token_secret,
                    verifier=verifier,
                    **app.config["OAUTH_CREDENTIALS"])
    r = requests.post(u"http://127.0.0.1:5000/access_token", auth=client)

    # Extract the access token from the response
    data = dict(parse_qsl(r.content))
    resource_owner = data.get(u'oauth_token').decode(u'utf-8')
    resource_owner_secret = data.get(u'oauth_token_secret').decode(u'utf-8')
    client = OAuth1(app.config["CLIENT_KEY"],
                    resource_owner_key=resource_owner,
                    resource_owner_secret=resource_owner_secret,
                    **app.config["OAUTH_CREDENTIALS"])
    r = requests.get(u"http://127.0.0.1:5000/protected", auth=client)
    r = requests.get(u"http://127.0.0.1:5000/protected_realm", auth=client)
    return r.content
Пример #3
0
    def __init__(self, app_key=None, app_secret=None, oauth_token=None, oauth_token_secret=None, \
                headers=None, callback_url=None, twitter_token=None, twitter_secret=None, proxies=None):
        """Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).

            :param app_key: (optional) Your applications key
            :param app_secret: (optional) Your applications secret key
            :param oauth_token: (optional) Used with oauth_token_secret to make authenticated calls
            :param oauth_token_secret: (optional) Used with oauth_token to make authenticated calls
            :param headers: (optional) Custom headers to send along with the request
            :param callback_url: (optional) If set, will overwrite the callback url set in your application
            :param proxies: (optional) A dictionary of proxies, for example {"http":"proxy.example.org:8080", "https":"proxy.example.org:8081"}.
        """

        # Needed for hitting that there API.
        self.api_url = 'https://api.twitter.com/%s'
        self.request_token_url = self.api_url % 'oauth/request_token'
        self.access_token_url = self.api_url % 'oauth/access_token'
        self.authorize_url = self.api_url % 'oauth/authorize'
        self.authenticate_url = self.api_url % 'oauth/authenticate'

        # Enforce unicode on keys and secrets
        self.app_key = app_key and unicode(app_key) or twitter_token and unicode(twitter_token)
        self.app_secret = app_key and unicode(app_secret) or twitter_secret and unicode(twitter_secret)

        self.oauth_token = oauth_token and u'%s' % oauth_token
        self.oauth_token_secret = oauth_token_secret and u'%s' % oauth_token_secret

        self.callback_url = callback_url

        # If there's headers, set them, otherwise be an embarassing parent for their own good.
        self.headers = headers or {'User-Agent': 'Twython v' + __version__}

        # Allow for unauthenticated requests
        self.client = requests.session(proxies=proxies)
        self.auth = None

        if self.app_key is not None and self.app_secret is not None and \
        self.oauth_token is None and self.oauth_token_secret is None:
            self.auth = OAuth1(self.app_key, self.app_secret,
                               signature_type='auth_header')

        if self.app_key is not None and self.app_secret is not None and \
        self.oauth_token is not None and self.oauth_token_secret is not None:
            self.auth = OAuth1(self.app_key, self.app_secret,
                               self.oauth_token, self.oauth_token_secret,
                               signature_type='auth_header')

        if self.auth is not None:
            self.client = requests.session(headers=self.headers, auth=self.auth, proxies=proxies)

        # register available funcs to allow listing name when debugging.
        def setFunc(key):
            return lambda **kwargs: self._constructFunc(key, **kwargs)
        for key in api_table.keys():
            self.__dict__[key] = setFunc(key)

        # create stash for last call intel
        self._last_call = None
Пример #4
0
    def __init__(self, app_key=None, app_secret=None, oauth_token=None, \
                oauth_token_secret=None, headers=None, callback_url=None, \
                pool_maxsize=None):

        # Define some API URLs real quick
        self.base_api_url = 'http://api.tumblr.com'
        self.api_version = 'v2'
        self.api_url = '%s/%s/' % (self.base_api_url, self.api_version)

        # Authentication URLs
        self.request_token_url = 'http://www.tumblr.com/oauth/request_token'
        self.access_token_url = 'https://www.tumblr.com/oauth/access_token'
        self.authorize_url = 'https://www.tumblr.com/oauth/authorize'
        self.authenticate_url = 'https://www.tumblr.com/oauth/authorize'

        self.callback_url = callback_url

        self.default_params = {'api_key': app_key}

        # If there's headers, set them, otherwise be an embarassing parent
        self.headers = headers or {'User-Agent': 'Tumblpy v' + __version__}

        if pool_maxsize:
            requests_config = {'pool_maxsize': pool_maxsize}
        else:
            requests_config = {}

        # Allow for unauthenticated requests
        self.client = requests.session(config=requests_config)
        self.auth = None

        if app_key and app_secret:
            self.app_key = unicode(app_key) or app_key
            self.app_secret = unicode(app_secret) or app_key

        if oauth_token and oauth_token_secret:
            self.oauth_token = unicode(oauth_token)
            self.oauth_token_secret = unicode(oauth_token_secret)

        if app_key and app_secret and not oauth_token and not oauth_token_secret:
            self.auth = OAuth1(self.app_key,
                               self.app_secret,
                               signature_type='auth_header')

        if app_key and app_secret and oauth_token and oauth_token_secret:
            self.auth = OAuth1(self.app_key,
                               self.app_secret,
                               self.oauth_token,
                               self.oauth_token_secret,
                               signature_type='auth_header')

        if self.auth is not None:
            self.client = requests.session(headers=self.headers,
                                           auth=self.auth,
                                           config=requests_config)
Пример #5
0
def register():
    #### Step 1: Obtain a request token
    # We start asking for a request token, which will finally turn into an
    # access token, the one we need to operate on behalf of the user.
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, signature_type='auth_header')
    response = requests.get(REQUEST_TOKEN_URL, auth=auth, verify=False)
    qs = parse_qs(response.text)
    REQUEST_TOKEN = unicode(qs['oauth_token'][0])
    REQUEST_SECRET = unicode(qs['oauth_token_secret'][0])


    #### Step 2: Redirect the user for getting authorization
    # In this step we give the user a link or open a web browser redirecting
    # him to an endpoint, passing the REQUEST_TOKEN we got in the previous step
    # as a url parameter. The user will get a dialog asking for authorization
    # for our application. PyPI will redirect the user back to the URL you
    # provide in CALLBACK_URL.
    import webbrowser
    webbrowser.open("%s?oauth_token=%s&oauth_callback=%s" % (AUTHORIZATION_URL,
        REQUEST_TOKEN, CALLBACK_URL))

    raw_input('[press enter when ready]')


    #### Step 3: Authenticate
    # Once we get user's authorization, we request a final access token, to
    # operate on behalf of the user. We build a new hook using previous request
    # token information achieved at step 1. The request token will have been
    # authorized at step 2.
    # This code is typically invoked in the page called at CALLBACK_URL.
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, REQUEST_TOKEN, REQUEST_SECRET,
        signature_type='auth_header')
    response = requests.get(ACCESS_TOKEN_URL, auth=auth, verify=False)
    response = parse_qs(response.content)
    ACCESS_TOKEN = unicode(response['oauth_token'][0])
    ACCESS_SECRET = unicode(response['oauth_token_secret'][0])
    # The ACCESS_TOKEN and ACCESS_SECRET are the credentials we need to use for
    # handling user's oauth, so most likely you will want to persist them
    # somehow. These are the ones you should use for building a requests
    # session with a new hook. Beware that not all OAuth APIs provide unlimited
    # time credentials.

    print 'ACCESS TOKEN', ACCESS_TOKEN
    print 'ACCESS SECRET', ACCESS_SECRET

    ### Optional Step 4: Access a protected resource
    # Now we have an access token we may access the protected resources on
    # behalf of the user. In this case we access the test URL which will echo
    # back to us the authenticated user and any parameters we pass.
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET,
        signature_type='auth_header')
    response = requests.get(RESOURCE_URL, params={'test': 'spam'}, auth=auth,
        verify=False)
    print response.text
Пример #6
0
    def crawl(self, query):
        client_key = u'arrbro3YTv2A6KPptQQcXg'
        client_secret = u'1WF24ePPs7SN3M0lojOTuMb1yF0W0yhnFPAOQGN0'
        resource_owner_key = u'486242818-qBEzxhfMSUac7ZnQCG69Ww3NfUcGJIZR7bB8yC10'
        resource_owner_secret = u'247XsNb0no7PjjI4ae012SnsPf0c9eeFxd914TunaI'

        queryoauth = OAuth1(client_key,
                            client_secret,
                            resource_owner_key,
                            resource_owner_secret,
                            signature_type='query')

        # build corpus of 40 tweets each from the found users
        page = 1
        f = open('corpus.json', 'w')
        while (page < 2):
            # This will get 20 (the max) users on one page
            url = u'https://api.twitter.com/1/users/search.json?q=' + '%10'.join(
                query) + '&page=' + repr(page) + '&per_page=10'
            r = requests.get(url, auth=queryoauth)

            for user in r.json:
                # print user['screen_name']
                # print user.status
                url = u'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=' + user[
                    'screen_name'] + '&count=40'
                corpus_r = requests.get(url, auth=queryoauth)
                for tweet in corpus_r.json:
                    f.write(str(tweet) + '\n')
            page += 1
        f.close()
Пример #7
0
def release(ACCESS_TOKEN, ACCESS_SECRET, name, version, summary, **optional):
    '''Register a new package, or release of an existing package.

    The "optional" parameters match fields in PEP 345.

    The complete list of parameters are:

    Single value: description, keywords, home_page, author, author_email,
        maintainer, maintainer_email, license, requires_python

    Multiple values: requires, provides, obsoletes, requires_dist,
        provides_dist, obsoletes_dist, requires_external, project_url,
        classifiers.

    For parameters with multiple values, pass them as lists of strings.

    The API will default metadata_version to '1.2' for you. The other valid
    value is '1.0'.

    Two additional metadata fields are available specific to PyPI:

    1. _pypi_hidden: If set to '1' the relase will be hidden from listings and
       searches.
    2. bugtrack_url: This will be displayed on package pages.
    '''
    RESOURCE_URL = 'https://testpypi.python.org/oauth/add_release'
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET,
        signature_type='auth_header')
    params = {u'name': name, u'version': version, u'summary': summary}
    params.update(optional)
    data = flatten_params(params)
    response = requests.post(RESOURCE_URL, data=data, auth=auth,
        verify=False)
    return response.text
Пример #8
0
    def get_twitter_embed(cls, string):
        ids = cls._get_url_id(string, cls.twitter_pattern_search)

        try:
            string = string.decode('utf-8')
        except:
            pass

        for id in ids:
            tweet, created = EmbedCache.objects.get_or_create(
                service="twitter", embed_id=id)

            if tweet.embed_code is None:
                params = dict()
                params = cls.config
                params['id'] = id

                auth = OAuth1(unicode(cls.consumer_key),
                              unicode(cls.consumer_secret),
                              unicode(cls.oauth_token),
                              unicode(cls.oauth_token_secret),
                              signature_type="auth_header")
                r = requests.get(cls.twitter_embed_url,
                                 auth=auth,
                                 params=params)

                if r.status_code == 200:
                    tweet.embed_code = r.json['html']
                    tweet.save()

            string = re.sub(
                r'http[s]?://(%s)%s' % (cls.twitter_pattern_search, id),
                tweet.embed_code, string)

        return mark_safe(string)
Пример #9
0
def upload(ACCESS_TOKEN, ACCESS_SECRET, name, version, content,
        filename, filetype, **optional):
    '''Upload a file for a package release. If the release does not exist then
    it will be registered automatically.

    The name and version identify the package release to upload the file
    against. The content and filetype are specific to the file being uploaded.

    content - an readable file object
    filetype - one of the standard distutils file types ("sdist", "bdist_win",
        etc.)

    There are several optional parameters:

    pyversion - specify the 'N.N' Python version the distribution works with.
        This is not needed for source distributions but required otherwise.
    comment - use if there's multiple files for one distribution type.
    md5_digest - supply the MD5 digest of the file content to verify
        transmission
    gpg_signature - ASCII armored GPG signature for the file content
    protocol_version - defaults to "1" (currently the only valid value)

    Additionally the release parameters are as specified for release() above.
    '''
    RESOURCE_URL = 'https://testpypi.python.org/oauth/upload'
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET,
        signature_type='auth_header')
    params = dict(name=name, version=version, filename=filename,
        filetype=filetype, protocol_version='1')
    params.update(optional)
    data = flatten_params(params)
    files = dict(content=(filename, content))
    response = requests.post(RESOURCE_URL, params=params, files=files,
        auth=auth, verify=False)
    return response.text
Пример #10
0
    def get_request_token(self):
        """
        Get the initial request token from GetGlue.

        Returns a dictionary.
        """
        url = urljoin(API_URL, '/oauth/request_token')
        oauth = OAuth1(settings.CONSUMER_KEY, settings.SECRET_KEY)
        response = requests.get(url, auth=oauth)
        return self._parse_query_string(response.text)
Пример #11
0
def test(ACCESS_TOKEN, ACCESS_SECRET, **params):
    '''Access the test resource passing optional parameters.

    The test resource will echo back the authenticated user and any parameters
    we pass.
    '''
    RESOURCE_URL = 'https://testpypi.python.org/oauth/test'
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET,
        signature_type='auth_header')
    client = SimpleOAuthClient(CONSUMER_KEY, CONSUMER_SECRET, access_token)
    response = requests.get(RESOURCE_URL, params=params, auth=auth,
        verify=False)
    return response.text
Пример #12
0
def start():
    client = OAuth1(app.config["CLIENT_KEY"],
                    callback_uri=u"http://client.local:5001/callback",
                    **app.config["OAUTH_CREDENTIALS"])

    r = requests.post(u"http://127.0.0.1:5000/request_token?realm=secret",
                      auth=client)
    print r.content
    data = dict(parse_qsl(r.content))
    resource_owner = data.get(u'oauth_token')
    session["token_secret"] = data.get('oauth_token_secret').decode(u'utf-8')
    url = u"http://127.0.0.1:5000/authorize?oauth_token=" + resource_owner
    return redirect(url)
Пример #13
0
    def retrieve_access_token(self, request_token):
        """
        Retrieve and set the access token on this client object, given a request
        token.

        After this method has executed, the following attributes are available
        on the client object:
          1. user_id
          2. oauth
        """
        url = urljoin(API_URL, '/oauth/access_token')
        oauth = OAuth1(settings.CONSUMER_KEY, settings.SECRET_KEY,
                       request_token['oauth_token'],
                       request_token['oauth_token_secret'])
        response = requests.get(url, auth=oauth)
        response_dict = self._parse_query_string(response.text)
        self.user_id = response_dict.get('glue_userId', None)
        if self.user_id:
            self.oauth = OAuth1(settings.CONSUMER_KEY, settings.SECRET_KEY,
                                response_dict['oauth_token'],
                                response_dict['oauth_token_secret'])
        else:
            self.oauth = None
Пример #14
0
    def get_twitter_embed_by_id(cls, id, **kwargs):

        tweet, created = EmbedCache.objects.get_or_create(service="twitter",
                                                          embed_id=id)

        if tweet.embed_code is None:
            auth = OAuth1(unicode(cls.consumer_key),
                          unicode(cls.consumer_secret),
                          unicode(cls.oauth_token),
                          unicode(cls.oauth_token_secret),
                          signature_type="auth_header")
            kwargs['id'] = id

            r = requests.get(cls.twitter_embed_url, auth=auth, params=kwargs)

            if r.status_code == 200:
                tweet.embed_code = r.json['html']
                tweet.save()

        return mark_safe(tweet.embed_code)
Пример #15
0
import requests
from requests.auth import OAuth1
from oauthlib.oauth1.rfc5849 import SIGNATURE_RSA

client_key = u'...'

# You need to register your key with the OAuth provider first,
# in this case Google at https://accounts.google.com/ManageDomains
key = open("your_rsa_key.pem").read()

# Request token endpoint for access to Blogger
url = u'https://www.google.com/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.blogger.com%2Ffeeds%2F'

queryoauth = OAuth1(client_key,
                    signature_method=SIGNATURE_RSA,
                    rsa_key=key,
                    signature_type='query')
headeroauth = OAuth1(client_key,
                     signature_method=SIGNATURE_RSA,
                     rsa_key=key,
                     signature_type='auth_header')
bodyoauth = OAuth1(client_key,
                   signature_method=SIGNATURE_RSA,
                   rsa_key=key,
                   signature_type='body')

r_query = requests.get(url, auth=queryoauth)
r_header = requests.get(url, auth=headeroauth)
r_body = requests.post(url, auth=bodyoauth)
Пример #16
0
    def __init__(self, app_key=None, app_secret=None, oauth_token=None, oauth_token_secret=None, \
                headers=None, callback_url=None, twitter_token=None, twitter_secret=None):
        """Instantiates an instance of Twython. Takes optional parameters for authentication and such (see below).

            :param app_key: (optional) Your applications key
            :param app_secret: (optional) Your applications secret key
            :param oauth_token: (optional) Used with oauth_secret to make authenticated calls
            :param oauth_secret: (optional) Used with oauth_token to make authenticated calls
            :param headers: (optional) Custom headers to send along with the request
            :param callback_url: (optional) If set, will overwrite the callback url set in your application
        """

        # Needed for hitting that there API.
        self.api_url = 'https://api.twitter.com/%s'
        self.request_token_url = self.api_url % 'oauth/request_token'
        self.access_token_url = self.api_url % 'oauth/access_token'
        self.authorize_url = self.api_url % 'oauth/authorize'
        self.authenticate_url = self.api_url % 'oauth/authenticate'

        # Enforce unicode on keys and secrets
        self.app_key = None
        if app_key is not None or twitter_token is not None:
            self.app_key = u'%s' % (app_key or twitter_token)

        self.app_secret = None
        if app_secret is not None or twitter_secret is not None:
            self.app_secret = u'%s' % (app_secret or twitter_secret)

        self.oauth_token = None
        if oauth_token is not None:
            self.oauth_token = u'%s' % oauth_token

        self.oauth_secret = None
        if oauth_token_secret is not None:
            self.oauth_secret = u'%s' % oauth_token_secret

        self.callback_url = callback_url

        # If there's headers, set them, otherwise be an embarassing parent for their own good.
        self.headers = headers
        if self.headers is None:
            self.headers = {
                'User-agent': 'Twython Python Twitter Library v' + __version__
            }

        self.client = None
        self.auth = None

        if self.app_key is not None and self.app_secret is not None:
            self.auth = OAuth1(self.app_key,
                               self.app_secret,
                               signature_type='auth_header')

        if self.oauth_token is not None and self.oauth_secret is not None:
            self.auth = OAuth1(self.app_key,
                               self.app_secret,
                               self.oauth_token,
                               self.oauth_secret,
                               signature_type='auth_header')

        if self.client is None:
            # If they don't do authentication, but still want to request
            # unprotected resources, we need an opener.
            self.client = requests.session()

        # register available funcs to allow listing name when debugging.
        def setFunc(key):
            return lambda **kwargs: self._constructFunc(key, **kwargs)

        for key in api_table.keys():
            self.__dict__[key] = setFunc(key)

        # create stash for last call intel
        self._last_call = None
Пример #17
0
import requests
import sys
from requests.auth import OAuth1
import os

# This reads tweets from Twitter's streaming API and writes them to a file.
# See Twitter's documentation here:
# https://dev.twitter.com/docs/api/1/post/statuses/filter
# You will need to change the SCREEN_NAME and PASSWORD below.

client_key = u''
client_secret = u''
resource_owner_key = u''
resource_owner_secret = u''

queryoauth = OAuth1(client_key, client_secret, resource_owner_key, resource_owner_secret, signature_type='query')

# build corpus of 40 tweets each from the found users
page = 1
f = open('test.json', 'w')
while (page < 5):
	# This will get 20 (the max) users on one page
	url = u'https://api.twitter.com/1/users/search.json?q=' + '%20'.join(sys.argv[1:]) + '&page=' + repr(page) + '&per_page=20'

	r = requests.get(url, auth=queryoauth)
	
	for user in r.json:
		# print user['screen_name']
		url = u'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=' + user['screen_name'] + '&count=40'
		corpus_r = requests.get(url, auth=queryoauth)
		for tweet in corpus_r.json:
Пример #18
0
import requests, json, sys, re, enchant, langid
from requests.auth import OAuth1

# import a load of external features, for text display and date handling
from time import strftime
from textwrap import fill
from termcolor import colored
from email.utils import parsedate

#set it up for unicode
reload(sys)
sys.setdefaultencoding("utf-8")

queryoauth = OAuth1(consumer_key,
                    consumer_secret,
                    access_key,
                    access_secret,
                    signature_type='query')

r = requests.post('https://stream.twitter.com/1/statuses/sample.json',
                  auth=queryoauth,
                  prefetch=False)


def highlight_word(tweet, search_term, pattern):
    # turn the date string into a date object that python can handle
    timestamp = parsedate(tweet["created_at"])
    # now format this nicely into HH:MM:SS format
    timetext = strftime("%H:%M:%S", timestamp)
    # colour our tweet's time, user and text
    time_colored = colored(timetext, color="white", attrs=["bold"])
Пример #19
0
import requests
from requests.auth import OAuth1

url = u'https://api.twitter.com/1/account/settings.json'

client_key = u'...'
client_secret = u'...'
resource_owner_key = u'...'
resource_owner_secret = u'...'

queryoauth = OAuth1(client_key,
                    client_secret,
                    resource_owner_key,
                    resource_owner_secret,
                    signature_type='query')
headeroauth = OAuth1(client_key,
                     client_secret,
                     resource_owner_key,
                     resource_owner_secret,
                     signature_type='auth_header')
bodyoauth = OAuth1(client_key,
                   client_secret,
                   resource_owner_key,
                   resource_owner_secret,
                   signature_type='body')

r_query = requests.get(url, auth=queryoauth)
r_header = requests.get(url, auth=headeroauth)
r_body = requests.post(url, auth=bodyoauth)