用Python的Django框架编写从Google Adsense中获得报表的应用

yizhihongxing

首先让我们来讲解一下用Python的Django框架编写从Google Adsense中获得报表的应用的完整攻略。

1.准备工作

在开始编写应用程序之前,您需要准备以下工具和框架:

  • Python 3.6+
  • Django 2.x
  • Google Adsense API
  • Google OAuth2认证

2.创建Google OAuth2应用程序

在项目开发之前,首先需要设置好Google授权认证。访问Google API Console并使用您的Google账户登录。创建一个项目并启用Google Adsense API。

然后,配置您的OAuth2认证。从左侧面板选择“凭据”选项。点击“创建凭据”,选择“OAuth客户端ID”为凭据类型。单击“创建凭据”按钮后,填写必要的信息即可完成设置。在这些信息包括:

  • 应用程序类型:Web应用程序
  • 授权JavaScript来源:http://localhost:8000
  • 受信任的重定向URI:http://localhost:8000/oauth/callback

记录下客户端ID和客户端密钥,稍后将用于在应用程序中进行授权。

3.安装必要的Python包

使用pip安装以下Python包(同样也可在PyPI上查找):

pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client Django

4.创建Django应用

创建Django项目和应用程序,并在“settings.py”文件中设置应用程序密钥和其他必要的设置:

# settings.py
from os import environ

# Google Adsense API
ADS_CLIENT_ID = environ.get('ADS_CLIENT_ID')
ADS_CLIENT_SECRET = environ.get('ADS_CLIENT_SECRET')
ADS_REDIRECT_URI = 'http://localhost:8000/oauth/callback'
ADS_USER_AGENT = 'google-api-python-client/1.7.11 Python/3.7.3'

# Django settings
DEBUG = True
SECRET_KEY = 'your-secret-key-here'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ads.apps.AdsConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db.sqlite3',
    }
}

STATIC_URL = '/static/'

接下来,创建应用程序:

python manage.py startapp ads

并在“ads/apps.py”文件中添加应用程序名称:

# ads/apps.py
from django.apps import AppConfig

class AdsConfig(AppConfig):
    name = 'ads'

5.在Django中实现OAuth2身份验证

在“ads/views.py”中使用Google OAuth2进行身份验证:

from django.shortcuts import redirect, render
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow

def index(request):
    if 'credentials' not in request.session:
        flow = Flow.from_client_config(
            client_id=settings.ADS_CLIENT_ID,
            client_secret=settings.ADS_CLIENT_SECRET,
            scope=['https://www.googleapis.com/auth/adsense.readonly'],
            redirect_uri=settings.ADS_REDIRECT_URI)
        auth_url, state = flow.authorization_url(
            access_type='offline', include_granted_scopes='true')
        request.session['oauth2_state'] = state
        return redirect(auth_url)
    else:
        credentials = Credentials.from_authorized_user_info(
            request.session['credentials'])
        return render(request, 'index.html')

接下来,在重定向URI上创建回调视图以便于接收OAuth2授权码:

def oauth_callback(request):
    try:
        state = request.session['oauth2_state']
    except KeyError:
        return redirect('index')
    flow = Flow.from_client_config(
        client_id=settings.ADS_CLIENT_ID,
        client_secret=settings.ADS_CLIENT_SECRET,
        scope=['https://www.googleapis.com/auth/adsense.readonly'],
        state=state,
        redirect_uri=settings.ADS_REDIRECT_URI)
    flow.fetch_token(authorization_response=request.get_full_path())
    request.session['credentials'] = flow.credentials.to_json()
    return redirect('index')

6.使用Google Adsense API

使用以下代码从Google Adsense API中检索报告数据:

from django.conf import settings
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

def get_report_data(request):
    credentials = Credentials.from_authorized_user_info(
        request.session['credentials'])
    svc = build('adsense', 'v1.4', credentials=credentials, user_agent=settings.ADS_USER_AGENT)
    results = svc.accounts().reports().generate(
        accountId=request.GET.get('account_id'),
        currency=request.GET.get('currency'),
        date_range='custom',
        dimension=['DATE'],
        metric=['EARNINGS', 'CLICKS'],
        start_date=request.GET.get('start_date'),
        end_date=request.GET.get('end_date')).execute()
    return results

示例

以下是通过Django应用程序使用Google Adsense API的两个示例:

示例1:从用户的所有Adsense账户中汇总并列出数据

def report(request):
    accounts = []
    results = {}
    credentials = Credentials.from_authorized_user_info(
        request.session['credentials'])
    svc = build('adsense', 'v1.4', credentials=credentials, user_agent=settings.ADS_USER_AGENT)
    accounts_list = svc.accounts().list().execute()
    for account in accounts_list['items']:
        accounts.append({
            'id': account['id'],
            'name': account['name'],
        })
        r = svc.accounts().reports().generate(
            accountId=account['id'],
            currency='USD',
            date_range='custom',
            dimension=['DATE'],
            metric=['EARNINGS', 'CLICKS'],
            start_date=request.GET.get('start_date'),
            end_date=request.GET.get('end_date')).execute()
        for row in r['rows']:
            date = row['cells'][0]['value']
            earnings = float(row['cells'][1]['value'])
            clicks = int(row['cells'][2]['value'])
            if date not in results:
                results[date] = {
                    'clicks': clicks,
                    'earnings': earnings,
                }
            else:
                results[date]['clicks'] += clicks
                results[date]['earnings'] += earnings
    return render(request, 'report.html', {
        'accounts': accounts,
        'results': sorted(results.items()),
    })

示例2:列出已选择账户的数据

def account_report(request):
    data = get_report_data(request)
    rows = []
    for row in data['rows']:
        date = row['cells'][0]['value']
        earnings = float(row['cells'][1]['value'])
        clicks = int(row['cells'][2]['value'])
        rows.append({
            'date': date,
            'earnings': earnings,
            'clicks': clicks,
        })
    return render(request, 'account_report.html', {
        'rows': rows,
    })

这些示例仅是使用Google Adsense API的几个可能性之一。可以使用Django框架构建更多更复杂的应用程序来呈现详细的报表和数据视图。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:用Python的Django框架编写从Google Adsense中获得报表的应用 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • Django之ORM性能优化建议

    前言   DjangoORM数据层提供各种途径优化数据的访问。   如果事先理解Django的优化技巧,开发过程中稍稍留意,后期会省不少的工作量。 正题 一,利用标准数据库优化技术 传统数据库优化技术博大精深,不同的数据库有不同的优化技巧,但重心还是有规则的。在这里算是题外话,挑两点通用的说说:  索引,给关键的字段添加索引,性能能更上一层楼,如给表的关联字…

    Django 2023年4月13日
    00
  • django ngRoute ui-router 开发环境下禁用缓存

    问题描述: Python manage.py runserver ,禁用缓存,及时修改反馈到浏览器 解决办法: 使用dummy cache: Dummy caching (for development)¶ Finally, Django comes with a “dummy” cache that doesn’t actually cache – it …

    Django 2023年4月16日
    00
  • 以一个投票程序的实例来讲解Python的Django框架使用

    让我来详细讲解一下“以一个投票程序的实例来讲解Python的Django框架使用”的完整攻略。 首先,需要明确的是,Django是一个基于Python的开源web框架,它让开发web应用变得更加容易,同时也能提高开发效率。在本攻略中,我们将借助Django框架来实现一个简单的投票程序,以便更好地理解Django框架的使用方法。 一、环境搭建在使用Django…

    Django 2023年5月16日
    00
  • Django中用户权限模块

    Django中用户权限模块 1 auth模块 auth模块是Django提供的标准权限管理系统,可以提供用户身份认证, 用户组和权限管理。 auth可以和admin模块配合使用, 快速建立网站的管理系统。 在INSTALLED_APPS中添加’django.contrib.auth’使用该APP, auth模块默认启用。 2 User属性与方法 (1) 属性…

    Django 2023年4月10日
    00
  • django与vue的完美结合_实现前后端的分离开发之后在整合的方法

    下面将为你详细讲解“Django与Vue的完美结合——实现前后端的分离开发之后在整合的方法”。 1.前言 Django和Vue都是非常流行的Web开发框架,Django是一款开源的Python Web框架,Vue是一款渐进式JavaScript框架,常用于构建单页面应用(SPA)。在Web开发中,前端与后端的分离已经成为了主流趋势,而Django和Vue的完…

    Django 2023年5月16日
    00
  • Django之单表查询,多表查询(正向、反向查询),聚合查询

    常用字段 AutoField int自增列,必须填入参数 primary_key=True。当model中如果没有自增列,则自动会创建一个列名为id的列。 IntegerField 一个整数类型,范围在 -2147483648 to 2147483647。(一般不用它来存手机号(位数也不够),直接用字符串存,) CharField 字符类型,必须提供max_…

    Django 2023年4月12日
    00
  • Django-F和Q函数作用与使用

    F函数 能够解析对现有查询对象的引用的对象。 obj = Score.objects.get(stuid=’12’) obj.score += 1 obj.order.save() 执行出的SQL语句 update score set score = 60 where stuid = ’12’ 而我们想生成的SQL语句为 update score set s…

    Django 2023年4月10日
    00
  • Django如何批量创建Model

    首先,我们需要明确批量创建Model的场景。一般情况下,需要批量创建Model的场景比较罕见,因为Model用于描述一个数据表,每个表都有自己独立的结构和字段,不同的表之间极少会存在字段完全一致的情况。不过,在某些特殊情况下,可能需要针对一种特定的数据格式,创建多个具有相似结构的表,这时批量创建Model就派上用场了。 假设我们有一个需求,需要创建10个具有…

    Django 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部