当前位置: 首页>>代码示例>>Python>>正文


Python Session.query方法代码示例

本文整理汇总了Python中cms.db.Session.query方法的典型用法代码示例。如果您正苦于以下问题:Python Session.query方法的具体用法?Python Session.query怎么用?Python Session.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cms.db.Session的用法示例。


在下文中一共展示了Session.query方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import query [as 别名]
def main():
	# Get session
	session = Session()
	# Apre una sessione e lista i forum
	# forums = session.query(Forum).all()
	forums = session.query(forum.Forum).all()
	print "Forums found: ", len(forums)
	params = {'title': "Discussioni sul sito", 'description': "Per malfunzionamenti, dubbi o suggerimenti relativi al sito."}
	my_forum = forum.Forum(**params)
	session.add(my_forum)
	session.commit()
开发者ID:acube-unipi,项目名称:oii-web,代码行数:13,代码来源:add_forum.py

示例2: BaseHandler

# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import query [as 别名]
class BaseHandler(CommonRequestHandler):
    """Base RequestHandler for this application.

    All the RequestHandler classes in this application should be a
    child of this class.

    """

    def try_commit(self):
        """Try to commit the current session.

        If not successful display a warning in the webpage.

        return (bool): True if commit was successful, False otherwise.

        """
        try:
            self.sql_session.commit()
        except IntegrityError as error:
            self.application.service.add_notification(
                make_datetime(),
                "Operation failed.", "%s" % error)
            return False
        else:
            self.application.service.add_notification(
                make_datetime(),
                "Operation successful.", "")
            return True

    def safe_get_item(self, cls, ident, session=None):
        """Get item from database of class cls and id ident, using
        session if given, or self.sql_session if not given. If id is
        not found, raise a 404.

        cls (type): class of object to retrieve.
        ident (string): id of object.
        session (Session|None): session to use.

        return (object): the object with the given id.

        raise (HTTPError): 404 if not found.

        """
        if session is None:
            session = self.sql_session
        entity = cls.get_from_id(ident, session)
        if entity is None:
            raise tornado.web.HTTPError(404)
        return entity

    def prepare(self):
        """This method is executed at the beginning of each request.

        """
        # Attempt to update the contest and all its references
        # If this fails, the request terminates.
        self.set_header("Cache-Control", "no-cache, must-revalidate")

        self.sql_session = Session()
        self.sql_session.expire_all()
        self.contest = None

    def render_params(self):
        """Return the default render params used by almost all handlers.

        return (dict): default render params

        """
        params = {}
        params["timestamp"] = make_datetime()
        params["contest"] = self.contest
        params["url_root"] = get_url_root(self.request.path)
        if self.contest is not None:
            params["phase"] = self.contest.phase(params["timestamp"])
            # Keep "== None" in filter arguments. SQLAlchemy does not
            # understand "is None".
            params["unanswered"] = self.sql_session.query(Question)\
                .join(Participation)\
                .filter(Participation.contest_id == self.contest.id)\
                .filter(Question.reply_timestamp == None)\
                .filter(Question.ignored == False)\
                .count()  # noqa
        # TODO: not all pages require all these data.
        params["contest_list"] = self.sql_session.query(Contest).all()
        params["task_list"] = self.sql_session.query(Task).all()
        params["user_list"] = self.sql_session.query(User).all()
        return params

    def finish(self, *args, **kwds):
        """Finish this response, ending the HTTP request.

        We override this method in order to properly close the database.

        TODO - Now that we have greenlet support, this method could be
        refactored in terms of context manager or something like
        that. So far I'm leaving it to minimize changes.

        """
        self.sql_session.close()
        try:
#.........这里部分代码省略.........
开发者ID:hydai,项目名称:cms,代码行数:103,代码来源:base.py

示例3: BaseHandler

# 需要导入模块: from cms.db import Session [as 别名]
# 或者: from cms.db.Session import query [as 别名]
class BaseHandler(CommonRequestHandler):
    """Base RequestHandler for this application.

    All the RequestHandler classes in this application should be a
    child of this class.

    """

    # Whether the login cookie duration has to be refreshed when
    # this handler is called. Useful to filter asynchronous
    # requests.
    refresh_cookie = True

    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)
        self.timestamp = None
        self.cookie_lang = None
        self.browser_lang = None
        self.langs = None
        self._ = None

    def prepare(self):
        """This method is executed at the beginning of each request.

        """
        self.timestamp = make_datetime()

        self.set_header("Cache-Control", "no-cache, must-revalidate")

        self.sql_session = Session()
        self.contest = Contest.get_from_id(self.application.service.contest,
                                           self.sql_session)

        self._ = self.locale.translate

        self.r_params = self.render_params()

    def get_current_user(self):
        """The name is get_current_user because tornado wants it that
        way, but this is really a get_current_participation.

        Gets the current participation from cookies.

        If a valid cookie is retrieved, return a Participation tuple
        (specifically: the Participation involving the username
        specified in the cookie and the current contest).

        Otherwise (e.g. the user exists but doesn't participate in the
        current contest), return None.

        """
        remote_ip = self.request.remote_ip
        if self.contest.ip_autologin:
            self.clear_cookie("login")
            participations = self.sql_session.query(Participation)\
                .filter(Participation.contest == self.contest)\
                .filter(Participation.ip == remote_ip)\
                .all()
            if len(participations) == 1:
                return participations[0]

            if len(participations) > 1:
                logger.error("Multiple users have IP %s." % (remote_ip))
            else:
                logger.error("No user has IP %s" % (remote_ip))

            # If IP autologin is set, we do not allow password logins.
            return None

        if self.get_secure_cookie("login") is None:
            return None

        # Parse cookie.
        try:
            cookie = pickle.loads(self.get_secure_cookie("login"))
            username = cookie[0]
            password = cookie[1]
            last_update = make_datetime(cookie[2])
        except:
            self.clear_cookie("login")
            return None

        # Check if the cookie is expired.
        if self.timestamp - last_update > \
                timedelta(seconds=config.cookie_duration):
            self.clear_cookie("login")
            return None

        # Load user from DB.
        user = self.sql_session.query(User)\
            .filter(User.username == username)\
            .first()

        # Check if user exists.
        if user is None:
            self.clear_cookie("login")
            return None

        # Load participation from DB.
        participation = self.sql_session.query(Participation)\
#.........这里部分代码省略.........
开发者ID:giomasce,项目名称:cms,代码行数:103,代码来源:base.py


注:本文中的cms.db.Session.query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。