3 # Copyright 2011 Google Inc. All Rights Reserved.
5 """A simple guest book app that demonstrates the App Engine search API."""
8 from cgi
import parse_qs
9 from datetime
import datetime
13 from urlparse
import urlparse
16 from webapp2_extras
import jinja2
18 from google
.appengine
.api
import search
19 from google
.appengine
.api
import users
21 _INDEX_NAME
= 'greeting'
23 # _ENCODE_TRANS_TABLE = string.maketrans('-: .@', '_____')
25 class BaseHandler(webapp2
.RequestHandler
):
26 """The other handlers inherit from this class. Provides some helper methods
27 for rendering a template."""
29 @webapp2.cached_property
31 return jinja2
.get_jinja2(app
=self
.app
)
33 def render_template(self
, filename
, template_args
):
34 self
.response
.write(self
.jinja2
.render_template(filename
, **template_args
))
37 class MainPage(BaseHandler
):
38 """Handles search requests for comments."""
41 """Handles a get request with a query."""
42 uri
= urlparse(self
.request
.uri
)
45 query
= parse_qs(uri
.query
)
46 query
= query
['query'][0]
48 # sort results by author descending
49 expr_list
= [search
.SortExpression(
50 expression
='author', default_value
='',
51 direction
=search
.SortExpression
.DESCENDING
)]
52 # construct the sort options
53 sort_opts
= search
.SortOptions(
54 expressions
=expr_list
)
55 query_options
= search
.QueryOptions(
57 sort_options
=sort_opts
)
58 query_obj
= search
.Query(query_string
=query
, options
=query_options
)
59 results
= search
.Index(name
=_INDEX_NAME
).search(query
=query_obj
)
60 if users
.get_current_user():
61 url
= users
.create_logout_url(self
.request
.uri
)
62 url_linktext
= 'Logout'
64 url
= users
.create_login_url(self
.request
.uri
)
65 url_linktext
= 'Login'
69 'number_returned': len(results
.results
),
71 'url_linktext': url_linktext
,
73 self
.render_template('index.html', template_values
)
76 def CreateDocument(author
, content
):
77 """Creates a search.Document from content written by the author."""
79 nickname
= author
.nickname().split('@')[0]
81 nickname
= 'anonymous'
82 # Let the search service supply the document id.
83 return search
.Document(
84 fields
=[search
.TextField(name
='author', value
=nickname
),
85 search
.TextField(name
='comment', value
=content
),
86 search
.DateField(name
='date', value
=datetime
.now().date())])
89 class Comment(BaseHandler
):
90 """Handles requests to index comments."""
93 """Handles a post request."""
95 if users
.get_current_user():
96 author
= users
.get_current_user()
98 content
= self
.request
.get('content')
99 query
= self
.request
.get('search')
101 search
.Index(name
=_INDEX_NAME
).put(CreateDocument(author
, content
))
103 self
.redirect('/?' + urllib
.urlencode(
105 {'query': query
.encode('utf-8')}))
110 application
= webapp2
.WSGIApplication(