Python models 模块,Session() 实例源码

我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用models.Session()

项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def id_cancel(id):
    session = models.Session()
    qkou = session.query(models.Cancel)
    try:
        cancel_info = qkou.filter(models.Cancel.id == id).first()
        if cancel_info is not None:
            return cancel_info
        else:
            return 0
    except Exception as e:
        log.exception(e)
        return False
    finally:
        session.close()


# ?????????????????????
项目:jarvis    作者:whittlbc    | 项目源码 | 文件源码
def signup():
    email, pw = strip_creds_from_req(request.data)

    if not email or not pw:
        return rh.error(**ec.INCOMPLETE_LOGIN_CREDS)

    user = find(User, dict(email=email))
    if user: return rh.error(**ec.EMAIL_TAKEN)

    try:
        user = create(User, dict(email=email, password=pw))
        session = create(Session, dict(user_id=user.id))
        return rh.json_response(with_cookie=(cookie_name, session.token))
    except Exception as e:
        app.logger.error('Error signing up new user with email: {}, with error: {}'.format(email, e))
        return rh.error(**ec.USER_SIGNUP_ERROR)
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def add_news(update, detail, link, unique_hash):
    session = models.Session()
    qkou = session.query(models.News)
    # utf-8?????????????
    update = update.encode('utf-8')
    detail = detail.encode('utf-8')
    unique_hash = unique_hash.encode('utf-8')
    if len(link) is not 0:
        link = link.encode('utf-8')
    newinfo = models.News(update, detail, link, unique_hash, settings.now)
    try:
        ex_info = qkou.filter(models.News.unique_hash == unique_hash).first()
        if ex_info is None:
            # ?????
            log.debug('News: %s %s … [??]', update, detail[0:10])
            session.add(newinfo)
            session.commit()
            new_id = newinfo.id
            return new_id
        else:
            # ?????
            log.debug('News: %s %s … [??]', update, detail[0:10])
            ex_info.up_time = settings.now
            session.commit()
            return False
    except Exception as e:
        log.exception(e)
        return False
    finally:
        session.close()
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def del_old_news():
    session = models.Session()
    qkou = session.query(models.News)
    yday = settings.now - datetime.timedelta(days=1)
    try:
        qkou.filter(models.News.up_time < yday).delete()
        session.commit()
        log.debug('[ GetNewsThread ] ?????%s???????????', yday)
    except Exception as e:
        log.exception(e)
    finally:
        session.close()
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def id_news(id):
    session = models.Session()
    qkou = session.query(models.News)
    try:
        news_info = qkou.filter(models.News.id == id).first()
        if news_info is not None:
            return news_info
        else:
            return 0
    except Exception as e:
        log.exception(e)
        return False
    finally:
        session.close()
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def add_cancel(subject, teacher, day, week, period, abstract, first, unique_hash):
    session = models.Session()
    qkou = session.query(models.Cancel)
    # utf-8?????????????
    subject = subject.encode('utf-8')
    teacher = teacher.encode('utf-8')
    day = day.encode('utf-8')
    week = week.encode('utf-8')
    period = period.encode('utf-8')
    abstract = abstract.encode('utf-8')
    first = first.encode('utf-8')
    unique_hash = unique_hash.encode('utf-8')
    newcancel = models.Cancel(
        subject, teacher, day, week, period, abstract, first, unique_hash, now)
    try:
        ex_cancel = qkou.filter(
            models.Cancel.unique_hash == unique_hash).first()
        if ex_cancel is None:
            # ?????
            log.debug('???: %s … [??]', subject)
            session.add(newcancel)
            session.commit()
            new_id = newcancel.id
            return new_id
        else:
            # ?????
            log.debug('???: %s … [??]', subject)
            # ???????????????
            ex_cancel.up_time = now
            session.commit()
            return False
    except Exception as e:
        session.rollback()
        log.exception(e)
        return False
    finally:
        session.close()
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def todayinfo(day):
    infolist = []
    session = models.Session()
    for info in session.query(models.Cancel).filter(models.Cancel.day == day).all():
        infolist.append(info.subject)
    session.close()
    return infolist
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def del_old_info():
    session = models.Session()
    qkou = session.query(models.Info)
    yday = now - datetime.timedelta(days=1)
    try:
        qkou.filter(models.Info.up_time < yday).delete()
        session.commit()
        log.debug('[ GetInfoThread ] ?????%s???????????', yday)
    except Exception as e:
        log.exception(e)
    finally:
        session.close()
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def id_info(id):
    session = models.Session()
    qkou = session.query(models.Info)
    try:
        lecture_info = qkou.filter(models.Info.id == id).first()
        if lecture_info is not None:
            return lecture_info
        else:
            return 0
    except Exception as e:
        log.exception(e)
        return False
    finally:
        session.close()
项目:kokkuri    作者:LiGhT1EsS    | 项目源码 | 文件源码
def __make_pots_thread(self):

        db_session = Session()

        while not self._exit_flag:
            if self.evil_task_queue.empty():
                time.sleep(5)
            evil_ip = self.evil_task_queue.get()
            logger.info("Get An Evil IP: {0}".format(evil_ip))

            for ip in evil_ip:

                # ????attacker ip???????????
                qs = db_session.query(KokkuriSSHPot).filter(KokkuriSSHPot.attacker_ip == ip).first()
                if qs:
                    continue

                container_name = "{0}_honeypot".format(ip.replace(".", "_"))
                container_id, ssh_port = self.docker_pot.create_container(container_name)

                qs = KokkuriSSHPot(
                    container_name=container_name, container_id=container_id,
                    pot_ip=server_config.HONEYPOT_IP, attacker_ip=ip, ssh_port=ssh_port, status=1
                )

                db_session.add(qs)
                db_session.commit()
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def test_initialize(self):
        session = Session(self.session_store)
        assert isinstance(session.session_id, str)

        sid = 'test'
        session = Session(self.session_store, sid)
        assert session.session_id == sid
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def test_save(self):
        session = Session(self.session_store)
        sid = session.session_id
        session.data['twitter_id'] = '123123123'
        session.save()

        session = Session(self.session_store, sid)

        assert session.data['twitter_id'] == '123123123'
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def test_delete(self):
        session = Session(self.session_store)
        pass
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def get_current_user(self):
        sid = self.get_secure_cookie("sid")
        if not sid:
            return None
        sid = sid.decode('utf-8')
        session = Session(self.application.session_store, sid)
        if not session.data:
            return None
        if session.data.get('twitter_id'):
            user = User.get(twitter_id=session.data['twitter_id'])
        else:
            return None

        return user
        # return tornado.escape.json_decode(sid)
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def save_current_user(self, user):
        session = Session(self.application.session_store)
        session.data = user.fields()
        session.save()
        self.set_secure_cookie("sid", session.session_id)
项目:reversi-ai-place    作者:naari3    | 项目源码 | 文件源码
def save_current_user(self, user):
        session = Session(self.application.session_store)
        session.data = user.fields()
        session.save()
        self.set_secure_cookie("sid", session.session_id)
项目:opennumber    作者:opennumber    | 项目源码 | 文件源码
def get_user_id_rank(cls, phone):
        """
        ???phone???????????
        """

        with models.Session() as session:
            day = datetime.date.today()
            model = PhoneCheckLogModel
            count = session.query(func.count(distinct(model.user_id))).filter(model.phone==phone, model.create_datetime>=day).first()[0]

            rank = cls.user_id_rank_map.get_rank(count)
            logger.debug("phone access user_id count: %s at %s, rank: %s", count, day, rank)
            return rank
        return
项目:opennumber    作者:opennumber    | 项目源码 | 文件源码
def get_ip_rank(cls, phone):
        with models.Session() as session:
            day = datetime.date.today()
            model = PhoneCheckLogModel
            count = session.query(func.count(distinct(model.ip))).filter(model.phone==phone, model.create_datetime>=day).first()[0]

            rank = cls.ip_rank_map.get_rank(count)
            logger.debug("phone access ip count: %s at %s, rank: %s", count, day, rank)
            return rank
        return
项目:opennumber    作者:opennumber    | 项目源码 | 文件源码
def GET(self, *args, **kwargs):
        """
        """
        response = Response.internal_error()
        try:
            self.log_request()
            with models.Session() as orm:
                web.ctx.orm = orm
                response =  self.get(*args, **kwargs)
                return response
        except:
            logger.exception('BaseHandler failure:')
            status = '500 InternalError'
            headers = {'Content-Type': 'text/html'}
            raise web.HTTPError(status, headers, 'internal error')
项目:opennumber    作者:opennumber    | 项目源码 | 文件源码
def GET(self, *args, **kwargs):
        """
        """
        response = Response.internal_error()
        web.ctx.orm = None
        try:
            self.get_argument_timestamp()            
            self.get_argument('token')
            self.get_argument('sign')

            self.log_request()
            with models.Session() as session:
                web.ctx.orm = session
                result = self.get(*args, **kwargs)
                response.code = 0
                response.message = err.Success.message
                response.result = result
                pass

        except err.BaseError as e:
            logger.error("base error: %s", e.message)
            response.code = e.code
            response.message = e.message
        except:
            logger.exception('JsonHandler failure:')
            pass
        finally:
            del web.ctx.orm

        response_json_data =  utils.json_dumps(response)
        return response_json_data
项目:jarvis    作者:whittlbc    | 项目源码 | 文件源码
def get_current_user(req):
    session_token = req.headers.get(session_header)
    if not session_token: raise Exception()

    session = find(Session, dict(token=session_token))
    if not session: raise Exception()

    return find(User, dict(id=session.user_id))
项目:jarvis    作者:whittlbc    | 项目源码 | 文件源码
def login():
    email, pw = strip_creds_from_req(request.data)

    if not email or not pw:
        return rh.error(**ec.INCOMPLETE_LOGIN_CREDS)

    user = find(User, dict(email=email, password=pw))
    if not user: return rh.error(**ec.USER_NOT_FOUND)

    try:
        session = create(Session, dict(user_id=user.id))
        return rh.json_response(with_cookie=(cookie_name, session.token))
    except Exception as e:
        app.logger.error('Error logging in existing user with email: {}, with error: {}'.format(email, e))
        return rh.error(**ec.USER_LOGIN_ERROR)
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def soupinfo(*urls):
    log.debug('??????')
    br = mechanize.Browser()
    br.set_handle_equiv(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.addheaders = [('User-agent', 'Mozila/5.0(X11; U; Linux i686; en-us; rv:1.9.0.1) \
                        Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
    loginurl = 'https://portal.student.kit.ac.jp/'
    # ????????
    try:
        br.open(loginurl)
        br.select_form(nr=0)
        br['j_username'] = settings.shibboleth_user
        br['j_password'] = settings.shibboleth_pass
        br.submit()
        log.debug('???????????????')
        br.select_form(nr=0)
        br.submit()  # ??????????
        log.debug('??????')
    except Exception as e:
        session = models.Session()
        fault = session.query(models.Fault).filter(models.Fault.now == 1).first()
        if fault is None:
            new_fault = models.Fault(now=1, created_at=settings.now, status=e.encode('utf-8'))
            session.add(new_fault)
            session.commit()
            tweet('%s ??????????????????????????????????????'
                  % (settings.now.strftime('%Y/%m/%d %H:%M:%S')))
        session.close()
        log.exception(e)
    # ?????
    session = models.Session()
    fault = session.query(models.Fault).filter(models.Fault.now == 1).first()
    if fault is not None:
        fault.now = 0
        fault.ended_at = settings.now
        session.commit()
        tweet('%s ????????????????????'
              % (settings.now.strftime('%Y/%m/%d %H:%M:%S')))
    session.close()
    htmls = []
    for url in urls:
        target = loginurl + url
        br.open(target)
        log.debug('URL: %s … [??]', url)
        html = br.response().read()
        bs = BeautifulSoup(html, 'lxml')
        htmls.append(bs)
    return htmls
项目:Qkou_kit    作者:pddg    | 项目源码 | 文件源码
def add_info(subject, teacher, week, period, abstract, detail, first, update, unique_hash, renew_hash):
    session = models.Session()
    qkou = session.query(models.Info)
    # utf-8?????????????
    subject = subject.encode('utf-8')
    teacher = teacher.encode('utf-8')
    week = week.encode('utf-8')
    period = period.encode('utf-8')
    abstract = abstract.encode('utf-8')
    detail = detail.encode('utf-8')
    first = first.encode('utf-8')
    update = update.encode('utf-8')
    unique_hash = unique_hash.encode('utf-8')
    renew_hash = renew_hash.encode('utf-8')
    newinfo = models.Info(
        subject, teacher, week, period, abstract, detail, first, update, unique_hash, renew_hash, now)
    try:
        # ?????????
        ex_info = qkou.filter(models.Info.unique_hash == unique_hash).first()
        if ex_info is None:
            # ?????
            log.debug('???: %s … [??]', subject)
            session.add(newinfo)
            session.commit()
            new_id = newinfo.id
            return new_id
        else:
            # ????????
            if ex_info.renew_hash != renew_hash:
                log.debug('???: %s … [??]', subject)
                ex_info.detail = detail
                ex_info.up_date = update
                ex_info.renew_hash = renew_hash
                ex_info.up_time = now
                session.commit()
                ex_id = ex_info.id
                return ex_id
            else:
                # ???????
                log.debug('???: %s … [??]', subject)
                ex_info.up_time = now
                session.commit()
                return False
    except Exception as e:
        session.rollback()
        log.exception(e)
        return False
    finally:
        session.close()
项目:kokkuri    作者:LiGhT1EsS    | 项目源码 | 文件源码
def __guard_thread(self):

        logger.info("SSHD Guard start.")

        session = Session()
        while not self._exit_flag:

            logger.debug("Checking...")

            # ????1??????????
            current_time = datetime.datetime.now()
            last_time = datetime.datetime.now() - datetime.timedelta(minutes=2)

            logger.debug("current_time")
            logger.debug(current_time)

            logger.debug("last_time")
            logger.debug(last_time)

            ssh_event_qs = session.query(KokkuriSSHEvent).filter(
                KokkuriSSHEvent.is_deleted == 0, KokkuriSSHEvent.created_time < current_time,
                KokkuriSSHEvent.created_time > last_time, KokkuriSSHEvent.result == 0
            ).all()
            session.commit()

            analyze_dict = dict()
            logger.debug("ssh event qs")
            logger.debug(ssh_event_qs)

            # ??????IP?????
            for qs in ssh_event_qs:
                source_ip = qs.source_ip
                if source_ip not in analyze_dict.keys():
                    analyze_dict[source_ip] = 0

                analyze_dict[source_ip] += 1
            logger.debug(analyze_dict)
            # todo: ???????
            # todo: ??????
            # ???5????IP??????????????
            evil_ip = list()
            for ip, fail_count in analyze_dict.items():
                if fail_count >= 5:
                    evil_ip.append(ip)

            if len(evil_ip) != 0:
                self.evil_task_queue.put(evil_ip)

            # ??sleep??
            time.sleep(5)