def get(self, post_id):
"""
This renders home post page with content, comments and likes.
"""
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
comments = db.GqlQuery("select * from Comment where post_id = " +
post_id + " order by created desc")
likes = db.GqlQuery("select * from Like where post_id="+post_id)
if not post:
self.error(404)
return
error = self.request.get('error')
self.render("permalink.html", post=post, noOfLikes=likes.count(),
comments=comments, error=error)
python类GqlQuery()的实例源码
def __init__(self, query_string, model_class, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
model_class: Model class from which entities are constructed.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app, namespace='')
super(db.GqlQuery, self).__init__(model_class)
self.bind(*args, **kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: Properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
Returns:
A gql.GqlQuery object querying over BlobInfo's datastore kind.
"""
return _GqlQuery('SELECT * FROM %s %s'
% (cls.kind(), query_string),
cls,
*args,
**kwds)
def __init__(self, query_string, model_class, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
model_class: Model class from which entities are constructed.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app, namespace='')
super(db.GqlQuery, self).__init__(model_class)
self.bind(*args, **kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: Properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
Returns:
A gql.GqlQuery object querying over BlobInfo's datastore kind.
"""
return _GqlQuery('SELECT * FROM %s %s'
% (cls.kind(), query_string),
cls,
*args,
**kwds)
def get(self, post_id, post_user_id):
if self.user and self.user.key().id() == int(post_user_id):
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
post.delete()
self.redirect('/')
elif not self.user:
self.redirect('/login')
else:
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
comments = db.GqlQuery(
"select * from Comment where ancestor is :1 order by created desc limit 10", key)
error = "You don't have permission to delete this post"
self.render("permalink.html", post=post, comments=comments, error=error)
def __init__(self, query_string, model_class, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
model_class: Model class from which entities are constructed.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app, namespace='')
super(db.GqlQuery, self).__init__(model_class)
self.bind(*args, **kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: Properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
Returns:
A gql.GqlQuery object querying over BlobInfo's datastore kind.
"""
return _GqlQuery('SELECT * FROM %s %s'
% (cls.kind(), query_string),
cls,
*args,
**kwds)
def __init__(self, query_string, model_class, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
model_class: Model class from which entities are constructed.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app, namespace='')
super(db.GqlQuery, self).__init__(model_class)
self.bind(*args, **kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: Properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
Returns:
A gql.GqlQuery object querying over BlobInfo's datastore kind.
"""
return _GqlQuery('SELECT * FROM %s %s'
% (cls.kind(), query_string),
cls,
*args,
**kwds)
def __init__(self, query_string, model_class, *args, **kwds):
"""Constructor.
Args:
query_string: Properly formatted GQL query string.
model_class: Model class from which entities are constructed.
*args: Positional arguments used to bind numeric references in the query.
**kwds: Dictionary-based arguments for named references.
"""
from google.appengine.ext import gql
app = kwds.pop('_app', None)
self._proto_query = gql.GQL(query_string, _app=app, namespace='')
super(db.GqlQuery, self).__init__(model_class)
self.bind(*args, **kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a query using GQL query string.
See appengine/ext/gql for more information about GQL.
Args:
query_string: Properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
Returns:
A gql.GqlQuery object querying over BlobInfo's datastore kind.
"""
return _GqlQuery('SELECT * FROM %s %s'
% (cls.kind(), query_string),
cls,
*args,
**kwds)
def gql(cls, query_string, *args, **kwds):
"""Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
if cls == cls.__root_class__:
return super(PolyModel, cls).gql(query_string, *args, **kwds)
else:
from google.appengine.ext import gql
query = db.GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string))
query_filter = [('nop',
[gql.Literal(cls.class_name())])]
query._proto_query.filters()[('class', '=')] = query_filter
query.bind(*args, **kwds)
return query
def gql(cls, query_string, *args, **kwds):
"""Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
if cls == cls.__root_class__:
return super(PolyModel, cls).gql(query_string, *args, **kwds)
else:
from google.appengine.ext import gql
query = db.GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string))
query_filter = [('nop',
[gql.Literal(cls.class_name())])]
query._proto_query.filters()[('class', '=')] = query_filter
query.bind(*args, **kwds)
return query
def get(self, post_id):
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
comments = db.GqlQuery(
"select * from Comment where ancestor is :1 order by created desc limit 10", key)
if not post:
self.error(404)
return
self.render("permalink.html", post=post, comments=comments)
def get(self):
posts = db.GqlQuery(
"select * from Post order by created desc limit 10")
self.render('front.html', posts=posts)
def like_dup(ent, login_id, post_id):
key = post_key(post_id)
like_exists = db.GqlQuery("SELECT * "
"FROM " + ent +
" WHERE like_user_id = '" + login_id +
"' AND ANCESTOR IS :1", key).get()
return like_exists
# CLASS DEFINITIONS
def user_exists(self, username):
""" validates that the user exists in the database """
username_exists = db.GqlQuery("SELECT * "
"FROM User "
"WHERE username = :usernm",
usernm=username).get()
return username_exists
def user_auth(self, username, password):
"""
If the username exists it suthenticates the password of the user
"""
user = db.GqlQuery("SELECT * "
"FROM User "
"WHERE username = :usernm",
usernm=username).get()
if user:
return self.valid_pass_hash(user.username,
password,
user.pass_hash)
def post_likes(self, post_id):
# gets the metadata about the datastor
kinds = metadata.get_kinds()
# checks to see if any likes exist and if so displays them
if u'PostLike' in kinds:
likes = db.GqlQuery("SELECT * "
"FROM PostLike "
"WHERE ANCESTOR IS :1",
post_key(post_id)).count()
else:
likes = 0
return likes
def get(self):
"""
queries the database for the 10 most recent
blog posts and orders them descending
"""
posts = db.GqlQuery("SELECT * "
"FROM Post "
"ORDER BY created DESC LIMIT 10")
self.render("front.html", posts=posts)
def user_exists(self, username):
""" validates that the user exists in the database """
username_exists = db.GqlQuery("SELECT * "
"FROM User "
"WHERE username = :usernm",
usernm=username).get()
return username_exists
def post(self):
""" handles the POST request from signup.html """
auth_error = True
username = self.request.get('username')
password = self.request.get('password')
# dictionary to store error messages, username and email if not valid
params = dict(username=username)
# if the username already exists or it is an error
if self.user_exists(username):
auth_error = False
# tests for valid password and password match
if self.user_auth(username, password):
auth_error = False
else:
auth_error = True
params['error_password'] = 'Invalid Password'
else:
auth_error = True
params['error_username'] = 'User Does Not Exist'
# if there is an error re-render signup page
# else render the welcome page
if auth_error:
self.render("login.html", **params)
else:
user = db.GqlQuery("SELECT * "
"FROM User "
"WHERE username = :usernm",
usernm=username).get()
user_id = str(user.key().id())
self.set_secure_cookie('usercookie', user_id, None)
self.redirect('/welcome')
def gql(cls, query_string, *args, **kwds):
"""Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
if cls == cls.__root_class__:
return super(PolyModel, cls).gql(query_string, *args, **kwds)
else:
from google.appengine.ext import gql
query = db.GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string))
query_filter = [('nop',
[gql.Literal(cls.class_name())])]
query._proto_query.filters()[('class', '=')] = query_filter
query.bind(*args, **kwds)
return query
def gen_query(self, model_name, params):
"""takes a model_name (e.g. "User" as a string) and dictionary of params
and returns a GQLQuery object"""
query_text = "SELECT * from " + model_name + " WHERE "
first_and = True
for key in params_dict.keys():
if first_and:
query_text+=" " + key + " = :" + key
first_and = False
else:
query_text+=" AND " + key + " = :" + key
query = db.GqlQuery(query_text, **params_dict)
return query
def by_limit(cls, limit):
return db.GqlQuery("select * from Post order by created desc limit {}".format(limit))
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
try:
while True:
q = db.GqlQuery("SELECT __key__ FROM FacebookCachedObject")
if not q.count():
break
db.delete(q.fetch(200))
time.sleep(0.1)
except Exception, e:
self.response.out.write(repr(e) + '\n')
pass
def gql(cls, query_string, *args, **kwds):
"""Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
if cls == cls.__root_class__:
return super(PolyModel, cls).gql(query_string, *args, **kwds)
else:
from google.appengine.ext import gql
query = db.GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string))
query_filter = [('nop',
[gql.Literal(cls.class_name())])]
query._proto_query.filters()[('class', '=')] = query_filter
query.bind(*args, **kwds)
return query
def gql(cls, query_string, *args, **kwds):
"""Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Args:
query_string: properly formatted GQL query string with the
'SELECT * FROM <entity>' part omitted
*args: rest of the positional arguments used to bind numeric references
in the query.
**kwds: dictionary-based arguments (for named parameters).
"""
if cls == cls.__root_class__:
return super(PolyModel, cls).gql(query_string, *args, **kwds)
else:
from google.appengine.ext import gql
query = db.GqlQuery('SELECT * FROM %s %s' % (cls.kind(), query_string))
query_filter = [('nop',
[gql.Literal(cls.class_name())])]
query._proto_query.filters()[('class', '=')] = query_filter
query.bind(*args, **kwds)
return query
def get_user_by_username(cls, user_name):
'''
get_user_by_name : function return user instance by username
'''
return db.GqlQuery("SELECT * FROM User WHERE username= :username", username=user_name).get() # NOQA