json フィードをデータベースにインポートしようとしています。最初に純粋な python スクリプトを作成し、それを編集して Django のデータベース関数を使用しました。
def getListOfProperties():
if getLastModifiedTimestamp() != 0:
url = URL + "?from_date=" + str(getLastModifiedTimestamp())
else:
url = URL
resp,cont= client.request(url, "GET")
results = json.loads(cont)
try:
properties = results['properties']
except KeyError, e:
return "Geen panden in Max-immo"
for property in properties:
if checkIfPropertyInDBList(id=property['id'])== 0:
#do something
else:
#do the other thing
if len(properties)!=0:
addPropertiesDetail()
getListOfProperties()
純粋な python スクリプトでは、関数checkIfpropertyDbListは次のようになります。
import settings
def checkIfPropertyInDBList(id=0):
db = settings.db()
cur = db.cursor()
if id==0:
cur.execute("SELECT COUNT(*) FROM mi_import")
else:
cur.execute("SELECT COUNT(*) FROM mi_import WHERE id = %s" % id)
return cur.fetchone()[0]
設定モジュールは次のようになります。
###settings.py
import MySQLdb
def db():
return MySQLdb.connect(
host= "localhost",
user="root",
passwd="*****",
db="*****",
)
ターミナルでスクリプトを実行すると、問題なく動作します。問題は、Google App Engine にデプロイされた Django サイトにスクリプトを統合する必要があるため、上記の関数を Django の組み込みデータベース モジュールを使用するように調整したことです。
from django.db import connection, DatabaseError
def checkIfPropertyInDBList(id=0):
cur = connection.cursor()
if id==0:
cur.execute("SELECT COUNT(*) FROM mi_import")
else:
cur.execute("SELECT COUNT(*) FROM mi_import WHERE id = %s" % id)
return cur.fetchone()[0]
ただし、これによりTypeError: 'int' object is not subscriptable が発生します。
完全なトレースバックは次のとおりです。
Environment:
Request Method: GET
Request URL: localhost:8088/cron/importAll/
Django Version: 1.3.1
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'south',
'app']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware')
Traceback:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_1_3/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/username/PycharmProjects/project/app/cron.py" in lookupProperties
180. getListOfProperties()
File "/Users/username/PycharmProjects/project/app/cron.py" in getListOfProperties
169. if checkIfPropertyInDBList(id=property['id'])== 0:
Exception Type: TypeError at /cron/importAll/
Exception Value: 'int' object is not subscriptable
助言がありますか?