# Path: mod/_config.py

# 
# Path: mod/models/exam_cache.py
# class ExamCache(Base):
#     __tablename__ = 'exam'
#     cardnum = Column(Integer, primary_key=True)
#     text = Column(String(4096), nullable=False)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


from .._config import examCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..models.exam_cache import ExamCache
from time import time,localtime, strftime
from PIL import Image
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64,traceback,urllib
import io
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-12-3 12:46:36
# @Author  : jerry.liangj@qq.com


class ExamHandler(tornado.web.RequestHandler):

    @property
    def db(self):
        return self.application.db
    def on_finish(self):
        self.db.close()

    def get(self):
        self.write('Herald Web Service')

    @tornado.gen.engine
    def post(self):
        number = self.get_argument('cardnum',default=None)
        password = self.get_argument('password')
        retjson = {'code':200, 'content':''}
        # read from cache
        try:
            status = self.db.query(ExamCache).filter(ExamCache.cardnum == number).one()
            if status.date > int(time())-examCacheTime and status.text != '*':
                self.write(base64.b64decode(status.text))
                self.finish()
                return
        except NoResultFound:

# Path: mod/_config.py

# 
# Path: mod/models/exam_cache.py
# class ExamCache(Base):
#     __tablename__ = 'exam'
#     cardnum = Column(Integer, primary_key=True)
#     text = Column(String(4096), nullable=False)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


# Path: mod/exam/handler.py
from .._config import examCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from ..models.exam_cache import ExamCache
from time import time,localtime, strftime
from PIL import Image
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import json, base64,traceback,urllib
import io

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-12-3 12:46:36
# @Author  : jerry.liangj@qq.com


class ExamHandler(tornado.web.RequestHandler):

    @property
    def db(self):
        return self.application.db
    def on_finish(self):
        self.db.close()

    def get(self):
        self.write('Herald Web Service')

    @tornado.gen.engine
    def post(self):
        number = self.get_argument('cardnum',default=None)
        password = self.get_argument('password')
        retjson = {'code':200, 'content':''}
        # read from cache
        try:
            status = self.db.query(ExamCache).filter(ExamCache.cardnum == number).one()
            if status.date > int(time())-examCacheTime and status.text != '*':
                self.write(base64.b64decode(status.text))
                self.finish()
                return
        except NoResultFound:

            status = ExamCache(cardnum = number,text = '*',date = int(time()))