示例#1
0
def back_system():
    # 超级后台
    # 管理操作:
    # 已注册的学校列表
    rtdata = {
        'success': 'yes',
        'msg': 'done',
        'code': 0,
        'data': None,
        'dlen': 0
    }
    if request.method == 'GET':
        system_code = request.args.get("syscode")
        if syscode != cur_config.system("syscode"):
            return abort(403)
        target = request.args.get("target")
        action = request.args.get("action")
        if target == 'schools':
            if action == 'list':
                rtdata['data'] = system.on_school("list")
        return json.dumps(rtdata)
示例#2
0
class capp_smsg(app_smsg):
    # smsg with cache
    cacheA_Mark = True
    cacherA = dict()
    cacherB = dict()
    cache = cacherA
    #cache_limit = 128 # just for an easy way
    cache_limit = cur_config.system('cache_size')
    cache_kicks = 32  # when full how many to kick
    cache_kickr = 0.5
    cache_array = [None] * cache_limit
    cpos = 0
    cache_dict_limit = 5  # user seperated dict cache

    clear_time = 1800
    switch_time = 3600
    last_time = time.time()
    stimer = None

    C_LOCK = False
    lock_wait = 0.1
    lock_wcount = 10

    @classmethod
    def cclear(cls):
        if cls.cacheA_Mark:
            # when cacher_a works... clear cacherB
            _ = cls.cacherB
        else:
            _ = cls.cacherA
        loger.info("600s and clear on cache: %s with len: %d" %
                   ('cacherB' if cls.cacheA_Mark else 'cacherA', len(_)))
        _.clear()

    @classmethod
    def via_cache(cls, cpath, force=False):
        # check for switch cache
        dt = time.time() - cls.last_time
        if dt > cls.switch_time:
            loger.info("time to switch cacher")
            cls.cacheA_Mark = not cls.cacheA_Mark
            cls.cache = cls.cacherA if cls.cacheA_Mark else cls.cacherB
            cls.cache_array = []
            cls.last_time = time.time()
            cls.stimer = Timer(cls.clear_time, cls.cclear)
            cls.stimer.start()
        # real job
        cpath = cls._xpath(cpath)
        if cpath in cls.cache:
            loger.info("%s in cache!" % cpath)
            if cls.C_LOCK is True:
                loger.debug("CHECK: wait for C_LOCK!")
                t = cls.lock_wcount
                while t > 0:
                    time.sleep(cls.lock_wait)
                    if cls.C_LOCK is False:
                        break
                    t -= 1
                loger.error("CHECK: wait for C_CLOCK over time!")
                return None
            cls.cache_array.remove(cpath)
            cls.cache_array.insert(0, cpath)
            return cls.cache[cpath]
        else:
            return None

    @classmethod
    def store_cache(cls, cpath, data):
        cpath = cls._xpath(cpath)
        loger.info("%s store into cache!" % cpath)
        if cls.cpos >= cls.cache_limit and cls.C_LOCK is False:
            loger.info("cache ups to limit! do short clear.")
            _times = min(cls.cache_kicks,
                         round(len(cls.cache) * cls.cache_kickr))
            cls.C_LOCK = True
            for x in xrange(_times):
                xpath = cls.cache_array.pop()
                try:
                    cls.cache.pop(xpath)
                except KeyError:
                    loger.warn("pop cache error with key: %s" % xpath)
                    continue
            cls.cpos = len(cls.cache) - 1
            cls.C_LOCK = False
        cls.cpos += 1
        loger.debug("cache size: %s!" % cls.cpos)
        cls.cache_array.append(cpath)
        cls.cache[cpath] = data
        return True

    @classmethod
    def clear_cache(cls, xurl):
        try:
            cls.cache.pop(xurl)
        except KeyError:
            return False
        cls.cpos -= 1
        return True

    @classmethod
    def _xpath(cls, opath):
        pstr = re.sub(r'&timestamp=.*?&', '&', opath)
        return pstr[:pstr.index('&sign')]

    # inject a cacher
    def __init__(self, mapname, baseurl='', postdata=None, posturl=''):
        # any thing?
        super(capp_smsg, self).__init__(mapname,
                                        baseurl='',
                                        postdata=None,
                                        posturl='')

    def get(self, filep='', urlpath='', json=True, force=False, viacache=True):
        purl = self.path + '?' + urlpath if urlpath else self.path_param_url
        print(purl)
        if not force:
            rt = self.__class__.via_cache(purl)
            if rt is not None:
                if json:
                    return self._rt_solve(rt)
                else:
                    return rt
        if self.con:
            #turl = purl.encode('utf8') if isinstance(purl, unicode) else purl.decode('gbk').encode('utf8')
            #turl = purl.encode('utf8')
            self.con.request('GET', purl)
            resp = self.con.getresponse()
            if resp.status == 200:
                if filep:
                    fo = None
                    try:
                        fo = open(filep, 'w+b')
                        fo.write(resp.read())
                    except:
                        self._url_file_save(purl, filep)
                    finally:
                        if fo:
                            fo.close()
                    loger.info('file save done')
                    return filep
                else:
                    #   perhaps get a file some...
                    rt = resp.read()
                    if not json:
                        return rt
                    rt_json = self._rt_solve(rt)
                    if viacache and rt_json['success']:
                        self.__class__.store_cache(purl, rt)
                    return rt_json
        else:
            raise RuntimeError('NO connection!')
示例#3
0
import json
import re
import time
from threading import Timer
from .message_sets import appmsg_sets, appmsg_sets2
from sys_config import cur_config, loger
from .campusApp2 import thirdsvr
from ultilities import json_flat_2_tree

# PYTHON3 ON Linux:
if sys.platform == 'linux':
    #Context = ssl.create_default_context()
    #Context = ssl._create_unverified_context()
    try:
        _crtpath = os.path.join(cur_config.folder("base_fd"),
                                cur_config.system("qqcrt"))
        Context = ssl.SSLContext(ssl.PROTOCOL_TLS)
        Context.check_hostname = False
        Context.load_verify_locations(_crtpath)
        print("create context OK!")
    except:
        print(_crtpath)
        Context = None
        ssl._create_default_https_context = ssl._create_unverified_context
else:
    Context = None
"""
https://www.cnblogs.com/lykbk/p/ASDFQAWQWEQWEQWEQWEQWEQWEQEWEQW.html
问题的原因是“SSL: CERTIFICATE_VERIFY_FAILED”。
Python 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书。
而当目标网站使用的是自签名的证书时就会抛出一个 urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)> 的错误消息,