2017-06-01 33 views
0

我有一個問題,與此代碼:嵌套函數argparse使JSON變得瘋狂?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

# We import the requests module which allows us to make the API call 
import requests 
import argparse 
import pyodbc                  
import sys                   
import json                   

# Here we organize the choices command line aruments         
parser = argparse.ArgumentParser()             
parser.add_argument('--country', dest='country', default='NZ',      
        type=str, help="input a country code", metavar='')    
parser.add_argument('--location', dest='location', default= 'Auckland',    
        type=str, help= "enter a location", metavar='')     
parser.add_argument('--category', dest='category', default='movietheaters',   
        type=str, help="enter a business category", metavar='')   
parser.add_argument('--limit', dest='limit', default='50',       
        type=int, help="enter a limit", metavar='')      
parser.add_argument('--do', dest='do', default='show',        
        type=str, choices=['show', 'save'],        
        help="arguments are show or save", metavar='')     
parser.add_argument('--SQL', dest='SQL',            
        default='SELECT top 3 Country, City FROM worldcitiespop',  
        type=str, help="input a SQL statement", metavar='')    
args = parser.parse_args()               




# OAuth credential at https://www.yelp.com/developers/v3/manage_app\     
app_id = 'MYAPPID'             
app_secret = 'MYAPPSECRET'  
data = {'grant_type': 'client_credentials',           
     'client_id': app_id,               
     'client_secret': app_secret}             
token = requests.post('https://api.yelp.com/oauth2/token', data = data)    
access_token = token.json()['access_token']           
headers = {'Authorization': 'bearer %s' % access_token}        



def get_movietheaters_for(country, city):           
    connection2 = pyodbc.connect('DRIVER={SQL Server};'        
          'SERVER=ASPIRES3;'          
          'DATABASE=worldcitiespop;'        
          'UID=sqlninja;'           
          'PWD=sqlninja')           
    cursor2 = connection2.cursor()             
    # Call Yelp API to pull business data           
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)     
    url = 'https://api.yelp.com/v3/businesses/search'        
    params = {'cc': country,               
       'location': city,            
       'categories': args.category,           
       'limit': args.limit}             
    response = requests.get(url = url, headers = headers, params=params)    
    # if response.status_code == 200:            
    response_data = response.json()             

    sqlStatement = "INSERT INTO Yelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone) values (?,?,?,?,?,?,?,?,?,?,?,?)" # Query 
    # Here we go to store JSON elements for SQL 
    for SQL_element in response_data['businesses']: 
     SQL_ID = SQL_element['id']              
     SQL_Name = SQL_element['name']             
     SQL_City = SQL_element['location']['city']          
     SQL_Zip_code = SQL_element['location']['zip_code']        
     SQL_Country = SQL_element['location']['country']         
     SQL_State = SQL_element['location']['state']          
     SQL_Address1 = SQL_element['location']['address1']        
     SQL_Address2 = SQL_element['location']['address2']        
     SQL_Address3 = SQL_element['location']['address3']        
     SQL_Latitude = SQL_element['coordinates']['latitude']       
     SQL_Longitude = SQL_element['coordinates']['longitude']       
     SQL_Phone = SQL_element['phone']             



     if args.do == 'show': 
      print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State, 
       SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone) 
     elif args.do == 'save':  
      cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone) 
      connection2.commit() 

    if args.do == 'show': 
     print ('\nTotal Cinemas found: ' , len(response_data['businesses'])) 
    elif args.do == 'save': 
     print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses'])) 

def SQLQuery(): 
    # We connect to SQL Server Management Studio 
    connection = pyodbc.connect('DRIVER={SQL Server};'         
           'SERVER=ASPIRES3;'          
           'DATABASE=worldcitiespop;'        
           'UID=sqlninja;'           
           'PWD=sqlninja')           
    cursor = connection.cursor() 
    try:  
     cursor.execute(args.SQL) 
     for country, city in cursor: 
      get_movietheaters_for(country, city) 
    finally: 
     cursor.close() 
     connection.close() 
SQLQuery() 

我收到此錯誤:

Total Cinemas found: 11 
Traceback (most recent call last): 
    File "Check.py", line 107, in <module> 
    SQLQuery() 
    File "Check.py", line 103, in SQLQuery 
    get_movietheaters_for(country, city) 
    File "Check.py", line 64, in get_movietheaters_for 
    for SQL_element in response_data['businesses']: 
KeyError: 'businesses' 

但是,如果使用argparse這樣

python Check.py --country fr --location Toulouse --do show 

enter image description here

但是,如果我用我的第二個argparse選項:

python Check.py --SQL "select top 1 Country, City from worldcitiespop where Country = 'fr' and City = 'Toulouse'" --do show 

一切正常:

enter image description here

所以我覺得這個問題的根源是​​。我應該把它放在函數內部,還是在第二個選項的函數之外?

+0

打印'args'來查看argparse產生的值。更可能的錯誤在於從args值構造sql查詢的代碼中。 – hpaulj

回答

0

啓動時,您的代碼將創建解析器並設置args。我想在這一點上做一個診斷print(args)

下一個動作是

SQLQuery() 

該函數建立「連接」,並嘗試使用args.SQL值。如果使用--SQL進行設置,則會提取數據。

如果你不提供它獲得默認值:

'SELECT top 3 Country, City FROM worldcitiespop' 

顯然是SQL提取失敗。

我的代碼中沒有看到使用args.countryargs.location值的任何內容。我懷疑目的是使用這些值來修改默認的SQL查詢。