import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from crontab import *
from controller import *
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
greeting = self.get_argument('greeting', 'Hello')
self.write(greeting + ', friendly user!')
def timeaction():
obj = testTime()
obj.start()
def timeaction2():
print 22222
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[(r"/", IndexHandler),(r'/api', api),])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
if options.port == 8888:
tornado.ioloop.PeriodicCallback(timeaction, 1000).start() # start scheduler
timeaction2()
tornado.ioloop.IOLoop.instance().start()
以上代码是tornado入口文件,路由规则定义以及定时任务第一编码
tornado文件目录
controller负责业务逻辑处理但不负责实现
import time
import sys
from baseHandler import baseHandler
from library import sql
import tasks
import json, hashlib, re
from library import sql
import log
class api(baseHandler):
token = "12eqw21a" #接口提供的token
def get(self):
print 'api get'
self.write('api')
#验证接口信息
def checkSign(self):
signature = self.get_argument('signature')
timestamp = self.get_argument('timestamp')
nonce = self.get_argument('nonce')
token = self.token
tmpArr = [token, timestamp, nonce]
tmpArr.sort()
str = "".join(tmpArr)
sstr = hashlib.sha1(str).hexdigest()
if sstr == signature:
return True
else:
return False
#接收post请求
def post(self):
#验证信息
'''
res = self.checkSign()
if not res:
dict = '{"State":1}'
self.write(dict)
'''
#保存推送信息
name = self.get_argument('type',)
dict = {'ctime': time.time(), 'json':self.request.body}
obj = sql()
obj.saveData('dai_api_log', dict)
name = self.get_argument('type',)
if hasattr(api, name):
getattr(self, name)()
dict = '{"State":1}'
self.write(dict)
else:
self.write('no')
def postapi(self):
data = self.request.body
log.debug('==__++++=================data:{0}'.format(data))
tasks.saveApiPost.apply_async(args=['post',data])
def commentapi(self):
data = self.request.body
tasks.saveApiComment.apply_async(args=['comment',data])
def messageapi(self):
data = self.request.body
obj = sql()
#log.debug('===================data:{0}'.format(data))
dict = {'name':'私信', 'params':data, 'ctime':time.time()}
obj.saveData('dai_lslog', dict)
j = json.loads(data)
if j['from_user'] == 1:
return
recipientId = j['recipient_user']
mes = obj.getData('dai_sq_user', where=" sqid=%d and userstatus =0 "%recipientId, type=0, field='userid')
if not mes:
return
tasks.saveApiMessage.apply_async(args=['message',data])
post(self):实现请求方法 getAttr(type)()
mytask负责代码实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, json
#from library import sql
from library import tsql
from functions import lslog
from model import pushModel
from functions import sqcurl, sqpush
from model import userModel
class reciveComment(object):
def __init__(self):
self.obj = tsql()
def saveApi(self, data):
j = json.loads(data)
post = j['CommentTopic']
comment = j['Comment']
if not (post.has_key('TopicId') and post['TopicId'] > 0):
return
#保存新用户发布的评论
self.saveNewUserComment(comment, post)
#保存后台用户的回复
#self.addsaveComment(comment, post)
#self.saveComment(comment, post)
if (self.saveComment(comment, post) != 1 ):
self.addsaveComment(comment, post)
#判读评论是否是对0评论的帖子进行回复
postid = post['TopicId']
self.issetNoCommentPost(postid)
def saveNewUserComment(self, comment, post):
userid = comment['UserID']
user = self.getUserInfo(userid)
if not user:
return
#判读用户是否是编辑小号
res = self.obj.getData('dai_sq_user', where=" sqid=%d"%int(userid), type=1)
if res:
return
regDate = user['RegDate']
#print regDate
regTime = time.mktime(time.strptime(regDate,'%Y-%m-%d'))
mtime = time.time()-3600*24*30
if regTime < mtime:
return
data = {'postid':post['TopicId'], 'commentid' : comment['CommentID'], 'userid':userid, 'username':comment['UserName'], 'content':comment['CommentText'], 'post_title':post['Memo'], 'siteid':comment['WebSiteID'], 'ctime':int(time.time()), 'floor': comment['Floors']}
data['reg_date'] = regDate
data['jifen'] = user['IntegralCount']
data['send_post'] = user['InfoCount']
precommentid = int(comment['PreCommentID'])
if precommentid > 0:
url = 'http://discuss.108sq.cn/API/AComment/CommentInfo?commentID=%d'%precommentid
info = sqcurl(url)
if not info:
return
info = json.loads(info)
data['rcontent'] = info['CommentContent']
self.obj.saveData('dai_recent_comment', data)
def saveComment(self, comment, post):
precommentid = int(comment['PreCommentID'])
#直保存回复的评论
if not precommentid > 0:
return
#查看是否是后台用户的评论
url = 'http://discuss.108sq.cn/API/AComment/CommentInfo?commentID=%d'%precommentid
info = sqcurl(url)
if not info:
return
info = json.loads(info)
if not info:
return
ruserid = info['UserID']
user = self.obj.getData('dai_sq_user', where="sqid = %d" %ruserid, type=1)
if not user:
return
uid = user['userid']
data = {'postid':post['TopicId'], 'commentid': comment['CommentID'], 'ruserid':ruserid, 'rusername':info['UserName'],'rcomment':info['CommentContent'], 'userid':comment['UserID'], 'username':comment['UserName'],'content':comment['CommentText'], 'post_title':post['Memo'], 'uid':uid, 'siteid':comment['WebSiteID'], 'ctime':int(time.time())}
self.obj.saveData('dai_api_comment', data)
#推送消息
#uid = 1
um = userModel()
um.insertUserNotice(uid ,5 ,'评论回复', comment['CommentID'])
sqpush(uid)
return 1
def addsaveComment(self, comment, post):
precommentid = int(comment['PreCommentID'])
if not precommentid <=0:
return
TopicUserName = post['TopicUserName']
if not TopicUserName:
return
user = self.obj.getData('dai_sq_user', where="username = '%s'" %TopicUserName, type=1)
if not user:
return
uid = user['userid']
ruserid=user['sqid']
rusername=user['username']
#recomment=comment['CommentContent']
data = {'postid':post['TopicId'], 'commentid': comment['CommentID'], 'ruserid':ruserid, 'rusername':rusername,'rcomment':'', 'userid':comment['UserID'], 'username':comment['UserName'],'content':comment['CommentText'], 'post_title':post['Memo'], 'uid':uid, 'siteid':comment['WebSiteID'], 'ctime':int(time.time())}
self.obj.saveData('dai_api_comment', data)
#推送消息
#uid = 1
um = userModel()
um.insertUserNotice(uid ,5 ,'评论回复', comment['CommentID'])
sqpush(uid)
#如果是对0评论的帖子进行回复,在0评论列表中删除这个帖子id
def issetNoCommentPost(self, postid):
obj = self.obj
table = 'dai_no_comment_post'
info = obj.getData(table , where = "postid = %d" %postid, type = 1)
if info:
try:
id = info['id']
obj.delData(table, 'id=%s' %id)
obj.delData('dai_push_log','other=%s and pid = 4' %info['postid'])
push = pushModel()
push.baseSitePushUser(info['siteid'])
except:
log = {'sql':obj.lastsql, 'info': json.dumps(info)}
lslog('评论异常', log)
else :
return
def getUserInfo(self, userid):
url = 'http://108sq.cn/Api/AppUserInfo?userID=%d&userName='%userid;
data = sqcurl(url)
try:
j = json.loads(data)
except:
j = {}
return j
function 公共方法