博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django 学习
阅读量:5138 次
发布时间:2019-06-13

本文共 4465 字,大约阅读时间需要 14 分钟。

我的应用很简单。我只需要读取指定日期的收益金额,并保存到我的本地数据库。

我在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() 方法。祝贺我吧!。它能顺利工作了。

转载于:https://www.cnblogs.com/java20130722/p/3206909.html

你可能感兴趣的文章
list control控件的一些操作
查看>>
LVM快照(snapshot)备份
查看>>
绝望的第四周作业
查看>>
一月流水账
查看>>
npm 常用指令
查看>>
非常棒的Visual Studo调试插件:OzCode 2.0 下载地址
查看>>
判断字符串在字符串中
查看>>
Linux环境下Redis安装和常见问题的解决
查看>>
HashPump用法
查看>>
cuda基础
查看>>
Vue安装准备工作
查看>>
oracle 创建暂时表
查看>>
201421410014蒋佳奇
查看>>
Xcode5和ObjC新特性
查看>>
LibSVM for Python 使用
查看>>
Centos 7.0 安装Mono 3.4 和 Jexus 5.6
查看>>
CSS属性值currentColor
查看>>
java可重入锁reentrantlock
查看>>
浅谈卷积神经网络及matlab实现
查看>>
解决ajax请求cors跨域问题
查看>>