毎日Learning

学んだことを共有します

Twitter APIを使って検索取得したJSONをGoogle App Engineに保存するcron

Twitter APIを使って、あるキーワードで取得した結果を、そのままGoogle App EngineのEntityに保存する。

というcronを作ったので、メモっておく。

app.yamlは以下のようにする。

application: hoge
version: 1
runtime: python
api_version: 1

- url: /c/.*
  script: cron/urls.py
  login: admin

cron.yamlは以下のようにする。

cron:
- description: 10 minutes job
  url: /cron/pull/
  schedule: every 10 minutes

cron/urls.pyに以下のように記述する。

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import utils

from cron.views import PullAction

application = webapp.WSGIApplication(
    utils.patterns(
        ('/c/pull/', PullAction),
        ), debug=True)

if __name__ == "__main__":
    run_wsgi_app(application)

cron/views.pyは、以下のようにする。refresh_urlが取得できたら、refresh_urlをGETパラメータに指定して取得する。

import urllib, urllib2

from google.appengine.api import users
from google.appengine.ext import webapp, db

from django.utils import simplejson

from utils import render_to_response

from tweets.models import Twitter

class PullAction(webapp.RequestHandler):
    def get(self):

        baseurl = "http://search.twitter.com/search.json"

        t_l = Twitter.all().order("-insert_date")
        if t_l:
            json = simplejson.loads(t_l[0].src)
            q = json["refresh_url"]
        else:
            q = "?%s" % urllib.urlencode({"q": "#childquest"})

        src = urllib2.urlopen(baseurl + q)
        Twitter(src=src.read()).put()

保存するEntityは、tweets/models.pyに以下のように書く。

# -*- coding: utf-8 -*-

from google.appengine.ext import db
from google.appengine.ext.db import polymodel

class Twitter(db.Model):
    insert_date = db.DateTimeProperty("登録日時", auto_now_add=True)
    src = db.BlobProperty()

とりあえず、これでそのまんま保存できる。