2019-10-09 17:23:40 +08:00

234 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
from __future__ import absolute_import
"""
广告接口
get (返回广告明细) paramsgameidlocalidoutputad_title,ad_body,ad_image,jump_param
post新增广告定义 paramsname,gameid,localid,start_time,end_time,ad_nums,ad_title,ad_body,ad_image,jump_param,ad_sort,status=unapproved, output1,0
put更新广告配置paramsname,gameid,localid,start_time,end_time,ad_nums,ad_title,ad_body,ad_image,jump_param,ad_sortoutput1,0
delete删除定义的广告paramsoutput1,0
"""
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource
import logging
from ops.reflush_ad import rebuild_ad
# from myredis.myredis import ad_redis, expire_time
from mysql.mmysql import MysqlBase
from prod_config import mysql_promotion_config
import datetime
import pdb
log = logging.getLogger(__name__)
parser = reqparse.RequestParser()
parser.add_argument('id')
parser.add_argument('gameid')
parser.add_argument('channelid')
parser.add_argument('name')
parser.add_argument('locationid')
parser.add_argument('begin_time')
parser.add_argument('end_time')
parser.add_argument('ad_num')
parser.add_argument('ad_title')
parser.add_argument('ad_body')
parser.add_argument('ad_image')
parser.add_argument('jump_status')
parser.add_argument('ad_sort')
parser.add_argument('status')
parser.add_argument('companyid')
parser.add_argument('jump_param')
parser.add_argument('ad_property')
class Ad(Resource):
def __init__(self):
self.args = parser.parse_args()
self.mydb = MysqlBase(**mysql_promotion_config)
def get(self):
status = self.args['status']
id = self.args['id']
companyid = self.args['companyid']
gameid = self.args['gameid']
# if not gameid or not localid:
# # log.error(f"请输入必须的游戏ID和位置ID字段当前获得是{gameid},{localid}")
# return jsonify({'code': 500, "message": f"请输入必须的游戏ID和位置ID字段当前获得是{gameid},{localid},{status}"})
# now = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
if not id:
base_sql = """SELECT
id,
name,
begin_time,
end_time,
ad_num,
ad_title,
ad_body,
ad_image,
jump_param,
ad_sort,
status,
companyid,
locationid,
gameid,
channelid,
jump_status,
ad_property
FROM
ad
WHERE
in_used=1 """
if companyid:
sel_sql = f"{base_sql} and companyid={companyid}"
else:
sel_sql = f"{base_sql}"
if status:
sel_sql = f"{sel_sql} and status={status}"
if gameid:
sel_sql = f"{sel_sql} and gameid={gameid}"
else:
sel_sql = f"""select
id,
name,
begin_time,
end_time,
ad_num,
ad_title,
ad_body,
ad_image,
jump_param,
ad_sort,
status,
companyid,
locationid,
gameid,
channelid,
jump_status,
ad_property
from
ad
where
in_used=1
and id={id}; """
data = self.mydb.query(sel_sql)
#log.info(f"sql={sel_sql},data={data}")
if data:
all = []
try:
for line in data:
ad_info = {}
ad_info['id'], ad_info['name'], ad_info['begin_time'], ad_info['end_time'], ad_info['ad_num'], ad_info['ad_title'], ad_info['ad_body'], ad_info['ad_image'], ad_info['jump_param'], ad_info['ad_sort'], ad_info['status'], ad_info['companyid'], ad_info['locationid'], ad_info['gameid'], ad_info['channelid'], ad_info['jump_status'], ad_info['ad_property'] = line
all.append(ad_info)
return jsonify({'code': 200, 'message': all})
except Exception:
log.error("split data from mysql failed!", exc_info=True)
else:
return jsonify({'code': 200, 'message': []})
def post(self):
ad = {}
id = self.get_adid()
ad['id'] = id
ad['name'] = self.args['name']
ad['gameid'] = self.args['gameid']
ad['channelid'] = self.args['channelid']
ad['locationid'] = self.args['locationid']
ad['begin_time'] = self.args['begin_time'] or '1999-01-01'
ad['end_time'] = self.args['end_time'] or '3000-01-01'
ad['ad_num'] = self.args['ad_num'] or -1
ad['ad_title'] = self.args['ad_title']
ad['ad_body'] = self.args['ad_body']
ad['ad_image'] = self.args['ad_image']
ad['jump_param'] = self.args['jump_param']
ad['jump_status'] = self.args['jump_status']
ad['ad_sort'] = self.args['ad_sort'] or 0
ad['companyid'] = self.args['companyid']
ad['ad_property'] = self.args['ad_property']
# 检查必需有的字段
if not (
ad['name'] and ad['gameid'] and ad['locationid'] and ad['ad_image'] and ad['jump_status'] and ad['companyid']):
return jsonify({'code': 500, 'message': '一些必填项未提供'})
# 检查该广告是否已存在
try:
check_sql = f"select id from ad where name='{ad['name']}' and gameid={ad['gameid']} and \
locationid={ad['locationid']} and companyid=ad['companyid']"
data = self.mydb.query(check_sql)
if data:
return jsonify({'code': 500, 'message': f"name={ad['name']} gameid={ad['gameid']} was in db!"})
except Exception:
log.error(f"check new id in db failed!", exc_info=True)
return jsonify({'code': 500, 'message': 'check data in db failed!'})
try:
self.mydb.insert('ad', ad)
return jsonify({'code': 200, 'message': 'add adid={id} success!'})
except Exception:
log.error("Insert ad to mysql failed!", exc_info=True)
return jsonify({'code': 500, 'message': f'insert {id} failed! '})
def get_adid(self):
max_id = f"select id from ad order by id desc limit 1"
data = self.mydb.query(max_id)
try:
max = int(data[0][0]) + 1
log.info(f"max id was {max}!")
except Exception:
log.error(f"error with get ad id ", exc_info=True)
max = 1001
return max
def put(self):
try:
ad = {}
ad['id'] = self.args['id']
ad['name'] = self.args['name']
ad['gameid'] = self.args['gameid']
ad['channelid'] = self.args['channelid']
ad['locationid'] = self.args['locationid']
ad['begin_time'] = self.args['begin_time'] or '1999-01-01'
ad['end_time'] = self.args['end_time'] or '3000-01-01'
ad['ad_num'] = self.args['ad_num'] or -1
ad['ad_title'] = self.args['ad_title']
ad['ad_body'] = self.args['ad_body']
ad['ad_image'] = self.args['ad_image']
ad['jump_param'] = self.args['jump_param']
ad['ad_sort'] = self.args['ad_sort']
ad['status'] = self.args['status'] or 0
ad['companyid'] = self.args['companyid']
ad['jump_status'] = self.args['jump_status']
ad['ad_property'] = self.args['ad_property']
sel_sql = f"select name from ad where id={self.args['id']};"
data = self.mydb.query(sel_sql)
if data:
condition = f"id='{self.args['id']}'"
self.mydb.update("ad", ad, condition)
if rebuild_ad():
log.info(f"rebuild cache via ad change!")
return jsonify({'code': 200, 'message': 'update adid={id} success!'})
else:
return jsonify({'code': 500, 'message': 'rebuild cache failed!'})
else:
return jsonify({'code': 404, 'message': f"{self.args['id']} not found in mysql!"})
except Exception:
log.error("update values to ad mysql failed!", exc_info=True)
return jsonify({'code': 500})
def delete(self):
id = self.args['id'] or None
if not id:
return jsonify({'code': 404, 'message': f'{id} not found!'})
#del_sql = f"delete from ad where id={id};"
del_sql = f"update ad set in_used=0 where id={id};"
try:
self.mydb.change(del_sql)
return jsonify({'code': 200, 'message': f'remove adid={id} success!'})
except Exception:
log.error("remove id from ad failed!", exc_info=True)