2013-07-04 3 views
1

파이썬 파일에 오류가 있습니다. 그것은 특정 Google API에 대한 액세스 권한을 얻는 것입니다. OAuth2.0. 하지만 그건 잘못된 부분이 아닙니다. 잘못된 부분은 argparse (--something = ""을 추가하여 콘솔에서 인수를 얻음)의 일부분을 차지합니다. 이 라인에모듈 객체에 'argpaser'속성이 없습니다. ---- Python

import argparse 
import os 
import pprint 
import sys 
import time 
import httplib2 

from apiclient import discovery 
from oauth2client import file 
from oauth2client import tools 
from oauth2client import client 


# Time to wait (in seconds) between successive checks of training status. 
SLEEP_TIME = 10 


# Declare command-line flags. 
argparser = argparse.ArgumentParser(add_help=False) 
argparser.add_argument('object_name', 
        help='Full Google Storage path of csv data (ex bucket/object)') 
argparser.add_argument('id', 
        help='Model Id of your choosing to name trained model') 
#argparser.add_argument('action'); 


def print_header(line): 
    '''Format and print header block sized to length of line''' 
    header_str = '=' 
    header_line = header_str * len(line) 
    print '\n' + header_line 
    print line 
    print header_line 


def main(argv): 

    parent_parsers = [tools.argparser] 
    parent_parsers.extend(parents) 
    parser = argparse.ArgumentParser(
     description=doc, 
     formatter_class=argparse.RawDescriptionHelpFormatter, 
     parents=parent_parsers) 
    flags = parser.parse_args(argv[1:]) 

    scope='https://www.googleapis.com/auth/prediction' 

    client_secrets = os.path.join(os.path.dirname(__file__), 
           'client_secrets.json') 
    flow = client.flow_from_clientsecrets(client_secrets, 
     scope=scope, 
     message=tools.message_if_missing(client_secrets)) 

    storage = file.Storage('prediction.dat') 
    credentials = storage.get() 

    if credentials is None or credentials.invalid: 
    credentials = tools.run_flow(flow, storage, flags) 
    http = credentials.authorize(http = httplib2.Http()) 
    service = discovery.build('prediction', 'v1.6', http=http) 


    try: 
    papi = service.trainedmodels() 
    print_header('Fetching list of first ten models') 
    result = papi.list(maxResults=10).execute() 
    print 'List results:' 
    pprint.pprint(result) 

    except client.AccessTokenRefreshError: 
    print ("The credentials have been revoked or expired, please re-run" 
     "the application to re-authorize") 


if __name__ == '__main__': 
    main(sys.argv) 

->parent_parsers = [tools.argparser] 내가 그 오류가 있어요 : 여기

내 코드의

line 75, in main parent_parsers = [tools.argparser] AttributeError: 'module' object has no attribute 'argparser'

tools.py 파일이 하나가 :

import BaseHTTPServer 
import argparse 
import httplib2 
import logging 
import os 
import socket 
import sys 
import webbrowser 

from oauth2client import client 
from oauth2client import file 
from oauth2client import util 

try: 
    from urlparse import parse_qsl 
except ImportError: 
    from cgi import parse_qsl 

_CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0 

To make this sample run you will need to populate the client_secrets.json file 
found at: 

    %s 

with information from the APIs Console <https://code.google.com/apis/console>. 

""" 

# run_parser is an ArgumentParser that contains command-line options expected 
# by tools.run(). Pass it in as part of the 'parents' argument to your own 
# ArgumentParser. 
argparser = argparse.ArgumentParser(add_help=False) 
argparser.add_argument('--auth_host_name', default='localhost', 
         help='Hostname when running a local web server.') 
argparser.add_argument('--noauth_local_webserver', action='store_true', 
         default=False, help='Do not run a local web server.') 
argparser.add_argument('--auth_host_port', default=[8080, 8090], type=int, 
         nargs='*', help='Port web server should listen on.') 
argparser.add_argument('--logging_level', default='ERROR', 
         choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 
           'CRITICAL'], 
         help='Set the logging level of detail.') 


class ClientRedirectServer(BaseHTTPServer.HTTPServer): 
    """A server to handle OAuth 2.0 redirects back to localhost. 

    Waits for a single request and parses the query parameters 
    into query_params and then stops serving. 
    """ 
    query_params = {} 


class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): 
    """A handler for OAuth 2.0 redirects back to localhost. 

    Waits for a single request and parses the query parameters 
    into the servers query_params and then stops serving. 
    """ 

    def do_GET(s): 
    """Handle a GET request. 

    Parses the query parameters and prints a message 
    if the flow has completed. Note that we can't detect 
    if an error occurred. 
    """ 
    s.send_response(200) 
    s.send_header("Content-type", "text/html") 
    s.end_headers() 
    query = s.path.split('?', 1)[-1] 
    query = dict(parse_qsl(query)) 
    s.server.query_params = query 
    s.wfile.write("<html><head><title>Authentication Status</title></head>") 
    s.wfile.write("<body><p>The authentication flow has completed.</p>") 
    s.wfile.write("</body></html>") 

    def log_message(self, format, *args): 
    """Do not log messages to stdout while running as command line program.""" 
    pass 


@util.positional(3) 
def run_flow(flow, storage, flags, http=None): 

    logging.getLogger().setLevel(getattr(logging, flags.logging_level)) 
    if not flags.noauth_local_webserver: 
    success = False 
    port_number = 0 
    for port in flags.auth_host_port: 
     port_number = port 
     try: 
     httpd = ClientRedirectServer((flags.auth_host_name, port), 
            ClientRedirectHandler) 
     except socket.error, e: 
     pass 
     else: 
     success = True 
     break 
    flags.noauth_local_webserver = not success 
    if not success: 
     print 'Failed to start a local webserver listening on either port 8080' 
     print 'or port 9090. Please check your firewall settings and locally' 
     print 'running programs that may be blocking or using those ports.' 
     print 
     print 'Falling back to --noauth_local_webserver and continuing with', 
     print 'authorization.' 
     print 

    if not flags.noauth_local_webserver: 
    oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number) 
    else: 
    oauth_callback = client.OOB_CALLBACK_URN 
    flow.redirect_uri = oauth_callback 
    authorize_url = flow.step1_get_authorize_url() 

    if not flags.noauth_local_webserver: 
    webbrowser.open(authorize_url, new=1, autoraise=True) 
    print 'Your browser has been opened to visit:' 
    print 
    print ' ' + authorize_url 
    print 
    print 'If your browser is on a different machine then exit and re-run this' 
    print 'application with the command-line parameter ' 
    print 
    print ' --noauth_local_webserver' 
    print 
    else: 
    print 'Go to the following link in your browser:' 
    print 
    print ' ' + authorize_url 
    print 

    code = None 
    if not flags.noauth_local_webserver: 
    httpd.handle_request() 
    if 'error' in httpd.query_params: 
     sys.exit('Authentication request was rejected.') 
    if 'code' in httpd.query_params: 
     code = httpd.query_params['code'] 
    else: 
     print 'Failed to find "code" in the query parameters of the redirect.' 
     sys.exit('Try running with --noauth_local_webserver.') 
    else: 
    code = raw_input('Enter verification code: ').strip() 

    try: 
    credential = flow.step2_exchange(code, http=http) 
    except client.FlowExchangeError, e: 
    sys.exit('Authentication has failed: %s' % e) 

    storage.put(credential) 
    credential.set_store(storage) 
    print 'Authentication successful.' 

    return credential 


def message_if_missing(filename): 
    """Helpful message to display if the CLIENT_SECRETS file is missing.""" 

    return _CLIENT_SECRETS_MESSAGE % filename 

try: 
    from old_run import run 
except ImportError: 
    def run(*args, **kwargs): 
    raise NotImplementedError(
     'The gflags library must be installed to use tools.run(). ' 
     'Please install gflags or preferrably switch to using ' 
     'tools.run_flow().') 

나는 오류의 의미를 이해하지 못한다. 수입 문제 일지 모르지만 나는 모른다. 감사합니다.

답변

0

당신은 확실히 OAuth를 도구 설정이 제대로되어 확인해야합니다 :

python setup_oauth2client.py install 

는 기본 디렉토리에있어

관련 문제