zoukankan      html  css  js  c++  java
  • Django 学习


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

    我在djaongo项目中创建了一个新的应用,叫做“adsense”。并创建了一个models.py文件来存储认证证书。

    from django.contrib.auth.models import User
    from django.db import models
    from oauth2client.django_orm import CredentialsField
    
    class 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 os
    
    from django.conf import settings
    from django.contrib.auth.decorators import login_required
    from django.contrib.sites.models import Site
    from django.http import HttpResponseBadRequest, HttpResponse
    from django.http import HttpResponseRedirect
    from oauth2client import xsrfutil
    from oauth2client.client import flow_from_clientsecrets
    from oauth2client.django_orm import Storage
    
    from .models import Credential
    
    CLIENT_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_required
    def 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_required
    def 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, url
    from django.contrib import admin
    
    admin.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, url
    
    urlpatterns = patterns(
        'adsense.views',
        url(r'^$', 'index', name='index'),
        url(r'^oauth2callback/$', 'auth_return', name='auth_return'),
    )


    最后,创建了一个通过给定日期调用API并获取收益的类。它放在adsense/tasks.py,因为我准备把它当作任务,钩在  CeleryRabbitMQ之上。

    import datetime
    import httplib2
    
    from apiclient.discovery import build
    from django.contrib.auth.models import User
    from oauth2client.django_orm import Storage
    
    from .models import Credential, Revenue
    
    TODAY = 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() 方法。祝贺我吧!。它能顺利工作了。

  • 相关阅读:
    Deep Learning(深度学习)学习笔记整理系列五
    Deep Learning(深度学习)学习笔记整理系列四
    Deep Learning(深度学习)学习笔记整理系列三
    Deep Learning(深度学习)学习笔记整理系列二
    Deep Learning(深度学习)学习笔记整理系列 一
    java对象转为json字符串
    eclipse常用功能及快捷键
    fiddler详解
    http状态码
    eclipse中文乱码
  • 原文地址:https://www.cnblogs.com/java20130722/p/3206909.html
Copyright © 2011-2022 走看看