# Path: mod/models/library.py
# class LibraryHotCache(Base):
#     __tablename__ = 'library_hot'
#     id = Column(Integer,primary_key=True)
#     text = Column(String(4096), nullable=False)
#     date = Column(Integer, nullable=False)


from config import TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.library import LibraryHotCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import datetime
import tornado.gen
import urllib
import json, re,base64
# @Date    : 2016-03-14 17:34:57
# @Author  : jerry.liangj@qq.com

class HotHandler(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.web.asynchronous
    @tornado.gen.engine
    def post(self):
        HOT_URL = "http://www.libopac.seu.edu.cn:8080/top/top_lend.php"
        retjson = {
            'code':200,
            'content':''
        }
        try:
            status = self.db.query(LibraryHotCache).one()
            if status.date > int(time())-600000:
                self.write(base64.b64decode(status.text))
                self.db.close()
                self.finish()
                return
        except NoResultFound:

# Path: mod/models/library.py
# class LibraryHotCache(Base):
#     __tablename__ = 'library_hot'
#     id = Column(Integer,primary_key=True)
#     text = Column(String(4096), nullable=False)
#     date = Column(Integer, nullable=False)


# Path: mod/library/hothandler.py
from config import TIME_OUT
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.library import LibraryHotCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
import tornado.web
import datetime
import tornado.gen
import urllib
import json, re,base64

# @Date    : 2016-03-14 17:34:57
# @Author  : jerry.liangj@qq.com

class HotHandler(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.web.asynchronous
    @tornado.gen.engine
    def post(self):
        HOT_URL = "http://www.libopac.seu.edu.cn:8080/top/top_lend.php"
        retjson = {
            'code':200,
            'content':''
        }
        try:
            status = self.db.query(LibraryHotCache).one()
            if status.date > int(time())-600000:
                self.write(base64.b64decode(status.text))
                self.db.close()
                self.finish()
                return
        except NoResultFound:

            status = LibraryHotCache(text='*', date=int(time()))