首先让我们来讲解一下用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技术站