嵌套函数中的argparse会让JSON变得疯狂吗?

时间:2017-06-01 06:58:29

标签: python json argparse yelp

我有一个问题,使用此代码:

#!/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

所以我认为问题的根源是argparse。我应该把它放在函数内部,还要放在第二个选项的函数之外吗?

1 个答案:

答案 0 :(得分:0)

启动时,您的代码会创建解析器并设置args。我喜欢在此时进行诊断print(args)

下一步是

SQLQuery()

该函数建立'连接',并尝试使用args.SQL值。如果设置为--SQL,则会获取数据。

如果您未提供它获得默认值:

'SELECT top 3 Country, City FROM worldcitiespop'

显然sql fetch失败。

我的代码中没有显示使用args.countryargs.location值的任何内容。我怀疑其目的是使用这些值来修改默认的SQL查询。