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
15 from google
.appengine
.api
import search
16 from google
.appengine
.api
import users
17 from google
.appengine
.ext
import webapp
18 from google
.appengine
.ext
.webapp
import template
19 from google
.appengine
.ext
.webapp
.util
import run_wsgi_app
22 _INDEX_NAME
= 'greeting'
24 _ENCODE_TRANS_TABLE
= string
.maketrans('-: .@', '_____')
27 class MainPage(webapp
.RequestHandler
):
28 """Handles search requests for comments."""
31 """Handles a get request with a query."""
32 uri
= urlparse(self
.request
.uri
)
35 query
= parse_qs(uri
.query
)
36 query
= query
['query'][0]
38 # sort results by author descending
39 expr_list
= [search
.SortExpression(
40 expression
='author', default_value
='',
41 direction
=search
.SortExpression
.DESCENDING
)]
42 # construct the sort options
43 sort_opts
= search
.SortOptions(
44 expressions
=expr_list
)
45 query_options
= search
.QueryOptions(
47 sort_options
=sort_opts
)
48 query_obj
= search
.Query(query_string
=query
, options
=query_options
)
49 results
= search
.Index(name
=_INDEX_NAME
).search(query
=query_obj
)
51 if users
.get_current_user():
52 url
= users
.create_logout_url(self
.request
.uri
)
53 url_linktext
= 'Logout'
55 url
= users
.create_login_url(self
.request
.uri
)
56 url_linktext
= 'Login'
60 'number_returned': len(results
.results
),
62 'url_linktext': url_linktext
,
65 path
= os
.path
.join(os
.path
.dirname(__file__
), 'index.html')
66 self
.response
.out
.write(template
.render(path
, template_values
))
69 def CreateDocument(author
, content
):
70 """Creates a search.Document from content written by the author."""
72 nickname
= author
.nickname().split('@')[0]
74 nickname
= 'anonymous'
75 # Let the search service supply the document id.
76 return search
.Document(
77 fields
=[search
.TextField(name
='author', value
=nickname
),
78 search
.TextField(name
='comment', value
=content
),
79 search
.DateField(name
='date', value
=datetime
.now().date())])
82 class Comment(webapp
.RequestHandler
):
83 """Handles requests to index comments."""
86 """Handles a post request."""
88 if users
.get_current_user():
89 author
= users
.get_current_user()
91 content
= self
.request
.get('content')
92 query
= self
.request
.get('search')
94 search
.Index(name
=_INDEX_NAME
).add(CreateDocument(author
, content
))
96 self
.redirect('/?' + urllib
.urlencode(
98 {'query': query
.encode('utf-8')}))
103 application
= webapp
.WSGIApplication(
110 run_wsgi_app(application
)
112 if __name__
== '__main__':