fix some error

This commit is contained in:
pengtao 2019-07-15 10:43:17 +08:00
parent c43cd11065
commit b92c3f1414
3 changed files with 190 additions and 77 deletions

83
ad_interface_tornado.py Normal file
View File

@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
import os
import json
import time
import hashlib
import urllib.request
import tornado.ioloop
import tornado.web
import tornado.ioloop
import tornado.web
import json
from myredis import myredis
import datetime
class Adlist(tornado.web.RequestHandler):
def post(self):
res = adlist_workflow(json.loads(self.request.body))
self.write(json.dumps(res))
def adlist_workflow(input):
gameid = input['gameid']
localid = input['localtionid']
key = f"{gameid}::{localid}"
result = myredis.hmgetall(key)
return result
def getDaySeconds(time_val, incdays):
time_zone = 8
return int((time_val + time_zone * 3600) / 3600 / 24 + incdays) * 3600 * 24 - 3600 * time_zone;
def send_cache_data():
now = datetime.datetime.today().strftime("%Y-%m-%d")
get_data_sql = "select "
def sendNotify(conf, sendtime):
try:
print('sendNotify start')
params = {'key': 'kingsome'}
secret = 'fc38349c5d084e920925e614c420be9f'
timestamp = time.time()
md5signstr = md5Sign(params, secret, timestamp)
url = conf['notify_url'] + '&timestamp=' + str(timestamp) + '&sign=' + md5signstr
req = urllib.request.Request(url)
data = urllib.request.urlopen(req).read()
print('sendNotify end')
except Exception as e:
print('sendNotifu error: ' + str(e))
# 进入下一次循环
tornado.ioloop.IOLoop.current().call_at(getDaySeconds(time.time(), 1) + sendtime,
lambda: sendNotify(conf, sendtime))
class SelfCheckingHandler(tornado.web.RequestHandler):
def get(self):
self.write(json.dumps({
'errcode': 0, 'errmsg': '', 'healthy': 1, 'max_rundelay': 10
}, separators=(',', ':')))
def make_app():
return tornado.web.Application([(r"/webapp/index[\.]php", SelfCheckingHandler), (r"/", hello),
])
if __name__ == "__main__":
print('start!')
conf = json.loads(open('../config/kefu_robot.json', 'r').read())
app = make_app()
app.listen(conf['listen_port'])
tornado.ioloop.IOLoop.current().call_at(getDaySeconds(time.time(), 1) + conf['sendtime1'],
lambda: sendNotify(conf, conf['sendtime1']))
tornado.ioloop.IOLoop.current().call_at(getDaySeconds(time.time(), 1) + conf['sendtime2'],
lambda: sendNotify(conf, conf['sendtime2']))
tornado.ioloop.IOLoop.current().start()

30
add_task_1min.py Normal file
View File

@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# -*- coding:utf-8 -*-
from tornado import web, ioloop
import datetime
import time
class MainHandler(web.RequestHandler):
def get(self):
self.write('Hello Kingsome, I am alive!')
def add_task():
# print '2s ', datetime.datetime.now()
time.sleep(2)
print(
"执行f2s")
def remove_task():
# print '5s ', datetime.datetime.now()
print(
"执行f5s")
if __name__ == '__main__':
application = web.Application([(r'/', MainHandler), ])
application.listen(8081)
ioloop.PeriodicCallback(add_task, 2000).start() # start scheduler 每隔2s执行一次f2s
ioloop.PeriodicCallback(remove_task, 5000).start() # start scheduler 每隔5s执行一次f5s
ioloop.IOLoop.instance().start()

View File

@ -24,84 +24,84 @@ class Location(Resource):
self.args = parser.parse_args() self.args = parser.parse_args()
def get(self): def get(self):
sql = f"select id,gameid,area,type from location where in_used=1;" sql = f"select id,gameid,area,type from location where in_used=1;"
try: try:
data = mydb.query(sql) data = mydb.query(sql)
except Exception: except Exception:
log.error("get data from location failed!", exc_info=True) log.error("get data from location failed!", exc_info=True)
return jsonify({'code': 500}) return jsonify({'code': 500})
all_data = [] all_data = []
log.debug(f"get data from localtion was {data}") log.debug(f"get data from localtion was {data}")
if data:
for line in data:
if line:
localtion = {}
localtion['id'], localtion['gameid'], localtion['area'], localtion['type'] = line
all_data.append(localtion)
del localtion
return jsonify({'code': 200, 'message': all_data})
else:
log.error(f"{data} not found in mysql !")
return jsonify({'code': 404})
def post(self):
try:
location = {}
location['gameid'] = self.args['gameid']
location['area'] = self.args['area']
location['type'] = self.args['type']
location['id'] = self.create_id()
mydb.insert("location", location)
except Exception:
log.error("set values to location mysql failed!", exc_info=True)
return jsonify({'code': 500})
return jsonify({'code': 200})
def create_id(self):
max_id = f"select id from location order by id desc limit 1"
data = mydb.query(max_id)
log.info(f"2 {data}")
try:
max = int(data[0][0]) + 1
log.info(f"max id was {max}!")
except Exception:
log.error(f"error with get location id ", exc_info=True)
max = 1001
return max
def put(self):
try:
location = {}
location['id'] = self.args['id']
location['gameid'] = self.args['gameid']
location['area'] = self.args['area']
location['type'] = self.args['type']
location['in_used'] = self.args['in_used'] or 0
sel_sql = f"select area from location where id={self.args['id']};"
data = mydb.query(sel_sql)
if data: if data:
condition = f"id='{self.args['id']}'" for line in data:
mydb.update("location", location, condition) if line:
return jsonify({'code': 200}) localtion = {}
localtion['id'], localtion['gameid'], localtion['area'], localtion['type'] = line
all_data.append(localtion)
del localtion
return jsonify({'code': 200, 'message': all_data})
else: else:
return jsonify({'code': 404, 'message': f"{self.args['id']} not found in mysql!"}) log.error(f"{data} not found in mysql !")
except Exception: return jsonify({'code': 404})
log.error("update values to location mysql failed!", exc_info=True)
return jsonify({'code': 500})
def delete(self): def post(self):
id = self.args['id'] try:
if not id: location = {}
return jsonify({'code': 500, 'message': 'id not found'}) location['gameid'] = self.args['gameid']
try: location['area'] = self.args['area']
del_sql = f'delete from location where id={id};' location['type'] = self.args['type']
mydb.query(del_sql) location['id'] = self.create_id()
except Exception: mydb.insert("location", location)
log.error(f"location remove {id} failed!", exc_info=True) except Exception:
return jsonify({'code': 500}) log.error("set values to location mysql failed!", exc_info=True)
return jsonify({'code': 200}) return jsonify({'code': 500})
return jsonify({'code': 200})
def create_id(self):
max_id = f"select id from location order by id desc limit 1"
data = mydb.query(max_id)
log.info(f"2 {data}")
try:
max = int(data[0][0]) + 1
log.info(f"max id was {max}!")
except Exception:
log.error(f"error with get location id ", exc_info=True)
max = 1001
return max
def put(self):
try:
location = {}
location['id'] = self.args['id']
location['gameid'] = self.args['gameid']
location['area'] = self.args['area']
location['type'] = self.args['type']
location['in_used'] = self.args['in_used'] or 0
sel_sql = f"select area from location where id={self.args['id']};"
data = mydb.query(sel_sql)
if data:
condition = f"id='{self.args['id']}'"
mydb.update("location", location, condition)
return jsonify({'code': 200})
else:
return jsonify({'code': 404, 'message': f"{self.args['id']} not found in mysql!"})
except Exception:
log.error("update values to location mysql failed!", exc_info=True)
return jsonify({'code': 500})
def delete(self):
id = self.args['id']
if not id:
return jsonify({'code': 500, 'message': 'id not found'})
try:
del_sql = f'delete from location where id={id};'
mydb.query(del_sql)
except Exception:
log.error(f"location remove {id} failed!", exc_info=True)
return jsonify({'code': 500})
return jsonify({'code': 200})