コード例 #1
0
    def resolveUsers(self, ids, verbose=False):

        try:
            '''
            Returns information Twitter has on users corresponding to
            the queried ids. Max 100 values; additional are truncated.

            '''

            # Load your API keys
            secrets = self.getSecrets(user=True)
            if verbose: print('\nSecrets loaded')

            # Create rauth request
            twitter = OAuth1Service(
                consumer_key=secrets['consumer_key'],
                consumer_secret=secrets['consumer_secret'],
                name='twitter',
                access_token_url='https://api.twitter.com/oauth/access_token',
                authorize_url='https://api.twitter.com/oauth/authorize',
                request_token_url='https://api.twitter.com/oauth/request_token',
                base_url='https://api.twitter.com/1.1/')
            if verbose: print('oAuth service started')

            # Get a session
            session = twitter.get_session(
                (secrets['token_key'], secrets['token_secret']))
            if verbose: print('oAuth session created')

            # Fill out query parameters
            query = ''
            ctr = 0
            for uid in ids:
                query += str(uid) + ','
                ctr += 1
                if ctr == 100: break  # Max 100 queries per request
            if len(query) > 0:
                query = query[0:len(query) - 1]
            params = {'user_id': query, 'include_entities': 'false'}

            # Send the request and return results
            if verbose:
                print('\nSending id:screen_name request...')
                print(
                    'If this takes a long time, be sure to check availability:'
                )
                print('https://dev.twitter.com/overview/status\n')
            TWITTER_URL = 'https://api.twitter.com/1.1/users/lookup.json'
            reply = session.post(TWITTER_URL, data=params)
            data = reply.json()
            phonebook = {}
            for user in data:
                if 'id' in user and user['id'] is not None and str(
                        user['id']) in ids:
                    phonebook[str(user['id'])] = user
                    phonebook[str(user['id'])]['id'] = str(user['id'])

            for uid in ids:
                if uid not in phonebook:
                    phonebook[uid] = {
                        'id': uid,
                        'screen_name': '@???????',
                        'followers_count': 0
                    }

            return phonebook

        except Exception:
            print('Error resolving users.')
            raise
コード例 #2
0
#!/usr/bin/env python

import urlparse
from rauth import OAuth1Service  # pip install rauth

import sys
sys.path.append(
    '../lib/py')  # unnecessary if libZotero is installed separately
from libZotero import zotero

# Get a real consumer key & secret from https://www.zotero.org/oauth/apps
zotauth = OAuth1Service(
    name='zotero',
    consumer_key='<App Consumer Key>',
    consumer_secret='<App Consumer Secret>',
    request_token_url='https://www.zotero.org/oauth/request',
    access_token_url='https://www.zotero.org/oauth/access',
    authorize_url='https://www.zotero.org/oauth/authorize',
    base_url='https://api.zotero.org')

request_token, request_token_secret = zotauth.get_request_token(
    method='GET', params={'oauth_callback': 'oob'})
authorize_url = zotauth.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')

accessTokenResponse = zotauth.get_raw_access_token(
    request_token,
    request_token_secret,
    method='POST',
コード例 #3
0
# Curso BigData & Data Analytics by Handytec
# Fecha: Marzo-2016
# Descripcion: Programa que cosecha tweets de una cuenta de usuario en particular

from rauth import OAuth1Service

# Get a real consumer key & secret from https://dev.twitter.com/apps/new
twitter = OAuth1Service(
    name='twitter',
    consumer_key='7P7tUFiw8opI51SlTt3mVBy2R',
    consumer_secret='fQyFRmvDpFS467zOOApxbPZJfZWXwCncn5LtL6fXEhZxsvy1bl',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1.1/')

request_token, request_token_secret = twitter.get_request_token()

authorize_url = twitter.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
pin = raw_input('Enter PIN from browser: ')

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
                                   data={'oauth_verifier': pin})

params = {
    'screen_name': 'handytec',  # User to pull Tweets from
    'include_rts': 1,  # Include retweets
コード例 #4
0
import os, boto3, joblib
from flask import Flask, redirect, url_for, render_template
from flask import request, session, json, send_from_directory
from rauth import OAuth1Service
from TwitterAPI import TwitterAPI
from sklearn.naive_bayes import MultinomialNB

app = Flask(__name__)
app.config.from_pyfile('w295.config', silent=True)
app.secret_key = app.config['SESSION_KEY']

twitter = OAuth1Service(
    name='twitter',
    consumer_key=app.config['CONSUMER_KEY'],
    consumer_secret=app.config['CONSUMER_SECRET'],
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1.1/')

sqs = boto3.client('sqs',
                   aws_access_key_id=app.config['SQS_TWEETS_ADD_KEY'],
                   aws_secret_access_key=app.config['SQS_TWEETS_ADD_SECRET'],
                   region_name=app.config['SQS_TWEETS_REGION'])

print("Loading CountVectorizer.joblib.pkl...")
cv = joblib.load('CountVectorizer.joblib.pkl')

print("Loading MultinomialNB.joblib.pkl...")
mnb = joblib.load('MultinomialNB.joblib.pkl')
コード例 #5
0
ファイル: app.py プロジェクト: whywrd/notheme
from exceptions.requests import InvalidUsage
from pages import post_pages, info_pages, likes_page
from rauth import OAuth1Service
from utils import url_utils
import urllib.parse
import flask_mobility
from reverse_proxy_wrapper import ReverseProxied

app = flask.Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.config.from_object('config')
flask_mobility.Mobility(app)

oauth_service = OAuth1Service(name='tumblr',
                              consumer_key=app.config[OAuthC.CONSUMER_KEY],
                              consumer_secret=app.config[OAuthC.SECRET_KEY],
                              request_token_url=OAuthC.REQUEST_TOKEN_URL,
                              authorize_url=OAuthC.AUTHORIZE_URL,
                              access_token_url=OAuthC.ACCESS_TOKEN_URL)

# CONSTANTS
POST_LIMIT = 10
BLOG_LIMIT = 10
FOLLOWING_LIMIT = 10
FOLLOWERS_LIMIT = 10
REDIRECT = 'r'

# BEFORE REQUEST


@app.before_request
def set_request_handler():
コード例 #6
0
app = Flask(__name__)
app.secret_key = 'xxxxxxxxxxxxxxxxx'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://xxxxxxxxxxxxxxxxxxx"
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'index'
migrate = Migrate(app, db)
csrf = CSRFProtect(app)

service = OAuth1Service(
    name='twitter',
    consumer_key='xxxxxxxxx',
    consumer_secret='xxxxxxxxx',
    request_token_url='https://api.twitter.com/oauth/request_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    access_token_url='https://api.twitter.com/oauth/access_token',
    base_url='https://api.twitter.com/1.1/'
)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64))
    description = db.Column(db.String(1024))
    user_image_url = db.Column(db.String(1024))
    date_published = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    twitter_id = db.Column(db.String(64), nullable=False, unique=True)
    def __repr__(self):
        return '<User %r>' % self.username
コード例 #7
0
# ログイン用のインスタンスを初期化
login_manager=LoginManager()
login_manager.init_app(app)

# ローカルで動かすPostgreSQLのパスを指定
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://*****:*****@localhost/testdb"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'wj9jr2jg@249j0J4h20JaV91A03f4j2'
db = SQLAlchemy(app)
migrate = Migrate(app,db)
# Oauthの認証をするクライアント
service = OAuth1Service(
    name="twitter",
    consumer_key=API_KEY,
    consumer_secret=API_SECRET_KEY,
    request_token_url='https://api.twitter.com/oauth/request_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    access_token_url='https://api.twitter.com/oauth/access_token',
    base_url='https://api.twitter.com/1.1/'
)
# service = OAuth1Session(API_KEY,API_SECRET_KEY)
# service.fetch_request_token('https://api.twitter.com/oauth/request_token')
# authUrl = twitter.authorization_url('https://api.twitter.com/oauth/authorize')


# ユーザーテーブル
class User(UserMixin,db.Model):
    # ユーザーテーブルの」カラムの設定
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(64),index=True,unique=True)
    description = db.Column(db.String(120),index=True,unique=True)
コード例 #8
0
ファイル: routes.py プロジェクト: ldriveron/MovingPages
    return render_template("index.html", book_id=book_id, book_data=gr_result, movie_data=movie_result,
                           tv_data=tv_result, app_name=app_name, search=search_term, status_msg=status_msg,
                           status_num=status_num, previous_searches=previous_searches)


# OAuth service needs to be here to allow for multiple sessions at once
gr_key = json_functions.read_data("p_k.json")
gr_secret = gr_key["gr_secret"]
gr_key = gr_key["gr"]  # get Goodreads key
CONSUMER_KEY = gr_key
CONSUMER_SECRET = gr_secret
goodreads = OAuth1Service(
    consumer_key=gr_key,
    consumer_secret=gr_secret,
    name='goodreads',
    request_token_url='https://www.goodreads.com/oauth/request_token',
    authorize_url='https://www.goodreads.com/oauth/authorize',
    access_token_url='https://www.goodreads.com/oauth/access_token',
    base_url='https://www.goodreads.com/'
)


@app.route('/gr_result')  # route after authenticating the user on Goodreads (user will go here second)
def gr_result():
    """This function is called after the user is redirected to the 'gr_result' route.

    After the user is authenticated using Goodreads OAuth, the cookies previous set are retrieved and used as
    the current session to the user. Using Goodreads API methods, the users Goodreads ID is retrieved and used
    to search for the users Read books by using the 'get_users_books' method from API_functions import.

    After the books and adaptations list is obtained, it is rendered using the 'gr_result.html' page.
コード例 #9
0
print authorize_token_url
print access_token_url

debug = True

if debug:
    httplib.HTTPConnection.debuglevel = 1
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    requests_log = logging.getLogger("requests.packages.urllib3")
    requests_log.setLevel(logging.DEBUG)
    requests_log.propagate = True

service = OAuth1Service(consumer_key=consumer_key,
                        consumer_secret=consumer_secret,
                        request_token_url=request_token_url,
                        authorize_url=authorize_token_url,
                        access_token_url=access_token_url)

print username

# stage one: get the request token
request_token, request_token_secret = service.get_request_token(
    params={'oauth_callback': 'oob'})

service.get_request_token(params={'oauth_callback': 'oob'})
print 'request_token'
print request_token
print 'request_token_secret'
print request_token_secret
コード例 #10
0
def main(argv):
    try:
        read_input = raw_input
    except NameError:
        read_input = input
    try:
        opts, args = getopt.getopt(argv, "hp:r:t:", ["path=", "run="])
    except getopt.GetoptError:
        print('upload_photos_by_exif3.py -p <path>')
        sys.exit(2)
    if opts == []:
        print('upload_photos_by_exif3.py -p <path>')
        sys.exit()
    elif "-p" != opts[0][0] and opts[0][0] != "-h":
        print('upload_photos_by_exif3.py -p <path>')
        sys.exit()
    elif "-p" != opts[0][0] and opts[0][0] != "-h":
        print('upload_photos_by_exif3.py -p <path>')
        sys.exit()
    else:
        for opt, arg in opts:
            if opt == '-h':
                print("")
                print("Usage:")
                print('    upload_photos_by_exif3.py -p <path> -r <run> ')
                print("-General Options:")
                print("    -h                         Show help.")
                print(
                    "    -p   --path                Full path directory that contains photos"
                )
                print(
                    "    -t   --thread              Set number of thread min = 1, max = 10, default = 4"
                )
                print("-Optional:")
                print(
                    "    -r   --run                 This upload pictures on: http://openstreetcam.com/"
                )
                print(
                    "    -r   --run staging         This upload pictures on: http://staging.openstreetcam.com"
                )
                print(
                    "    -r   --run test            This upload pictures on: http://testing.openstreetcam.com/"
                )
                print("Example: ")
                print(
                    "    python upload_photos_by_exif3.py -p /Users/example/Desktop/Photos/ "
                )
                print(
                    "    python upload_photos_by_exif3.py -p /Users/example/Desktop/Photos/ -t 2"
                )
                print(
                    "    python upload_photos_by_exif3.py -p /Users/example/Desktop/Photos/ -r production"
                )
                print(
                    "    python upload_photos_by_exif3.py -p /Users/example/Desktop/Photos/ -r test"
                )
                print(
                    "    python upload_photos_by_exif3.py -p /Users/example/Desktop/Photos/ -r staging -t 8"
                )

                sys.exit()
            elif opt in ("-p", "--path"):
                run = 'prod'
                path = arg
                max_workers = 4
            elif opt in ("-r", "--run"):
                run = arg
            elif opt in ("-t", "--thread"):
                if int(arg) <= 10 and int(arg) > 0:
                    max_workers = int(arg)
                    print("Threads: " + str(max_workers))
                else:
                    max_workers = 4
                    print("Default threads: 4, maximum threads exceeded")
                    # run = "test"
    if run == "test":
        url_sequence = 'http://testing.openstreetview.com/1.0/sequence/'
        url_photo = 'http://testing.openstreetview.com/1.0/photo/'
        url_finish = 'http://testing.openstreetview.com/1.0/sequence/finished-uploading/'
        url_access = 'http://testing.openstreetview.com/auth/openstreetmap/client_auth'
    elif run == "staging":
        url_sequence = 'http://staging.openstreetview.com/1.0/sequence/'
        url_photo = 'http://staging.openstreetview.com/1.0/photo/'
        url_finish = 'http://staging.openstreetview.com/1.0/sequence/finished-uploading/'
        url_access = 'http://staging.openstreetview.com/auth/openstreetmap/client_auth'
    else:
        url_sequence = 'http://openstreetcam.com/1.0/sequence/'
        url_photo = 'http://openstreetcam.com/1.0/photo/'
        url_finish = 'http://openstreetcam.com/1.0/sequence/finished-uploading/'
        url_access = 'http://openstreetcam.com/auth/openstreetmap/client_auth'
    global PATH
    PATH = path
    try:
        token_file = open("access_token.txt", "r+")
        string = token_file.read()
        access_token = string
    except Exception as ex:
        osm = OAuth1Service(
            name='openstreetmap',
            consumer_key='rBWV8Eaottv44tXfdLofdNvVemHOL62Lsutpb9tw',
            consumer_secret='rpmeZIp49sEjjcz91X9dsY0vD1PpEduixuPy8T6S',
            request_token_url=
            'http://www.openstreetmap.org/oauth/request_token',
            access_token_url='http://www.openstreetmap.org/oauth/access_token',
            authorize_url='http://www.openstreetmap.org/oauth/authorize',
            signature_obj='',
            base_url='http://www.openstreetmap.org/')

        request_token, request_token_secret = osm.get_request_token()
        authorize_url = osm.get_authorize_url(request_token)
        print("")
        print('For login go to this URL in your browser:')
        print(authorize_url)
        print((read_input("Login and  grant acces then press ENTER")))
        cj = http.cookiejar.CookieJar()
        cookies = [{
            "name": "",
            "value": "",
            "domain": "domain",
            "path": "path",
            "secure": "secure",
        }]
        for cookie in cookies:
            c = http.cookiejar.Cookie(version=1,
                                      name=cookie["name"],
                                      value=cookie["value"],
                                      port=None,
                                      port_specified=False,
                                      domain=cookie["domain"],
                                      domain_specified=False,
                                      domain_initial_dot=False,
                                      path=cookie["path"],
                                      path_specified=True,
                                      secure=cookie["secure"],
                                      expires=None,
                                      discard=True,
                                      comment=None,
                                      comment_url=None,
                                      rest={'HttpOnly': None},
                                      rfc2109=False)
            cj.set_cookie(c)
        opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(cj))
        try:
            opener.open(urllib.request.Request(authorize_url))
        except urllib.error.HTTPError as e:
            print("Can't get osm id")
            print(
                "Please retry and report this issue with the error code on https://github.com/openstreetcam/uploader"
            )
            print(e.code)
            print(e.read())
            print(e)
            sys.exit()
        pin = cj._cookies['www.openstreetmap.org']['/']['_osm_session'].value

        try:
            request_token_access, request_token_secret_access = osm.get_access_token(
                request_token,
                request_token_secret,
                method='POST',
                data={'oauth_verifier': pin})
            data_access = {
                'request_token': request_token_access,
                'secret_token': request_token_secret_access
            }
            resp_access = requests.post(url=url_access, data=data_access)
            access_token = resp_access.json()['osv']['access_token']
            token_file = open("access_token.txt", "w+")
            token_file.write(access_token)
            token_file.close()
        except Exception as ex:
            print(ex)
            print("ERROR LOGIN no GRANT ACCES")
            sys.exit()

    local_dirs = os.listdir()
    if str(path).replace('/', '') in local_dirs:
        path = os.getcwd() + '/' + path
    if os.path.basename(path) != "":
        path += "/"

    old_dir = os.getcwd()
    os.chdir(path)
    photos_path = sorted(os.listdir(path), key=os.path.getmtime)
    os.chdir(old_dir)
    time_stamp_list = []
    exist_timestamp = True
    for photo_path in [p for p in photos_path]:
        if ('jpg' in photo_path.lower() or 'jpeg'
                in photo_path.lower()) and "thumb" not in photo_path.lower():
            try:
                time_stamp_list.append({
                    "file":
                    photo_path,
                    "timestamp":
                    get_exif(path + photo_path).values
                })
            except:
                exist_timestamp = False
                photos_path = sorted(os.listdir(path), key=itemgetter(1, 2))
    if exist_timestamp:
        time_stamp_list = sorted(time_stamp_list, key=itemgetter('timestamp'))
        photos_path = []
        for element in time_stamp_list:
            photos_path.append(element['file'])
    for photo_path in [p for p in photos_path]:
        if ('jpg' in photo_path.lower() or 'jpeg'
                in photo_path.lower()) and "thumb" not in photo_path.lower():
            try:
                latitude, longitude, compas = get_gps_lat_long_compass(
                    path + photo_path)
            except Exception:
                try:
                    tags = exifread.process_file(open(path + photo_path, 'rb'))
                    latitude, longitude = get_exif_location(tags)
                    if latitude is None and longitude is None:
                        latitude, longitude, compas = get_data_from_json(
                            path, photo_path)
                except Exception as ex:
                    print(ex)
                    continue
            data_sequence = {
                'uploadSource': 'Python',
                'access_token': access_token,
                'currentCoordinate': str(latitude) + ',' + str(longitude)
            }
            if latitude is not None and longitude is not None:
                break
    try:
        with open(path + "sequence_file.txt", "r+") as sequence_file:
            id_sequence = sequence_file.read()
            sequence_file.close()
    except Exception as ex:
        with open(path + "sequence_file.txt", "w+") as sequence_file:
            if latitude is None and longitude is None:
                print("Error. There is no latitude and longitude in images.")
                sys.exit()
            h = requests.post(url_sequence, data=data_sequence)
            try:
                id_sequence = h.json()['osv']['sequence']['id']
            except Exception as ex:
                print("Fail code:" + str(ex))
                print("Fail to create the sequence")
                os.remove(path + "sequence_file.txt")
                print("Please restart the script")
                sys.exit()
            sequence_file.write(id_sequence)
            sequence_file.close()
    try:
        photos_path.remove("sequence_file.txt")
    except Exception as ex:
        print("No sequence file existing")
    count_list = []
    try:
        count_file = open(path + "count_file.txt", "r")
        lines = count_file.readlines()
        for line in lines:
            count_list.append(int(line.replace('\n', '').replace('\r', '')))
            count = int(line.replace('\n', '').replace('\r', ''))
    except:
        count = 0
    nr_photos_upload = 0
    for photo_path in [p for p in photos_path]:
        if ('jpg' in photo_path.lower() or 'jpeg'
                in photo_path.lower()) and "thumb" not in photo_path.lower():
            nr_photos_upload += 1
    print("Found " + str(nr_photos_upload) + " pictures to upload")
    local_count = 0
    list_to_upload = []
    int_start = 0
    count_uploaded = count
    global COUNT_TO_WRITE
    COUNT_TO_WRITE = count
    global START_TIME
    START_TIME = time.time()

    for index in range(int_start, len([p for p in photos_path])):
        photo_to_upload = photos_path[index]
        local_count += 1
        if ('jpg' in photo_to_upload.lower() or 'jpeg' in photo_to_upload.lower()) and \
                        "thumb" not in photo_to_upload.lower() and local_count not in count_list:
            total_img = nr_photos_upload
            photo_name = os.path.basename(photo_to_upload)
            try:
                photo = {
                    'photo': (photo_name, open(path + photo_to_upload,
                                               'rb'), 'image/jpeg')
                }
                try:
                    latitude, longitude, compas = get_gps_lat_long_compass(
                        path + photo_to_upload)
                except Exception:
                    try:
                        tags = exifread.process_file(
                            open(path + photo_to_upload, 'rb'))
                        latitude, longitude = get_exif_location(tags)
                        compas = -1
                        if latitude is None and longitude is None:
                            latitude, longitude, compas = get_data_from_json(
                                path, photo_path)
                    except Exception:
                        continue
                if compas == -1:
                    # TODO: add 'acces_token': acces_token,
                    data_photo = {
                        'access_token': access_token,
                        'coordinate': str(latitude) + "," + str(longitude),
                        'sequenceId': id_sequence,
                        'sequenceIndex': count
                    }
                else:
                    data_photo = {
                        'access_token': access_token,
                        'coordinate': str(latitude) + "," + str(longitude),
                        'sequenceId': id_sequence,
                        'sequenceIndex': count,
                        'headers': compas
                    }
                info_to_upload = {
                    'data': data_photo,
                    'photo': photo,
                    'name': photo_to_upload
                }
                list_to_upload.append(info_to_upload)
                if count != local_count:
                    count += 1
            except Exception as ex:
                print(ex)
        if (index % 100 == 0 and index != 0) and local_count not in count_list:
            count_uploaded = thread(max_workers, url_photo, list_to_upload,
                                    path, count_uploaded, total_img)
            list_to_upload = []
    if (index % 100 != 0) or index == 0:
        count_uploaded = thread(max_workers, url_photo, list_to_upload, path,
                                count_uploaded, nr_photos_upload)

    data_finish = {'access_token': access_token, 'sequenceId': id_sequence}
    f = requests.post(url_finish, data=data_finish)
    if f.json()['status']['apiCode'] == '600':
        print(("Finish uploading from dir: " + path + " with sequence id: " +
               str(id_sequence)))
    else:
        print(("FAIL uploading from dir: " + path))
        print("Error: ")
        print(f.json())
コード例 #11
0
#
#  Find friends with the most similar interests as you
#

from rauth import OAuth1Service, OAuth1Session

# Enter consumer key and consumer secret
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

goodreads = OAuth1Service(
    consumer_key=CONSUMER_KEY,
    consumer_secret=CONSUMER_SECRET,
    name='goodreads',
    request_token_url='http://www.goodreads.com/oauth/request_token',
    authorize_url='http://www.goodreads.com/oauth/authorize',
    access_token_url='http://www.goodreads.com/oauth/access_token',
    base_url='http://www.goodreads.com/')

# Get request token and authorize url
request_token, request_token_secret = goodreads.get_request_token(
    header_auth=True)
authorize_url = goodreads.get_authorize_url(request_token)

print 'Visit this URL in your browser: ' + authorize_url
accepted = 'n'

while accepted.lower() == 'n':
    accepted = raw_input('Have you authorized me? (y/n)')

# Add book to shelf
コード例 #12
0
ファイル: app.py プロジェクト: canisterism/FlaskApp01
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.secret_key = 'wj9jr2jg@249j0J4h20JaV91A03f4j2'
app.config["SQLALCHEMY_TRACK_MODIFICATION"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost/flasknote"
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'index'
migrate = Migrate(app, db)
csrf = CSRFProtect(app)

service = OAuth1Service(
    name="twitter",
    consumer_key="ioqBwQoKyDeeT5Va2uZH3Fo8a",
    consumer_secret="uEiXFyLmkXGU9r5MAWWHUG50UaTQlcljxta1GUWHYIB5KJFH6Q",
    request_token_url='https://api.twitter.com/oauth/request_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    access_token_url='https://api.twitter.com/oauth/access_token',
    base_url='https://api.twitter.com/1.1/')


class User(UserMixin, db.Model):
    __tablename__ = "appdb01"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(64), index=True, unique=True)
    description = db.Column(db.String(120), index=True, unique=True)
    user_image_url = db.Column(db.String(120), index=True, unique=True)
    date_published = db.Column(db.DateTime, nullable=False, unique=True)
    twitter_id = db.Column(db.String(64), nullable=False, unique=True)

    def __repr__(self):
コード例 #13
0
# ---------------- Setup ------------------

class GracenoteError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

p = pyaudio.PyAudio()

# ---------------- Discogs ----------------

discogs = OAuth1Service(
    name="discogs",
    consumer_key=config["DISCOGS_CONSUMER_KEY"],
    consumer_secret=config["DISCOGS_CONSUMER_SECRET"],
    request_token_url=config["DISCOGS_REQUEST_TOKEN_URL"],
    access_token_url=config["DISCOGS_ACCESS_TOKEN_URL"],
    authorize_url=config["DISCOGS_AUTHORIZE_URL"],
    base_url=config["DISCOGS_BASE_URL"])

def discogs_get_master(artist_name, album_name):
    # TODO: sometimes comes up with nothing when it should find something
    payload = {
        "key": config["DISCOGS_KEY"],
        "secret": config["DISCOGS_SECRET"],
        "artist": artist_name,
        "release_title": album_name,
        "type": "master"
    }
    r = requests.get("https://api.discogs.com/database/search", params=payload)
    result = r.json()["results"]
from pathlib import Path
from dotenv import load_dotenv
import os
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

# Autenticação com a API
try:
    read_input = raw_input
except NameError:
    read_input = input

twitter = OAuth1Service(
    name='twitter',
    consumer_key=os.getenv("consumer_key"),
    consumer_secret=os.getenv('consumer_secret'),
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1.1/')

request_token, request_token_secret = twitter.get_request_token()

authorize_url = twitter.get_authorize_url(request_token)

print("Cole link: {url}".format(url=authorize_url))

pin = read_input('Digite o PIN')

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
コード例 #15
0
from datetime import datetime
from rauth import OAuth1Service

app = Flask(__name__)
app.secret_key = 'wj9jr2jg@249j0J4h20JaV91A03f4j2'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://localhost/hostdb"
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'index'
migrate = Migrate(app, db)

service = OAuth1Service(
    name='twitter',
    consumer_key='5bdOd32t4jg09jrhq390j0',
    consumer_secret='DmNMyf42j9jh530qjhb90pmpo4jx48IbIPhbZ',
    request_token_url='https://api.twitter.com/oauth/request_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    access_token_url='https://api.twitter.com/oauth/access_token',
    base_url='https://api.twitter.com/1.1/')


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64))
    description = db.Column(db.String(1024))
    user_image_url = db.Column(db.String(1024))
    date_published = db.Column(db.DateTime,
                               nullable=False,
                               default=datetime.utcnow)
    twitter_id = db.Column(db.String(64), nullable=False, unique=True)
コード例 #16
0
ファイル: oauth.py プロジェクト: sim6/osmose-frontend
################################################################################

oauth_client_key = "zGtBQ4zQfaWqy0G3HtRua2d00gvIcSfS4iHHwH2s"
oauth_client_secret = "2KOQG8eUVvcHcTGV5I12XsseRuaeBW0vcmRTTuli"
oauth_server = "http://www.openstreetmap.org/oauth/"

################################################################################

oauth_request_token = oauth_server + "request_token"
oauth_access_token = oauth_server + "access_token"
oauth_authorize = oauth_server + "authorize"

oauth = OAuth1Service(consumer_key=oauth_client_key,
                      consumer_secret=oauth_client_secret,
                      request_token_url=oauth_request_token,
                      access_token_url=oauth_access_token,
                      authorize_url=oauth_authorize)


def fetch_request_token():
    request_token, request_token_secret = oauth.get_request_token()
    authorize_url = oauth.get_authorize_url(request_token)
    return (authorize_url, (request_token, request_token_secret))


def fetch_access_token(oauth_tokens, request):
    session = oauth.get_auth_session(oauth_tokens[0],
                                     oauth_tokens[1],
                                     method='POST')
    return (session.access_token, session.access_token_secret)
コード例 #17
0
# In[ ]:

import json
import time
from rauth import OAuth1Service
from auth import TwitterAuth
import os
import urllib.parse
import os
from datetime import datetime
from datetime import timedelta

twitter = OAuth1Service(
    consumer_key=TwitterAuth.consumer_key,
    consumer_secret=TwitterAuth.consumer_secret,
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1.1/')
session = twitter.get_session(
    token=[TwitterAuth.access_token, TwitterAuth.access_token_secret])

# In[ ]:

outputDir = "output_streaming_sum_Tweets_48_hours"
try:
    os.mkdir(outputDir)
except OSError as error:
    if error.errno == 17:
        pass
    else:
コード例 #18
0
ファイル: gklst.py プロジェクト: abhisinghal/Geeklist_console
try:
    read_input = raw_input
except NameError:
    read_input = input




#Initializing variables - These are the default entries for Geeklist Console App
CONSUMER_KEY='B_9C1WM-hC-JcVTVOUwyOwXB0PA'
CONSUMER_SECRET='RLEw2jBmlceHb02GobOnI-wtiyukg-in6lEgQIxMttI'
ACCESS_TOKEN_FILE = os.path.join(os.path.dirname(__file__), '.gklst_access_token')
Geeklist = OAuth1Service(
	    name='Geeklist',
	    consumer_key=CONSUMER_KEY,
	    consumer_secret=CONSUMER_SECRET,
	    request_token_url='http://api.geekli.st/v1/oauth/request_token',
	    access_token_url='http://api.geekli.st/v1/oauth/access_token',
	    authorize_url='https://geekli.st/oauth/authorize',
	    base_url='http://api.geekli.st/v1/')



INTRODUCTION = '''
**************************************************************************************************************
*                                           Please use the following commands:
*
* help() - Display help message.
* auth(Geeklist) - Authenticate with Geekli.st. 
* logout() - Expire the access token in case of any authentication or bad request error.
* userdetails() - Fetches your name and email address.
* getCards() - Fetches profile information of another geek.
コード例 #19
0
from rauth import OAuth1Service

twitter = OAuth1Service(
    name='twitter',
    consumer_key='Z9XGQMZuFNot3oXMu6nqTNurN',
    consumer_secret='xdFmRj6RRDl4Kwx1bXP4Ab3xTsuICvKUqPHy5vKYnamFGXQWxm',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    base_url='https://api.twitter.com/1.1/')

request_token, request_token_secret = twitter.get_request_token()

authorize_url = twitter.get_authorize_url(request_token)
コード例 #20
0
def getResultsFromHattrick():
    access_token_key = request.args.get('access_token_key')
    access_token_secret = request.args.get('access_token_secret')
    consumer_key = settings.consumer_key
    consumer_secret = settings.consumer_secret
    chpp = OAuth1Service(
        consumer_key=consumer_key,
        consumer_secret=consumer_secret,
        request_token_url='https://chpp.hattrick.org/oauth/request_token.ashx',
        access_token_url='https://chpp.hattrick.org/oauth/access_token.ashx',
        authorize_url='https://chpp.hattrick.org/oauth/authorize.aspx',
        base_url='http://chpp.hattrick.org/chppxml.ashx',
        signature_obj=HmacSha1Signature)

    session = OAuth1Session(consumer_key,
                            consumer_secret,
                            access_token=access_token_key,
                            access_token_secret=access_token_secret)
    #print access_token_key
    #print access_token_secret
    #The way we choose doesn't know about base_url, add the url
    r = session.get('http://chpp.hattrick.org/chppxml.ashx',
                    params={
                        'file': 'leaguefixtures',
                        'version': '1.2'
                    })

    xmldict = xmltodict.parse(r.text)
    jsonfile = json.loads(json.dumps(xmldict))
    logging.debug(jsonfile)
    for i in jsonfile['HattrickData']['Match']:

        if 'HomeGoals' in i:
            result = i['HomeGoals'] + "-" + i['AwayGoals']
            putResult(i['MatchID'], result)
        elif isMatchPlayed(i['MatchID']):

            resp = session.get('http://chpp.hattrick.org/chppxml.ashx',
                               params={
                                   'file': 'live',
                                   'matchID': i['MatchID'],
                                   'version': '1.8'
                               })
            #print resp.text
            xmldictmatch = xmltodict.parse(resp.text)
            jsonfilematch = json.loads(json.dumps(xmldictmatch))
            #print i['MatchID']

            #print jsonfilematch['HattrickData']['MatchList']['Match']

            for match in jsonfilematch['HattrickData']['MatchList']['Match']:
                if match['MatchID'] == i['MatchID']:

                    homegoals = jsonfilematch['HattrickData']['MatchList'][
                        'Match'][0]['HomeGoals']
                    awaygoals = jsonfilematch['HattrickData']['MatchList'][
                        'Match'][0]['AwayGoals']
                    #print jsonfilematch
                    #print homegoals
                    #print awaygoals
                    result = homegoals + "-" + awaygoals
                    putResult(i['MatchID'], result)

    return Response("Matches collected from Hattrick", status=200)
コード例 #21
0
from datetime import datetime
from rauth import OAuth1Service

app = Flask(__name__)
app.secret_key = 'wj9jr2jg@249j0J4h20JaV91A03f4j2'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://localhost/hotdb"
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'index'
migrate = Migrate(app, db)

service = OAuth1Service(
    name='twitter',
    consumer_key='5bd42rjh9q3j50j09j0e',
    consumer_secret='DmNMy3j5hqhq59hj90q4thtohmtobIPhbZ',
    request_token_url='https://api.twitter.com/oauth/request_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    access_token_url='https://api.twitter.com/oauth/access_token',
    base_url='https://api.twitter.com/1.1/')


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    description = db.Column(db.String(1024), index=True, unique=True)
    user_image_url = db.Column(db.String(1024), index=True, unique=True)
    date_published = db.Column(db.DateTime,
                               nullable=False,
                               default=datetime.utcnow)
    twitter_id = db.Column(db.String(64), nullable=False, unique=True)
コード例 #22
0
ファイル: main.py プロジェクト: mccoydj1/OptionsPricer
# logger settings
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler("python_client.log",
                              maxBytes=5 * 1024 * 1024,
                              backupCount=3)
FORMAT = "%(asctime)-15s %(message)s"
fmt = logging.Formatter(FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')
handler.setFormatter(fmt)
logger.addHandler(handler)
"""Allows user authorization for the sample application with OAuth 1"""
etrade = OAuth1Service(
    name="etrade",
    consumer_key=config["DEFAULT"]["CONSUMER_KEY"],
    consumer_secret=config["DEFAULT"]["CONSUMER_SECRET"],
    request_token_url="https://api.etrade.com/oauth/request_token",
    access_token_url="https://api.etrade.com/oauth/access_token",
    authorize_url="https://us.etrade.com/e/t/etws/authorize?key={}&token={}",
    base_url="https://api.etrade.com")

base_url = config["DEFAULT"]["SANDBOX_BASE_URL"]
#base_url = config["DEFAULT"]["PROD_BASE_URL"]

# Step 1: Get OAuth 1 request token and secret
request_token, request_token_secret = etrade.get_request_token(
    params={
        "oauth_callback": "oob",
        "format": "json"
    })

# Step 2: Go through the authentication flow. Login to E*TRADE.
コード例 #23
0
def main(argv):
    try:
        read_input = raw_input
    except NameError:
        read_input = input
    try:
        opts, args = getopt.getopt(argv, "hp:r:", ["path=", "run="])
    except getopt.GetoptError:
        print('upload_photos.py -p <path>')
        sys.exit(2)
    if opts == []:
        print('upload_photos.py -p <path>')
        sys.exit()
    elif "-p" != opts[0][0] and opts[0][0] != "-h":
        print('upload_photos.py -p <path>')
        sys.exit()

    else:
        for opt, arg in opts:
            if opt == '-h':
                print("")
                print("Usage:")
                print('    upload_photos.py -p <path> -r <run> ')
                print("-General Options:")
                print("    -h                         Show help.")
                print(
                    "    -p   --path                Full path to main directory that contains the track directories"
                )
                print("-Optional:")
                print(
                    "    -r   --run                 This upload pictures on: http://openstreetview.com/"
                )
                print(
                    "    -r   --run staging         This upload pictures on: http://staging.open-street-view.skobbler.net"
                )
                print(
                    "    -r   --run test            This upload pictures on: http://tst.open-street-view.skobbler.net/"
                )
                print("Example: ")
                print(
                    "    python upload_photos.py -p /Users/example/Desktop/Photos/ "
                )
                print(
                    "    python upload_photos.py -p /Users/example/Desktop/Photos/ -r production"
                )
                print(
                    "    python upload_photos.py -p /Users/example/Desktop/Photos/ -r test"
                )
                print(
                    "    python upload_photos.py -p /Users/example/Desktop/Photos/ -r staging"
                )

                sys.exit()
            elif opt in ("-p", "--path"):
                run = 'prod'
                path = arg
            elif opt in ("-r", "--run"):
                run = arg

    if run == "test":
        url_sequence = 'http://testing.openstreetview.com/1.0/sequence/'
        url_photo = 'http://testing.openstreetview.com/1.0/photo/'
        url_finish = 'http://testing.openstreetview.com/1.0/sequence/finished-uploading/'
        url_access = 'http://testing.openstreetview.com/auth/openstreetmap/client_auth'
    elif run == "staging":
        url_sequence = 'http://staging.openstreetview.com/1.0/sequence/'
        url_photo = 'http://staging.openstreetview.com/1.0/photo/'
        url_finish = 'http://staging.openstreetview.com/1.0/sequence/finished-uploading/'
        url_access = 'http://staging.openstreetview.com/auth/openstreetmap/client_auth'
    else:
        url_sequence = 'http://openstreetview.com/1.0/sequence/'
        url_photo = 'http://openstreetview.com/1.0/photo/'
        url_finish = 'http://openstreetview.com/1.0/sequence/finished-uploading/'
        url_access = 'http://openstreetview.com/auth/openstreetmap/client_auth'

    try:
        token_file = open("access_token.txt", "r+")
        string = token_file.read()
        access_token = string
    except Exception as ex:
        osm = OAuth1Service(
            name='openstreetmap',
            consumer_key='rBWV8Eaottv44tXfdLofdNvVemHOL62Lsutpb9tw',
            consumer_secret='rpmeZIp49sEjjcz91X9dsY0vD1PpEduixuPy8T6S',
            request_token_url=
            'http://www.openstreetmap.org/oauth/request_token',
            access_token_url='http://www.openstreetmap.org/oauth/access_token',
            authorize_url='http://www.openstreetmap.org/oauth/authorize',
            signature_obj='',
            base_url='http://www.openstreetmap.org/')

        request_token, request_token_secret = osm.get_request_token()
        authorize_url = osm.get_authorize_url(request_token)
        print("")
        print('For login go to this URL in your browser:')
        print(authorize_url)
        print((read_input("Login and  grant acces then press ENTER")))
        cj = cookielib.CookieJar()
        cookies = [{
            "name": "",
            "value": "",
            "domain": "domain",
            "path": "path",
            "secure": "secure",
        }]
        for cookie in cookies:
            c = cookielib.Cookie(version=1,
                                 name=cookie["name"],
                                 value=cookie["value"],
                                 port=None,
                                 port_specified=False,
                                 domain=cookie["domain"],
                                 domain_specified=False,
                                 domain_initial_dot=False,
                                 path=cookie["path"],
                                 path_specified=True,
                                 secure=cookie["secure"],
                                 expires=None,
                                 discard=True,
                                 comment=None,
                                 comment_url=None,
                                 rest={'HttpOnly': None},
                                 rfc2109=False)
            cj.set_cookie(c)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        ceva = opener.open(urllib2.Request(authorize_url))
        pin = cj._cookies['www.openstreetmap.org']['/']['_osm_session'].value
        try:
            request_token_access, request_token_secret_access = osm.get_access_token(
                request_token,
                request_token_secret,
                method='POST',
                data={'oauth_verifier': pin})
            data_access = {
                'request_token': request_token_access,
                'secret_token': request_token_secret_access
            }
            resp_access = requests.post(url=url_access, data=data_access)
            access_token = resp_access.json()['osv']['access_token']
            token_file = open("access_token.txt", "w+")
            token_file.write(access_token)
            token_file.close()
        except Exception as ex:
            print(ex)
            print("ERROR LOGIN no GRANT ACCES")
            sys.exit()

    # run = "test"

    directory = os.listdir(path)
    for dir in directory:
        if os.path.isfile(path + "/" + dir +
                          "/track.txt") or os.path.isfile(path + "/" + dir +
                                                          "/track.txt.gz"):
            print("Processing directory: " + str(dir))
            dir_path = path + "/" + dir + "/"
            if os.path.isfile(path + "/" + dir + "/track.txt"):
                metaData_name = 'track.txt'
            elif os.path.isfile(path + "/" + dir + "/track.txt.gz"):
                metaData_name = 'track.txt.gz'
            dst = path + dir + "/" + 'index_write.txt'

            if os.path.isfile(dst):
                print("Metadata backup found")
                index_write = file(dst, "r+")
                for i in index_write:
                    firs_id_sequence = int(i)
            else:
                print("Generating metadata backup")
                index_write = file(dst, "w+")
                firs_id_sequence = -1
                # copyfile(src, dst)
            backup_path = dir_path + metaData_name
            if "gz" in metaData_name:
                metaData = gzip.open(backup_path, "r")
                metaData1 = gzip.open(backup_path, "r")
            else:
                metaData = file(backup_path, "r")
                metaData1 = file(backup_path, "r")
            senzor_data1 = parseCsv(metaData1, backup_path)
            for image in senzor_data1:
                files = {
                    'metaData':
                    (metaData_name, open(dir_path + metaData_name,
                                         "rb"), 'text/plain')
                }
                try:
                    app_version = image_data['app_version']
                except:
                    app_version = None
                data_sequence = {
                    'uploadSource':
                    'Python',
                    'access_token':
                    access_token,
                    'currentCoordinate':
                    str(image['latitude']) + "," + str(image['longitude'])
                }

                try:
                    sequence_file = file(dir_path + "sequence_file.txt", "r+")
                    id_sequence = sequence_file.read()
                    break
                except Exception as ex:
                    sequence_file = file(dir_path + "sequence_file.txt", "w+")
                    h = requests.post(url_sequence,
                                      data=data_sequence,
                                      files=files)
                    id_sequence = h.json()['osv']['sequence']['id']
                    sequence_file.write(id_sequence)
                    sequence_file.close()
                    break

            senzor_data = parseCsv(metaData, backup_path)
            count = 0
            for image_data in senzor_data:
                try:
                    if firs_id_sequence < int(image_data['index']):
                        photo = {
                            'photo':
                            (image_data['index'] + '.jpg',
                             open(dir_path + image_data['index'] + '.jpg',
                                  'rb'), 'image/jpeg')
                        }
                        if image_data['compas'] != '':
                            # TODO: add 'acces_token': acces_token,
                            data_photo = {
                                'access_token':
                                access_token,
                                'coordinate':
                                str(image_data['latitude']) + "," +
                                str(image_data['longitude']),
                                'sequenceId':
                                id_sequence,
                                'headers':
                                image_data['compas'],
                                'gpsAccuracy':
                                image_data['horizontal_accuracy'],
                                'sequenceIndex':
                                count
                            }
                        else:
                            data_photo = {
                                'access_token':
                                access_token,
                                'coordinate':
                                str(image_data['latitude']) + "," +
                                str(image_data['longitude']),
                                'sequenceId':
                                id_sequence,
                                'sequenceIndex':
                                count,
                                'gpsAccuracy':
                                image_data['horizontal_accuracy']
                            }

                        try:
                            p = requests.post(url_photo,
                                              data=data_photo,
                                              files=photo)
                        except requests.exceptions.Timeout:
                            print("Timout error  retry:")
                            count_timeout = 0
                            for i in range(0, 9):
                                try:
                                    count_timeout += 1
                                    print("Retry : " + str(i))
                                    p = requests.post(url_photo,
                                                      data=data_photo,
                                                      files=photo)
                                    if int(p.json()['osv']['photo']
                                           ['id']) != "":
                                        break
                                except requests.exceptions.Timeout:
                                    continue
                            if count_timeout == 9:
                                print("Timeout Err")
                                print(
                                    "To not lose any data the script will stop"
                                )
                                print("Please restart the script")
                                sys.exit()
                        except requests.exceptions.ConnectionError:
                            print("Connection Err")
                            print("To not lose any data the script will stop")
                            print(
                                "Make sure you have an internet connection then restart the script"
                            )
                            sys.exit()
                        try:
                            if int(p.json()['osv']['photo']['id']) != "":
                                count += 1
                                img_index = image_data['index']
                                total_img = senzor_data[len(senzor_data) -
                                                        1]['index']
                                percentage = float((float(img_index) * 100) /
                                                   float(total_img))
                                print("Uploaded :" + img_index +
                                      '.jpg, remaining :' +
                                      str(len(senzor_data) - count) +
                                      ", percentage: " +
                                      str(round(percentage, 2)) + "%")
                                index_write.write(str(img_index) + "\n")
                                # deletePhoto(dir_path, image_data['index'])
                        except Exception as ex:
                            print("Err for: " + image_data['index'] +
                                  ".jpg with message: " +
                                  str(p.json()['status']['apiMessage']))
                except Exception as ex:
                    if str(
                            ex
                    ) == "local variable 'firs_id_sequence' referenced before assignment":
                        print("Index file is corrupted")
                        print(
                            "The index file will be deleted and start from the first photo"
                        )
                        print("Please restart the script")
                        os.remove(dst)
                        sys.exit()
                    print "ERR"
            data_finish = {
                'access_token': access_token,
                'sequenceId': id_sequence
            }
            f = requests.post(url_finish, data=data_finish)
            if f.json()['status']['apiCode'] == '600':
                print("Finish uploading from dir: " + dir_path)
            else:
                print("FAIL uploading from dir: " + dir_path)
コード例 #24
0
# create an instance of database migration class
migrate = Migrate(app, db)

login = LoginManager(app)
login.login_view = 'login'
bootstrap = Bootstrap(app)

import models
from models import User, Book
from forms import LoginForm, RegistrationForm
from explore import load_embedding, showneighbors, postgres_query, load_embedding2, find_close_books, load_bookinfo

zoteroAuth = OAuth1Service(
    name='zotero',
    consumer_key=app.config['ZOTERO_CONSUMER_KEY'],
    consumer_secret=app.config['ZOTERO_CONSUMER_SECRET'],
    request_token_url='https://www.zotero.org/oauth/request',
    access_token_url='https://www.zotero.org/oauth/access',
    authorize_url='https://www.zotero.org/oauth/authorize',
    base_url='https://api.zotero.org')
request_token = ''
request_token_secret = ''


# connect to database
def connect_db():
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv


# open database connection
コード例 #25
0
from rauth import OAuth1Service

try:
    read_input = raw_input
except NameError:
    read_input = input

# Get a real consumer key & secret from https://dev.twitter.com/apps/new
twitter = OAuth1Service(
    name='twitter',
    consumer_key='J8MoJG4bQ9gcmGh8H7XhMg',
    consumer_secret='7WAscbSy65GmiVOvMU5EBYn5z80fhQkcFWSLMJJu4',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    base_url='https://api.twitter.com/1.1/')

request_token, request_token_secret = twitter.get_request_token()

authorize_url = twitter.get_authorize_url(request_token)

print('Visit this URL in your browser: {url}'.format(url=authorize_url))
pin = read_input('Enter PIN from browser: ')

session = twitter.get_auth_session(request_token,
                                   request_token_secret,
                                   method='POST',
                                   data={'oauth_verifier': pin})

params = {
    'include_rts': 1,  # Include retweets
コード例 #26
0
from rauth import OAuth1Session
import os

if __name__ == '__main__':

    ROOT = 'http://api.cubesensors.com'
    AUTH = '%s/auth' % ROOT
    RES = '%s/v1' % ROOT

    consumer_key = raw_input('Please enter consumer_key:')
    consumer_secret = raw_input('Please enter consumer_secret:')

    cbsr = OAuth1Service(
            consumer_key=consumer_key,
            consumer_secret=consumer_secret,
            access_token_url='%s/access_token' % AUTH,
            authorize_url='%s/authorize' % AUTH,
            request_token_url='%s/request_token' % AUTH,
            base_url='%s/' % RES)

    request_token, request_token_secret = cbsr.get_request_token(params={"oauth_callback":"oob"})

    #print ('request token = %s, request token secret = %s' % (request_token, request_token_secret))

    authorize_url = cbsr.get_authorize_url(request_token)

    print 'Open the following URL in a browser and authorise access.'
    print authorize_url

    print 'Enter the code given below and press enter.'
    oauth_verifier = raw_input('oauth_verifier:')
コード例 #27
0
ファイル: views.py プロジェクト: suhaaskaul/tweet_imoffer
from rauth import OAuth1Service
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_protect
import nltk
import re
from instamojo import *

twitter = OAuth1Service(
		name='twitter',
		consumer_key='EGeDjo0UzJPrKYuFnwKw',
		consumer_secret='2KxZ5UC5ZEGRSwra2uEtG3FfxccPRnP2U0Sbx8c',
		request_token_url='https://api.twitter.com/oauth/request_token',
		access_token_url='https://api.twitter.com/oauth/access_token',
		authorize_url='https://api.twitter.com/oauth/authorize',
		base_url='https://api.twitter.com/1.1/')
 
request_token, request_token_secret = twitter.get_request_token()
authorize_url = twitter.get_authorize_url(request_token)


class Offer:
     def __init__(self, title, description, price , currency):
        self.title = title
        self.description = description
        self.price = price
        self.currency = currency
       
def userenter(request):
	return TemplateResponse(request, 'enter.html', {"URL" : authorize_url  })
	
@csrf_protect 
コード例 #28
0
    app.debug = True
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.DEBUG)
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN)
log = app.logger
app.config['TEMPLATES_AUTO_RELOAD'] = True
db = SQLAlchemy(app)
migrate = Migrate(app, db)
models = build_models(db)
for m in models:
    globals()[m.__name__] = m

goodreads = OAuth1Service(
    consumer_key=config["goodreads"]["key"],
    consumer_secret=config["goodreads"]["secret"],
    name='goodreads',
    request_token_url='https://www.goodreads.com/oauth/request_token',
    authorize_url='https://www.goodreads.com/oauth/authorize',
    access_token_url='https://www.goodreads.com/oauth/access_token',
    base_url='https://www.goodreads.com/')


@app.route("/")
def index():
    return render_template('index.html', **config)


tokens = {}


@app.route("/oauth/request", methods=["GET"])
def oauth_request():
コード例 #29
0
def get_powershop_session(access_token_url,
                          authorize_url,
                          base_url,
                          consumer_key,
                          consumer_secret,
                          customer_email,
                          customer_password,
                          oauth_callback,
                          request_token_url,
                          log_level=logging.INFO,
                          application_name="Powershop-App"):

    logger = logging.getLogger()
    logging.basicConfig(level=log_level)

    service = OAuth1Service(name=application_name,
                            consumer_key=consumer_key,
                            consumer_secret=consumer_secret,
                            request_token_url=request_token_url,
                            access_token_url=access_token_url,
                            authorize_url=authorize_url,
                            base_url=base_url)

    # Step 1: request token
    oauth_token, oauth_token_secret = service.get_request_token(
        method="POST", params={'oauth_callback': oauth_callback})
    logger.debug("oauth_request_token = %s, oauth_request_token_secret = %s",
                 oauth_token, oauth_token_secret)

    authorize_url = service.get_authorize_url(oauth_token)
    logger.info("authorize_url: %s", authorize_url)

    # Step 2: Client Authorize
    provider_auth_resp = requests.get(authorize_url)
    logger.info("request authorize page: %s", provider_auth_resp.url)
    auth_page = htmldom.HtmlDom().createDom(provider_auth_resp.content)
    authenticity_token = auth_page.find(
        "input[name=authenticity_token]").first().attr("value")
    logger.debug("authorize page authenticity_token: %s", authenticity_token)
    auth = requests.post(authorize_url,
                         cookies=provider_auth_resp.cookies,
                         data={
                             'utf8': '&#x2713;',
                             'email': customer_email,
                             'password': customer_password,
                             'oauth_token': oauth_token,
                             'authenticity_token': authenticity_token
                         },
                         allow_redirects=True)

    url = urlparse(auth.url)
    queries = parse_qs(url.query)
    logger.info("authorized access: %s", url)

    # Step 3: Get Access Token after Client Auth
    session = service.get_auth_session(
        oauth_token,
        oauth_token_secret,
        method="POST",
        params={'oauth_verifier': queries['oauth_verifier'][0]})

    logger.debug(vars(session))

    return session
コード例 #30
0
    def idToScreenname(self, ids, verbose=False):

        try:
            '''
            Returns a list of screennames corresponding to
            the queried ids. Max 100 values; additional are truncated.
             
            '''

            # Load your API keys
            secrets = self.getSecrets(user=True)
            if verbose: print('\nSecrets loaded')

            # Create rauth request
            twitter = OAuth1Service(
                consumer_key=secrets['consumer_key'],
                consumer_secret=secrets['consumer_secret'],
                name='twitter',
                access_token_url='https://api.twitter.com/oauth/access_token',
                authorize_url='https://api.twitter.com/oauth/authorize',
                request_token_url='https://api.twitter.com/oauth/request_token',
                base_url='https://api.twitter.com/1.1/')
            if verbose: print('oAuth service started')

            # Get a session
            session = twitter.get_session(
                (secrets['token_key'], secrets['token_secret']))
            if verbose: print('oAuth session created')

            # Fill out query parameters
            query = ''
            ctr = 0
            for uid in ids:
                query += str(uid) + ','
                ctr += 1
                if ctr == 100: break  # Max 100 queries per request
            if len(query) > 0:
                query = query[0:len(query) - 1]
            params = {'user_id': query, 'include_entities': 'false'}

            # Send the request and return results
            if verbose:
                print('\nSending id:screen_name request...')
                print(
                    'If this takes a long time, be sure to check availability:'
                )
                print('https://dev.twitter.com/overview/status\n')
            TWITTER_URL = 'https://api.twitter.com/1.1/users/lookup.json'
            reply = session.post(TWITTER_URL, data=params)
            data = reply.json()
            phonebook = Tweet.getScreennames(data)
            screennames = []
            for uid in ids:
                if uid in phonebook:
                    screennames.append(phonebook[str(uid)])
                else:
                    screennames.append('@???????')
            return screennames
        except Exception:
            print('Error retrieving screen names.')
            raise