コード例 #1
0
ファイル: snippet.py プロジェクト: szabo92/gistable
def get_user_by_username(session,
                         username,
                         with_profile=True,
                         from_cache=True):

    query = session.query(User).filter(User.username == username)

    if with_profile:
        query = query.options(joinedload('profile'))

    if from_cache:
        print("Pulling from cache")
        query = query.options(FromCache())
        query = query.options(RelationshipCache(User.profile))

    user = query.one()

    return user
コード例 #2
0
def load_name_range(start, end, invalidate=False):
    """Load Person objects on a range of names.

    start/end are integers, range is then
    "person <start>" - "person <end>".

    The cache option we set up is called "name_range", indicating 
    a range of names for the Person class.

    The `Person.addresses` collections are also cached.  Its basically
    another level of tuning here, as that particular cache option
    can be transparently replaced with joinedload(Person.addresses). 
    The effect is that each Person and his/her Address collection
    is cached either together or separately, affecting the kind of
    SQL that emits for unloaded Person objects as well as the distribution
    of data within the cache.
    """
    q = Session.query(Person).\
            filter(Person.name.between("person %.2d" % start, "person %.2d" % end)).\
            options(cache_address_bits).\
            options(FromCache("default", "name_range"))

    # have the "addresses" collection cached separately
    # each lazyload of Person.addresses loads from cache.
    q = q.options(RelationshipCache("default", "by_person", Person.addresses))

    # alternatively, eagerly load the "addresses" collection, so that they'd
    # be cached together.   This issues a bigger SQL statement and caches
    # a single, larger value in the cache per person rather than two
    # separate ones.
    #q = q.options(joinedload(Person.addresses))

    # if requested, invalidate the cache on current criterion.
    if invalidate:
        q.invalidate()

    return q.all()
コード例 #3
0
"""helloworld.py

Illustrate how to load some data, and cache the results.

"""

import pudb; pu.db
from environment import Session
from model import Person
from caching_query import FromCache

# load Person objects.  cache the result in the "default" cache region
print("loading people....")
people = Session.query(Person).options(FromCache("default")).all()

# remove the Session.  next query starts from scratch.
Session.remove()

# load again, using the same FromCache option. now they're cached,
# so no SQL is emitted.
print("loading people....again!")
people = Session.query(Person).options(FromCache("default")).all()

# Specifying a different query produces a different cache key, so
# these results are independently cached.
print("loading people two through twelve")
people_two_through_twelve = Session.query(Person).\
                            options(FromCache("default")).\
                            filter(Person.name.between("person 02", "person 12")).\
                            all()
コード例 #4
0
ファイル: local_session_caching.py プロジェクト: oleg84/CDS
    from caching_query import FromCache

    # create a Beaker container type called "ext:local_session".
    # it will reference the ScopedSession in meta.
    ScopedSessionNamespace.create_session_container("ext:local_session",
                                                    Session)

    # set up a region based on this new container type.
    cache_manager.regions['local_session'] = {'type': 'ext:local_session'}

    from model import Person

    # query to load Person by name, with criterion
    # of "person 10"
    q = Session.query(Person).\
                    options(FromCache("local_session", "by_name")).\
                    filter(Person.name=="person 10")

    # load from DB
    person10 = q.one()

    # next call, the query is cached.
    person10 = q.one()

    # clear out the Session.  The "_beaker_cache" dictionary
    # disappears with it.
    Session.remove()

    # query calls from DB again
    person10 = q.one()
コード例 #5
0
    # set up a region based on the ScopedSessionBackend,
    # pointing to the scoped_session declared in the example
    # environment.
    regions['local_session'] = make_region().configure(
        'sqlalchemy.session',
        arguments={
            "scoped_session": Session
        }
    )

    from model import Person

    # query to load Person by name, with criterion
    # of "person 10"
    q = Session.query(Person).\
                    options(FromCache("local_session")).\
                    filter(Person.name == "person 10")

    # load from DB
    person10 = q.one()

    # next call, the query is cached.
    person10 = q.one()

    # clear out the Session.  The "_cache_dictionary" dictionary
    # disappears with it.
    Session.remove()

    # query calls from DB again
    person10 = q.one()
コード例 #6
0
    def msg(self, response):
        #print(response)
        if response.get('history', None):
            #response["updates"] = response["history"]
            #print(response)
            if response["messages"][0] == 0:
                pass
            else:
                pass
                #print(response["messages"][1]["body"] + " - " + str(response["new_pts"]))

        else:

            if response.get("updates", None):
                if len(response["updates"][0]) > 4:
                    #print("GETTING " + str(response))
                    if response["updates"][0][4]:
                        #print(response)
                        if response["updates"][0][7].get("from", None):
                            self.uid = response["updates"][0][7]["from"]
                            self.groupChat = True
                        else:
                            self.uid = response["updates"][0][3]
                            self.groupChat = False

                        if response["updates"][0][2] == "547":
                            pass
                        else:
                            self.timestamp = response["updates"][0][4]
                            if self.groupChat:
                                self.group_id = abs(2000000000 - response["updates"][0][3])
                            self.message = response["updates"][0][6]
                            #pprint(self.message + " - " + str(response["ts"]))
                            vkapi.addUser(self.uid)
                            self.db = session.query(User).options(FromCache('default')).filter_by(id=self.uid).first()

                            data = {"message":self.message,
                            "user_id":self.uid,
                            "timestamp":self.timestamp,
                            #"group_id":self.group_id,
                            "db":self.db,
                            "dbsession":session
                            }
                            #logging.info('Got message from {} - {}'.format(self.uid, self.message))
                            if self.groupChat:
                                data["chat_id"] = self.group_id
                            else:
                                data["chat_id"] = None

                            vkapi.insert_message_db(data)

                            if response["updates"][0][7].get("source_act", None):

                                if response["updates"][0][7]["source_act"] == "chat_invite_user":
                                    msg = {"message":"Привет, {}!".format(self.db.first_name),
                                    "chat_id":self.group_id,
                                    "from":self.uid
                                    }
                                    vkapi.send(msg)

                                if response["updates"][0][7]["source_act"] == "chat_title_update":
                                    msg = {"message":"Классное название, {}! ".format(self.db.first_name),
                                    "chat_id":self.group_id,
                                    "from":self.uid
                                    }
                                    vkapi.send(msg)


                            checkmessage = self.msgengine.run(commands=[self.message], data=data) #check for keywords
                            #print(checkmessage)


                            if checkmessage is not None:

                                if type(checkmessage) is dict: #if its dict (more info)
                                    msg = checkmessage
                                    if self.groupChat == True:
                                        msg["chat_id"] = self.group_id
                                    else:
                                        msg["user_id"] = self.uid
                                    msg["forward_messages"] = response["updates"][0][1]

                                    

                                else: #if it's jsut a string (message)
                                    if self.groupChat == True:
                                        msg = {"message":checkmessage,
                                        "chat_id":self.group_id,
                                        "from":self.uid,
                                        }
                                    if self.groupChat == False:
                                        msg = {"message":checkmessage,
                                        "user_id":self.uid,
                                        "from":self.uid
                                        }

                                    msg["forward_messages"] = response["updates"][0][1]
                                if vkapi.debug:

                                    last_timestamp = session.query(Messages).options(FromCache('default')).order_by(Messages.id.desc()).limit(2)
                                    msg["message"] = msg.get("message", "") + "\nДЕБАГ ВЕРСИЯ!!!! НИЧЕГО НЕ БУДЕТ СОХРАНЯТЬСЯ!!!!! \n Последнее сообщение было {} секунд назад ".format(
                                        self.timestamp-last_timestamp[1].timestamp)
                                vkapi.send(msg)