我在djaongo项目中创建了一个新的应用,叫做“adsense”。并创建了一个models.py文件来存储认证证书。
from django.contrib.auth.models import Userfrom django.db import modelsfrom oauth2client.django_orm import CredentialsFieldclass Credential(models.Model): id = models.ForeignKey(User, primary_key=True) credential = CredentialsField()class Revenue(models.Model): date = models.DateField(unique=True) revenue = models.DecimalField(max_digits=7, decimal_places=2) def __unicode__(self): return '{0} ${1}'.format(self.date, self.revenue)
我把从API控制台下载的JSON文件放到我的应用的文件夹下面,并创建了一个views.py文件:
import osfrom django.conf import settingsfrom django.contrib.auth.decorators import login_requiredfrom django.contrib.sites.models import Sitefrom django.http import HttpResponseBadRequest, HttpResponsefrom django.http import HttpResponseRedirectfrom oauth2client import xsrfutilfrom oauth2client.client import flow_from_clientsecretsfrom oauth2client.django_orm import Storagefrom .models import CredentialCLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/adsense.readonly', redirect_uri='http://{0}/adsense/oauth2callback/'.format( Site.objects.get_current().domain))@login_requireddef index(request): storage = Storage(Credential, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid is True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: return HttpResponse('Already validated.')@login_requireddef auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.REQUEST) storage = Storage(Credential, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect("/")在 urls.py 文件中我包含了一个链接指向我的应用的url文件
main urls.py:
from django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.autodiscover()urlpatterns = patterns( '', url(r'^adsense/', include('adsense.urls', namespace='adsense')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)),)adsense/urls.py:
from django.conf.urls import patterns, urlurlpatterns = patterns( 'adsense.views', url(r'^$', 'index', name='index'), url(r'^oauth2callback/$', 'auth_return', name='auth_return'),)最后,创建了一个通过给定日期调用API并获取收益的类。它放在adsense/tasks.py,因为我准备把它当作任务,钩在 / 之上。
import datetimeimport httplib2from apiclient.discovery import buildfrom django.contrib.auth.models import Userfrom oauth2client.django_orm import Storagefrom .models import Credential, RevenueTODAY = datetime.date.today()YESTERDAY = TODAY - datetime.timedelta(days=1)class Scraper(object): def get_report(self, start_date=YESTERDAY, end_date=TODAY): user = User.objects.get(pk=1) storage = Storage(Credential, 'id', user, 'credential') credential = storage.get() if not credential is None or credential.invalid is False: http = httplib2.Http() http = credential.authorize(http) service = build('adsense', 'v1.2', http=http) reports = service.reports() report = reports.generate( startDate=start_date.strftime('%Y-%m-%d'), endDate=end_date.strftime('%Y-%m-%d'), dimension='DATE', metric='EARNINGS', ) data = report.execute() for row in data['rows']: date = row[0] revenue = row[1] record = Revenue() try: r = Revenue.objects.get(date=date) pk = r.id except Revenue.DoesNotExist: pk = None record.id = pk record.date = date record.revenue = revenue record.save()为了让它能工作起来,我在浏览器打开http://localhost:8000/adsense/。这时候会要求我登录Google帐号。我为我的应用授权来访问Adsense。然后,认证证书就会保存在我的本地数据库,然后我可以调用Scraper get_report() 方法。祝贺我吧!。它能顺利工作了。