示例#1
0
文件: handler.py 项目: BSlience/local
	def post(self):

		filepath = ''.join(self.request.arguments['filepath'])
		timestamp = ''.join(self.request.arguments['timestamp'])
		secret = ''.join(self.request.arguments['secret'])
		
		key = filepath + timestamp
		secret_key = sha1(key).hexdigest()
		
		if secret == secret_key:
			doit = Doit()
			doit.transcode(filepath)
			print filepath
示例#2
0
	def post(self):

		for i in range(1):
			LOG.info('API IN[%s]' % (self.__class__.__name__))
                        LOG.info('PARAMETER IN[%s]' % self.request.arguments)

                        ret = {'code':'','message':''}
			essential_keys = set(['filepath','timestamp','secret'])

			if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
				ret['code'] = 1
				ret['message'] = 'invalid parameter'
				LOG.error('ERROR[in parameter invalid]')
				break
			
			filepath = ''.join(self.request.arguments['filepath'])
			timestamp = ''.join(self.request.arguments['timestamp'])
			secret = ''.join(self.request.arguments['secret'])

			if Base.empty(filepath) or Base.empty(timestamp) or Base.empty(secret):
					ret['code'] = 1
					ret['message'] = 'invalid parameter'
					LOG.error('ERROR[parameter empty]')
					break
			
			key = filepath + timestamp
			secret_key = sha1(key).hexdigest()
			
			if secret == secret_key:
				doit = Doit()
				doit.transcode(filepath)
				LOG.info('QUEUE[put transcode task(%s)}' % filepath)

				ret['code'] = 0
				ret['message'] = 'success'
				break
                        else:
                                ret['code'] = 4
                                ret['message'] = 'secure key error'
                                LOG.error('ERR[secure key error]')
                                break

                self.write(json.dumps(ret))
                LOG.info('PARAMETER OUT[%s]' % ret)
                LOG.info('API OUT[%s]' % (self.__class__.__name__))
示例#3
0
	def load():

		configer = Configer('../config.ini')

		log_info = configer.get_configer('LOG','info')
		log_path = configer.get_configer('LOG','path')
		log_format = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s'

		logger = Logger(info = log_info,path = log_path,format = log_format)
		LOG = logger.get_logger()

		doit = Doit()
示例#4
0
文件: rest.py 项目: LeoAlioth/do.it
import json
import context
from doit import Doit
doit = Doit()

from flask import Flask, jsonify, request
app = Flask(__name__)


@app.errorhandler
def error404():
    return json.dumps({
        "status": 404,
        "data": [],
        "error": "Page not found!"
    }), 404


@app.route("/api/modules", methods=["GET"])
def get_modules():
    data = doit.get_modules()
    return jsonify(data), data["status"]


@app.route("/api/modules/<int:mid>", methods=["GET"])
def get_module(mid=-1):
    data = doit.get_module(mid)
    return jsonify(data), data["status"]


@app.route("/api/modules/<int:mid>/<cmd>", methods=["GET"])
示例#5
0
    def post(self):

        for i in range(1):

            self.set_header("Access-Control-Allow-Origin", "*")

            LOG.info('API IN[%s]' % (self.__class__.__name__))
            LOG.info('PARAMETER IN[%s]' % self.request.arguments)

            ret = {'code': '', 'message': ''}

            essential_keys = set([
                'json', 'html', 'topic', 'level', 'type', 'group', 'chapter',
                'ref'
            ])

            if Base.check_parameter(set(self.request.arguments.keys()),
                                    essential_keys):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERR[in parameter invalid]')
                break

            question_json = ''.join(self.request.arguments['json'])
            question_html = ''.join(self.request.arguments['html'])
            question_topic = ''.join(self.request.arguments['topic'])
            question_level = ''.join(self.request.arguments['level'])
            question_type = ''.join(self.request.arguments['type'])
            question_group = ''.join(self.request.arguments['group'])
            question_chapter = ''.join(self.request.arguments['chapter'])
            ref = ''.join(self.request.arguments['ref'])

            if Business.is_level(question_level) is False:
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERR[level is invalid]')
                break

            try:
                #question_json = urllib.unquote(question_json)
                #question_json = question_json.replace("'","\"")
                encode_json = json.loads(question_json, encoding='utf-8')
                #question_html = urllib.unquote(question_html)
                #question_html = question_html.replace("'","\"")
                encode_html = json.loads(question_html, encoding='utf-8')

                LOG.info('Json Loads Successful')
                answer_num = 0

                if Base.empty(question_topic) and Base.empty(question_chapter):
                    ret['code'] = 1
                    ret['message'] = '无效参数'
                    LOG.error('ERR[topic and chapter empty]')
                    break

                if Base.empty(question_group):
                    ret['code'] = 1
                    ret['message'] = '无效参数'
                    LOG.error('ERR[group empty]')
                    break

                if Base.empty(question_topic) is False:
                    topic_list = question_topic.split(',')

                    for question_theme in topic_list:
                        if Business.is_topic(question_theme) is False:
                            ret['code'] = 1
                            ret['message'] = '无效参数'
                            LOG.error('ERR[topic %s invalid]' % question_theme)
                            break

                type_name = Business.is_type(question_type)

                if type_name is False:
                    ret['code'] = 1
                    ret['message'] = '无效参数'
                    LOG.error('ERR[type is invalid]')
                    break

                option_num = 0

                LOG.info('Json Parse Start')

                if type_name == '选择题'.decode('utf-8'):
                    if 'answer' in encode_json.keys():
                        answer_num = len(encode_json['answer'])
                        option_num = len(encode_json['options'])

                if type_name == '填空题'.decode('utf-8'):
                    if 'answer' in encode_json.keys():
                        answer_num = max([
                            int(group['index'])
                            for group in encode_json['answer']
                        ])

                LOG.info('Json Parse End')

                if not Base.empty(question_chapter):
                    if Business.chapter_id_exist(question_chapter) is False:
                        ret['code'] = 1
                        ret['message'] = '无效参数'
                        LOG.error('ERR[seriess %s invalid]' % question_theme)
                        break
            except (ValueError, KeyError, TypeError):
                ret['code'] = 1
                ret['message'] = '无效参数'
                LOG.error('ERR[json format invalid]')
                break

            except CKException:
                ret['code'] = 3
                ret['message'] = '服务器错误'
                LOG.error('ERR[mysql exception]')
                break

            key = question_topic + question_level + question_type + question_group
            secret_key = hashlib.sha1(key).hexdigest()

            qiniu = QiniuWrap()

            json_key = 'tmp_' + secret_key + '.json'
            if not qiniu.upload_data("temp", json_key, question_json):
                ret['code'] = 4
                ret['message'] = '服务器错误'
                LOG.error('ERR[json upload  qiniu exception]')
                break

            html_key = 'tmp_' + secret_key + '.html'
            if not qiniu.upload_data("temp", html_key, question_html):
                ret['code'] = 4
                ret['message'] = '服务器错误'
                LOG.error('ERR[html upload  qiniu exception]')
                break

            configer = Configer()
            remote_host = configer.get_configer('REMOTE', 'host')
            remote_port = configer.get_configer('REMOTE', 'port')
            remote_uri = configer.get_configer('REMOTE', 'uri')
            remote_timeout = configer.get_configer('REMOTE', 'timeout')

            remote_url = "http://%s:%s/%s" % (remote_host, remote_port,
                                              remote_uri)

            token = self.get_cookie("teacher_id")
            LOG.info('TOKEN[%s]' % token)

            if token is None:
                ret['code'] = 6
                ret['message'] = 'token失效'
                LOG.error('ERROR[token empty]')
                break

            post_data = {'token': token}

            client = httpclient.AsyncHTTPClient()
            response = yield gen.Task(client.fetch,
                                      remote_url,
                                      request_timeout=int(remote_timeout),
                                      method='POST',
                                      body=urllib.urlencode(post_data))
            #response = Http.post(remote_url,post_data)

            if 200 == response.code:
                encode_body = json.loads(response.body, encoding='utf-8')

                if 0 == encode_body['code'] or 2 == encode_body['code']:
                    ret['code'] = 7
                    ret['message'] = 'token失效'
                    LOG.error('ERR[token not exist]')
                    break

                if 1 == encode_body['code']:
                    subject_id = encode_body['subject_id']
                    grade_id = encode_body['grade_id']
                    system_id = encode_body['system_id']
                    org_type = encode_body['org_type']

                    if 0 != int(question_group):
                        if Business.group_id_exist(question_group,
                                                   system_id) is False:
                            ret['code'] = 8
                            ret['message'] = '无效参数'
                            LOG.error('ERROR[group not exist]')
                            break

                    db = Mysql()

                    question_sql = "insert into entity_question (difficulty,question_docx,html,upload_time,update_time,question_type,subject_id,new_format,upload_id,upload_src,question_group,grade_id,state,is_single,question_type_id,answer_num,count_ref,paper_year,parent_question_id,count_options) values (%(level)d,'%(json)s','%(html)s',now(),now(),'%(type)s',%(subject_id)d,1,%(upload_id)d,%(upload_src)d,%(question_group)d,%(grade_id)d,'ENABLED',1,%(question_type_id)d,%(answer_num)d,0,0,0,%(count_options)d);"

                    link_topic_sql = "insert into link_question_topic (question_id,topic_id) values (%(q_id)d,%(t_id)d);"

                    link_chapter_sql = "insert into link_question_chapter (question_id,chapter_id) values (%(q_id)d,%(c_id)d);"

                    try:
                        db.connect_master()
                        db.start_event()

                        question_res = db.exec_event(
                            question_sql,
                            level=int(question_level),
                            json=json_key,
                            html=html_key,
                            type=type_name,
                            subject_id=int(subject_id),
                            upload_id=int(system_id),
                            upload_src=int(org_type),
                            question_group=int(question_group),
                            grade_id=int(grade_id),
                            question_type_id=int(question_type),
                            answer_num=answer_num,
                            count_options=option_num)
                        question_sql = db.get_last_sql()
                        question_id = db.get_last_id()
                        LOG.info('RES[%s] - INS[%d]' %
                                 (question_res, question_id))

                        if Base.empty(question_topic) is False:
                            topic_list = question_topic.split(',')
                            for question_theme in topic_list:
                                topic_res = db.exec_event(
                                    link_topic_sql,
                                    q_id=int(question_id),
                                    t_id=int(question_theme))
                                topic_sql = db.get_last_sql()
                                topic_id = db.get_last_id()
                                LOG.info('RES[%s] - INS[%d]' %
                                         (topic_res, topic_id))

                        if not Base.empty(question_chapter):
                            chapter_res = db.exec_event(
                                link_chapter_sql,
                                q_id=int(question_id),
                                c_id=int(question_chapter))
                            chapter_sql = db.get_last_sql()
                            chapter_id = db.get_last_id()
                            LOG.info('RES[%s] - INS[%d]' %
                                     (chapter_res, chapter_id))

                    except DBException as e:
                        db.rollback()
                        db.end_event()
                        ret['code'] = 3
                        ret['message'] = '服务器错误'
                        LOG.error('ERR[insert mysql error]')
                        break

            else:
                ret['code'] = 3
                ret['message'] = '服务器错误'
                LOG.error('ERROR[remote error]')
                break

            mongo = Mongo()

            try:
                mongo.connect('resource')
                mongo.select_collection('mongo_question_json')
                json_id = mongo.insert_one({
                    "content": encode_json,
                    "question_id": question_id
                })
                LOG.info(
                    'MONGO[insert json] - DATA[%s] - INS[%s] - Question Id[%d]'
                    % (json.dumps(encode_json), json_id, question_id))

                mongo.select_collection('mongo_question_html')
                html_id = mongo.insert_one({
                    "content": encode_html,
                    "question_id": question_id
                })
                LOG.info(
                    'MONGO[insert html] - DATA[%s] - INS[%s] - Question Id[%d]'
                    % (json.dumps(encode_html), html_id, question_id))

            except DBException as e:
                db.rollback()
                db.end_event()
                ret['code'] = 3
                ret['message'] = '服务器错误'
                LOG.error('ERR[mongo exception]')
                break

            db.end_event()

            if int(ref):
                doit = Doit()
                doit.local_img(str(question_id))
                LOG.info('Local Img [%s]' % str(question_id))

            ret['code'] = 0
            ret['message'] = 'success'
            ret['id'] = question_id

        LOG.info('PARAMETER OUT[%s]' % ret)
        LOG.info('API OUT[%s]' % (self.__class__.__name__))
        self.write(json.dumps(ret))
        self.finish()
示例#6
0
	def post(self):
		
		for i in range(1):

			self.set_header("Access-Control-Allow-Origin", "*")

			LOG.info('API IN[%s]' % (self.__class__.__name__))
			LOG.info('PARAMETER IN[%s]' % self.request.arguments)
			
			ret = {'code':'','message':''}

			essential_keys = set(['json','html','topic','level','type','group','chapter','ref'])

			if Base.check_parameter(set(self.request.arguments.keys()),essential_keys):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[in parameter invalid]') 
				break

			question_json = ''.join(self.request.arguments['json'])
			question_html = ''.join(self.request.arguments['html'])
			question_topic = ''.join(self.request.arguments['topic'])
			question_level = ''.join(self.request.arguments['level'])
			question_type = ''.join(self.request.arguments['type'])
			question_group = ''.join(self.request.arguments['group'])
			question_chapter = ''.join(self.request.arguments['chapter'])
			ref = ''.join(self.request.arguments['ref'])


			if Business.is_level(question_level) is False:
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[level is invalid]') 
				break

			try:
				#question_json = urllib.unquote(question_json)
				#question_json = question_json.replace("'","\"")
				encode_json = json.loads(question_json,encoding = 'utf-8')
				#question_html = urllib.unquote(question_html)
				#question_html = question_html.replace("'","\"")
				encode_html = json.loads(question_html,encoding = 'utf-8')

				LOG.info('Json Loads Successful')
				answer_num = 0
				
				if Base.empty(question_topic) and Base.empty(question_chapter):
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[topic and chapter empty]') 
					break

				if Base.empty(question_group):
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[group empty]') 
					break

				if Base.empty(question_topic) is False:
					topic_list = question_topic.split(',')

					for question_theme in topic_list:
						if Business.is_topic(question_theme) is False:
							ret['code'] = 1
							ret['message'] = '无效参数'
							LOG.error('ERR[topic %s invalid]' % question_theme) 
							break

				type_name =  Business.is_type(question_type)

				if type_name is False:
					ret['code'] = 1
					ret['message'] = '无效参数'
					LOG.error('ERR[type is invalid]') 
					break

				option_num = 0

				LOG.info('Json Parse Start')

				if type_name == '选择题'.decode('utf-8'):
					if 'answer' in encode_json.keys():
						answer_num = len(encode_json['answer'])
						option_num = len(encode_json['options'])

				if type_name == '填空题'.decode('utf-8'):
					if 'answer' in encode_json.keys():
							answer_num = max([int(group['index']) for group in encode_json['answer']])
				
				LOG.info('Json Parse End')

				if not Base.empty(question_chapter):
					if Business.chapter_id_exist(question_chapter) is False:
						ret['code'] = 1
						ret['message'] = '无效参数'
						LOG.error('ERR[seriess %s invalid]' % question_theme) 
						break
			except (ValueError,KeyError,TypeError):
				ret['code'] = 1
				ret['message'] = '无效参数'
				LOG.error('ERR[json format invalid]') 
				break

			except CKException: 
				ret['code'] = 3
				ret['message'] = '服务器错误'
				LOG.error('ERR[mysql exception]') 
				break

			key = question_topic + question_level + question_type + question_group
			secret_key = hashlib.sha1(key).hexdigest()

			qiniu = QiniuWrap()

			json_key = 'tmp_' + secret_key + '.json'
			if not qiniu.upload_data("temp",json_key,question_json):
				ret['code'] = 4
				ret['message'] = '服务器错误'
				LOG.error('ERR[json upload  qiniu exception]') 
				break
			
			html_key = 'tmp_' + secret_key + '.html'
			if not qiniu.upload_data("temp",html_key,question_html):
				ret['code'] = 4
				ret['message'] = '服务器错误'
				LOG.error('ERR[html upload  qiniu exception]') 
				break

			configer = Configer()
			remote_host = configer.get_configer('REMOTE','host')
			remote_port = configer.get_configer('REMOTE','port')
			remote_uri = configer.get_configer('REMOTE','uri')
			remote_timeout = configer.get_configer('REMOTE','timeout')
			
			remote_url = "http://%s:%s/%s" % (remote_host,remote_port,remote_uri)

			token = self.get_cookie("teacher_id")
			LOG.info('TOKEN[%s]' % token)

			if token is None:
				ret['code'] = 6
				ret['message'] = 'token失效'
				LOG.error('ERROR[token empty]')
				break

			post_data = {'token' : token}

			client = httpclient.AsyncHTTPClient()
			response = yield gen.Task(client.fetch,remote_url,request_timeout = int(remote_timeout),method = 'POST',body = urllib.urlencode(post_data
))
			#response = Http.post(remote_url,post_data)

			if 200 == response.code:
				encode_body = json.loads(response.body,encoding = 'utf-8')

				if 0 == encode_body['code'] or 2 == encode_body['code']:
					ret['code'] = 7
					ret['message'] = 'token失效'
					LOG.error('ERR[token not exist]')
					break

				if 1 == encode_body['code']:
					subject_id = encode_body['subject_id']
					grade_id = encode_body['grade_id']
					system_id = encode_body['system_id']
					org_type = encode_body['org_type']


					if 0 != int(question_group):
						if Business.group_id_exist(question_group,system_id) is False:
							ret['code'] = 8
							ret['message'] = '无效参数'
							LOG.error('ERROR[group not exist]')
							break	

					db = Mysql()

					question_sql = "insert into entity_question (difficulty,question_docx,html,upload_time,update_time,question_type,subject_id,new_format,upload_id,upload_src,question_group,grade_id,state,is_single,question_type_id,answer_num,count_ref,paper_year,parent_question_id,count_options) values (%(level)d,'%(json)s','%(html)s',now(),now(),'%(type)s',%(subject_id)d,1,%(upload_id)d,%(upload_src)d,%(question_group)d,%(grade_id)d,'ENABLED',1,%(question_type_id)d,%(answer_num)d,0,0,0,%(count_options)d);"
					
					link_topic_sql = "insert into link_question_topic (question_id,topic_id) values (%(q_id)d,%(t_id)d);"

					link_chapter_sql = "insert into link_question_chapter (question_id,chapter_id) values (%(q_id)d,%(c_id)d);"

					try:
						db.connect_master()
						db.start_event()

						question_res = db.exec_event(question_sql,level = int(question_level),json = json_key,html = html_key,type = type_name,subject_id = int(subject_id),upload_id = int(system_id),upload_src = int(org_type),question_group = int(question_group),grade_id = int(grade_id),question_type_id = int(question_type),answer_num = answer_num,count_options = option_num)
						question_sql = db.get_last_sql()
						question_id = db.get_last_id()
						LOG.info('RES[%s] - INS[%d]' % (question_res,question_id))
				
						if Base.empty(question_topic) is False:
							topic_list = question_topic.split(',')
							for question_theme in topic_list:
								topic_res = db.exec_event(link_topic_sql,q_id = int(question_id),t_id = int(question_theme))
								topic_sql = db.get_last_sql()
								topic_id = db.get_last_id()
								LOG.info('RES[%s] - INS[%d]' % (topic_res,topic_id))

						if not Base.empty(question_chapter):
							chapter_res = db.exec_event(link_chapter_sql,q_id = int(question_id),c_id = int(question_chapter))
							chapter_sql = db.get_last_sql()
							chapter_id = db.get_last_id()
							LOG.info('RES[%s] - INS[%d]' % (chapter_res,chapter_id))
						
					except DBException as e:
						db.rollback()
						db.end_event()
						ret['code'] = 3
						ret['message'] = '服务器错误'
						LOG.error('ERR[insert mysql error]') 
						break

			else:
				ret['code'] = 3
				ret['message'] = '服务器错误'
				LOG.error('ERROR[remote error]')
				break
							
			mongo = Mongo()

			try:
				mongo.connect('resource')
				mongo.select_collection('mongo_question_json')
				json_id = mongo.insert_one({"content":encode_json,"question_id":question_id})
				LOG.info('MONGO[insert json] - DATA[%s] - INS[%s] - Question Id[%d]' % (json.dumps(encode_json),json_id,question_id))

				mongo.select_collection('mongo_question_html')
				html_id = mongo.insert_one({"content":encode_html,"question_id":question_id})
				LOG.info('MONGO[insert html] - DATA[%s] - INS[%s] - Question Id[%d]' % (json.dumps(encode_html),html_id,question_id))

			except DBException as e:
				db.rollback()
				db.end_event()
				ret['code'] = 3 
				ret['message'] = '服务器错误'
				LOG.error('ERR[mongo exception]') 
				break

			db.end_event()

			if int(ref):
				doit = Doit()
				doit.local_img(str(question_id))
				LOG.info('Local Img [%s]' % str(question_id))

			ret['code'] = 0
			ret['message'] = 'success'
			ret['id'] = question_id

		LOG.info('PARAMETER OUT[%s]' % ret)
		LOG.info('API OUT[%s]' % (self.__class__.__name__))
		self.write(json.dumps(ret))
		self.finish()