Commit 22d485db authored by gaoming's avatar gaoming

新增渠道信息表

parent 46cde286
...@@ -36,9 +36,11 @@ CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案 ...@@ -36,9 +36,11 @@ CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案
#************************************requests*********************************************** #************************************requests***********************************************
REQUESTS_CONNECT_TIMEOUT=5 REQUESTS_CONNECT_TIMEOUT=5
REQUESTS_READ_TIMEOUT=5 REQUESTS_READ_TIMEOUT=5
#************************************requests***********************************************
#************************************渠道信息***********************************************
CHANNEL_BAIDU="MjgzNzA3MzE="
# Application definition # Application definition
......
from .server_settings import * from .server_settings import *
#from .local_settings import * from .settings_log import *
\ No newline at end of file
#如果是我的电脑就加载本地配置文件
import socket
if socket.gethostname()=="AppledeMacBook-Pro.local":
from .local_settings import *
\ No newline at end of file
# coding=utf-8
import os
import logging
LOG_DIR = '/data/log/channels/app/'
#日志基本配置
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s',
filename=os.path.join(LOG_DIR, 'filelog.log'),
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
#日志格式
'formatters': {
'verbose': {
'format': '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
'profile': {
'format': '%(asctime)s %(message)s'
},
'raw': {
'format': '%(message)s',
},
'normal': {
'format': '[%(asctime)s]-[%(levelname)s]:[%(module)s.%(funcName)s] %(message)s'
}
},
#定义具体处理日志的方式
'handlers': {
# 默认的服务器Log(保存到log/filelog.log中, 通过linux的logrotate来处理日志的分割
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'filelog.log'),
'formatter': 'verbose',
},
# 默认的服务器ERROR log
'default_err': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'error_logger.log'),
'formatter': 'verbose',
},
'exception_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'exception_logger.log'),
'formatter': 'raw',
},
'info_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'info_logger.log'),
'formatter': 'verbose',
},
'auth_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'auth_logger.log'),
'formatter': 'verbose',
},
'profile_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'profile.log'),
'formatter': 'profile',
},
'channel_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'channel_logger.log'),
'formatter': 'verbose',
},
'url_logger': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOG_DIR, 'url_logger.log'),
'formatter': 'verbose',
},
'sql_logger': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.handlers.RotatingFileHandler',
'maxBytes': 100000000, # 100M
'backupCount': 3,
'filename': os.path.join(LOG_DIR, 'sql_logger.log'),
'formatter': 'verbose',
}
},
'loggers': {
'django': {
'handlers': ['default'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['default_err'],
'level': 'ERROR',
'propagate': False,
},
'django.db.backends': {
'handlers': ['sql_logger'],
'level': 'DEBUG',
},
'exception_logger': {
'handlers': ['exception_logger'],
'level': 'INFO',
'propagate': False,
},
'info_logger': {
'handlers': ['info_logger'],
'level': 'INFO',
'propagate': False,
},
'channel_logger': {
'handlers': ['channel_logger'],
'level': 'INFO',
'propagate': False,
},
'url_logger': {
'handlers': ['url_logger'],
'level': 'INFO',
'propagate': False,
}
},
}
#!/usr/bin/env python
# encoding=utf-8
#from __future__ import unicode_literals
import abc
from urllib.parse import urlencode,unquote
import logging
import json
# import requests #导致循环引用
import hashlib
import time
from collections import namedtuple, OrderedDict
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseNotAllowed, JsonResponse, HttpResponse, Http404
from django.views.generic import View
from .models import *
from django.conf import settings
from celery import shared_task
from django.db.models import Q
import urllib
import logging
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
channel_logger = logging.getLogger('channel_logger')
def list(requests):
'''获取全部渠道信息'''
results=PromotionInfo.objects.values().all()
data=[item for item in results]
return JsonResponse({"data":data})
@csrf_exempt
def add(requests):
'''添加渠道商信息'''
parame=requests.POST.dict()
obj, created=PromotionInfo.objects.get_or_create(**parame)
return JsonResponse({"result":created})
# Generated by Django 2.2.1 on 2019-07-30 14:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('like', '0002_remove_promotionchannel_channel'),
]
operations = [
migrations.CreateModel(
name='PromotionInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, verbose_name='渠道名')),
('code', models.CharField(max_length=64, verbose_name='渠道编码')),
('sub_code', models.CharField(max_length=128, verbose_name='子渠道编码')),
('platform', models.CharField(max_length=8, verbose_name='推广平台,IOS or Android')),
('appendtime', models.DateField(auto_now_add=True, verbose_name='创建时间')),
],
options={
'verbose_name': '渠道商信息表',
'verbose_name_plural': '渠道商信息表',
'db_table': 'promotioninfo',
},
),
migrations.AlterField(
model_name='promotionchannel',
name='mac',
field=models.CharField(default='', max_length=100, null=True, verbose_name='Android设备的mac'),
),
]
...@@ -8,15 +8,32 @@ import json ...@@ -8,15 +8,32 @@ import json
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import models from django.db import models
from django.utils import timezone from django.utils import timezone
import logging
channel_logger = logging.getLogger('channel_logger')
from channels.HermesEnum import( from channels.HermesEnum import(
APP_TYPE, APP_TYPE,
CHANNEL_CALLBACK_TYPE, CHANNEL_CALLBACK_TYPE,
CLIENT_TYPE, CLIENT_TYPE,
PLATFORM_CHANNEL, PLATFORM_CHANNEL,
CHANNEL_STATUS CHANNEL_STATUS,
) )
class PromotionInfo(models.Model):
'''
渠道商信息表
'''
class Meta:
verbose_name = '渠道商信息表'
verbose_name_plural = '渠道商信息表'
db_table = 'promotioninfo'
name = models.CharField(max_length=128, verbose_name='渠道名')
code=models.CharField(max_length=64,verbose_name='渠道编码')
sub_code = models.CharField(max_length=128, verbose_name='子渠道编码')
platform=models.CharField(max_length=8,verbose_name='推广平台,IOS or Android')
appendtime=models.DateField(auto_now_add=True,verbose_name="创建时间")
class PromotionChannel(models.Model): class PromotionChannel(models.Model):
class Meta: class Meta:
unique_together = ('device_id', 'appid','idfa','idfv','imei') unique_together = ('device_id', 'appid','idfa','idfv','imei')
...@@ -99,8 +116,7 @@ class PromotionChannel(models.Model): ...@@ -99,8 +116,7 @@ class PromotionChannel(models.Model):
def record(request,sub_name=None,**kwargs): def record(request,sub_name=None,**kwargs):
""" """
新增加渠道设备数据 新增加渠道设备数据
""" """
params=PromotionChannel.filter_exists_propertys(**kwargs) params=PromotionChannel.filter_exists_propertys(**kwargs)
#获得request的数据 #获得request的数据
......
from django.urls import include, path,re_path from django.urls import include, path,re_path
from . import views from . import views,channelsinfo_views
app_name="like" app_name="like"
#(?P<sub_name>[a-z0-9]+/)? #(?P<sub_name>[a-z0-9]+/)?
urlpatterns =[ urlpatterns =[
re_path(r'^[a-z0-9]+/((?P<sub_name>[a-z0-9]+)/)?click-notify$', views.Channel.as_view()), re_path(r'^[a-z0-9]+/((?P<sub_name>[a-z0-9]+)/)?click-notify$', views.Channel.as_view()),
re_path(r'^statistic$', views.Statistic.as_view()), re_path(r'^statistic$', views.Statistic.as_view()),
re_path(r'^[a-z0-9]+/doublecheck$', views.DoubleCheck.as_view()) re_path(r'^[a-z0-9]+/doublecheck$', views.DoubleCheck.as_view()),
re_path('ping',views.ping),
re_path('list',channelsinfo_views.list),
re_path('add',channelsinfo_views.add)
] ]
\ No newline at end of file
...@@ -17,8 +17,16 @@ from .models import * ...@@ -17,8 +17,16 @@ from .models import *
from django.conf import settings from django.conf import settings
from celery import shared_task from celery import shared_task
from django.db.models import Q from django.db.models import Q
import urllib
import logging
channel_logger = logging.getLogger('channel_logger')
url_logger=logging.getLogger('url_logger')
def ping(request):
'''健康检查'''
channel_logger.info("ping------")
return JsonResponse(data="dong")
class Statistic(View): class Statistic(View):
""" """
...@@ -49,6 +57,9 @@ class Statistic(View): ...@@ -49,6 +57,9 @@ class Statistic(View):
# 迈可思, 趣米, 广点通, 爱思助手激活回调(增加点入) # 迈可思, 趣米, 广点通, 爱思助手激活回调(增加点入)
#self.async_active_callback.delay(**data) #self.async_active_callback.delay(**data)
channel_logger.info("接收到的参数---")
channel_logger.info(data)
self.async_active_callback(**data) self.async_active_callback(**data)
result={ result={
...@@ -74,7 +85,6 @@ class Statistic(View): ...@@ -74,7 +85,6 @@ class Statistic(View):
platform=kwargs.get('platform','') platform=kwargs.get('platform','')
#time.sleep(2)
#设备编号相关id #设备编号相关id
device_id=kwargs.get('device_id') device_id=kwargs.get('device_id')
...@@ -93,7 +103,7 @@ class Statistic(View): ...@@ -93,7 +103,7 @@ class Statistic(View):
sub_query=[item for key,value in kwargs.items() if key in ["device_id","idfa","idfv","imei","mac"] for item in ("{0}='{1}'".format(key,value),"{0}='{1}'".format(key,md5(value)))] sub_query=[item for key,value in kwargs.items() if key in ["device_id","idfa","idfv","imei","mac"] for item in ("{0}='{1}'".format(key,value),"{0}='{1}'".format(key,md5(value)))]
sql="select * from like_promotion_channel where {0}".format(" or ".join(sub_query)) sql="select * from like_promotion_channel where {0}".format(" or ".join(sub_query))
print(sql) channel_logger.info(sql)
record = PromotionChannel.objects.raw(sql) record = PromotionChannel.objects.raw(sql)
...@@ -103,7 +113,7 @@ class Statistic(View): ...@@ -103,7 +113,7 @@ class Statistic(View):
platform=kwargs.get("platform","") platform=kwargs.get("platform","")
print("platform is:",platform) channel_logger.info("platform is:{0}".format(platform))
if platform.strip().lower()=="iphone": if platform.strip().lower()=="iphone":
kwargs.update({"appid":"appstore"}) kwargs.update({"appid":"appstore"})
...@@ -111,13 +121,14 @@ class Statistic(View): ...@@ -111,13 +121,14 @@ class Statistic(View):
if platform.strip().lower()=="android": if platform.strip().lower()=="android":
kwargs.update({"appid":"mainpackage"}) kwargs.update({"appid":"mainpackage"})
print(kwargs)
record=PromotionChannel.record(None,**kwargs) record=PromotionChannel.record(None,**kwargs)
return return
if record: if record:
record=record[0] record=record[0]
channel_logger.info("存在待激活记录---")
#如果已经激活,不做处理 #如果已经激活,不做处理
if record and record.active_time: if record and record.active_time:
...@@ -141,7 +152,7 @@ class Statistic(View): ...@@ -141,7 +152,7 @@ class Statistic(View):
import requests import requests
#GET回调 #GET回调
if record.callback_type == CHANNEL_CALLBACK_TYPE.GET_CALLBACK.value[0]: if record.callback_type == CHANNEL_CALLBACK_TYPE.GET_CALLBACK.value[0]:
print(url) channel_logger.info(url)
response = requests.get(url, timeout=(settings.REQUESTS_CONNECT_TIMEOUT,settings.REQUESTS_READ_TIMEOUT)) response = requests.get(url, timeout=(settings.REQUESTS_CONNECT_TIMEOUT,settings.REQUESTS_READ_TIMEOUT))
#POST回调 #POST回调
...@@ -152,8 +163,7 @@ class Statistic(View): ...@@ -152,8 +163,7 @@ class Statistic(View):
record.save() record.save()
except Exception as e: except Exception as e:
print(e) channel_logger.info(e)
#channel_logger.error(str(e))
return {'error':0, 'msg':''} return {'error':0, 'msg':''}
...@@ -203,10 +213,14 @@ class Channel(View): ...@@ -203,10 +213,14 @@ class Channel(View):
platform=request.path.split('/')[2] platform=request.path.split('/')[2]
url_logger.info(request.path)
#获得渠道数据 #获得渠道数据
try: try:
data,success,fail=Channel.__dict__.get(platform)(self) data,success,fail=Channel.__dict__.get(platform)(self)
except Exception as e: except Exception as e:
channel_logger.info(e)
return JsonResponse({'code':1,'failMsg':"not exists method to handle it!"}) return JsonResponse({'code':1,'failMsg':"not exists method to handle it!"})
...@@ -240,4 +254,54 @@ class Channel(View): ...@@ -240,4 +254,54 @@ class Channel(View):
fail =lambda msg:{"ret":1,'failMsg':msg} fail =lambda msg:{"ret":1,'failMsg':msg}
return data,success,fail return data,success,fail
\ No newline at end of file def kuaishou(self):
'''
对接快手
'''
data=self.request.GET.dict()
#加入appid
data.update({"appid":"kuaishou","idfa":data.pop("idfaMD5",""),"imei":data.pop("imeiMD5","")})
success =lambda msg:{"ret":0,"failMsg":msg}
fail =lambda msg:{"ret":1,'failMsg':msg}
return data,success,fail
def baidu(self):
'''
对接百度
'''
channel_logger.info("处理百度平台点击请求---")
data=self.request.GET.dict()
callback_url=data.get("callback_url")
callback_url=unquote(callback_url)
callback_url=callback_url.replace("{{ATYPE}}","activate").replace("{{AVALUE}}","0")
#从百度拿到的akey
akey=settings.CHANNEL_BAIDU
#md5加密
def get_sign():
string=callback_url+akey
m=hashlib.md5()
m.update(string.encode("utf-8"))
return m.hexdigest()
sign=get_sign()
callback_url=callback_url+"&sign="+sign
data.update({"imei":data.pop("imei_MD5","")})
data.update({"callback":callback_url})
data.update({"appid":"baidu"})
success =lambda msg:{"ret":0,"failMsg":msg}
fail =lambda msg:{"ret":1,'failMsg':msg}
return data,success,fail
-- Deploy flipr:channelsinfo to mysql
BEGIN;
CREATE TABLE `promotioninfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`code` varchar(64) NOT NULL,
`sub_code` varchar(128) NOT NULL,
`platform` varchar(8) NOT NULL,
`appendtime` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
COMMIT;
-- Revert flipr:channelsinfo from mysql
BEGIN;
-- XXX Add DDLs here.
COMMIT;
[core]
engine = mysql
# plan_file = sqitch.plan
# top_dir = .
# [engine "mysql"]
# target = db:mysql:
# registry = sqitch
# client = mysql
%syntax-version=1.0.0
%project=flipr
%uri=https://github.com/sqitchers/sqitch-mysql-intro/
channelsinfo 2019-07-31T05:33:27Z gaomingming <apple@AppledeMacBook-Pro.local> # 创建渠道信息表.
-- Verify flipr:channelsinfo on mysql
BEGIN;
-- XXX Add verifications here.
ROLLBACK;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment