0

当我在网络表单中进行搜索时,似乎找到了匹配项,但未显示:

在此处输入图像描述

我该怎么做才能使 SERP 显示?我的代码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <link rel="stylesheet" type="text/css" href="/static/css/main.css"/>
    <title>Search Demonstration App</title>
  </head>
  <body>

    <form action="/sign" method="post">
      <div>Search Demo</div>
      <div><textarea name="search" rows="1" cols="60"></textarea></div>
      <div><input type="submit" value="Search"/></div>
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Comment"/></div>
    </form>

    {{number_returned}} of {{results.number_found}} comments found <p>
    {% for scored_document in results %}
      {% for field in scored_document.fields %}
        {{field.value}} &nbsp;
      {% endfor %}
      <p>
    {% endfor %}

    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>

和.py

class SearchAPI(webapp.RequestHandler):
    """Handles search requests for comments."""

    def get(self):
        """Handles a get request with a query."""
        uri = urlparse(self.request.uri)
        query = ''
        if uri.query:
            query = parse_qs(uri.query)
            query = query['query'][0]

        # sort results by author descending
        expr_list = [search.SortExpression(
            expression='author', default_value='',
            direction=search.SortExpression.DESCENDING)]
        # construct the sort options 
        sort_opts = search.SortOptions(
             expressions=expr_list)
        query_options = search.QueryOptions(
            limit=3,
            sort_options=sort_opts)
        query_obj = search.Query(query_string=query, options=query_options)
        results = search.Index(name='ad').search(query=query_obj)
    #logging.info("number of results:" +len(results))
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'results': results,
            'number_returned': len(results.results),
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'searchapi.html')
        self.response.out.write(template.render(path, template_values))

索引是这样构建的:

class CreateAdHandler(BaseHandler):

    def post(self):
    ad = Ad.get_by_id(self.session.get('ad_id'))
        city_entity = montaomodel.City.all().filter('name =', ad.city).get()
        region_entity = montaomodel.Region.all().filter('name =', ad.region).get()
        form = PreviewAdForm(self.request.params)
        if form.validate():
            ad.set_password(self.request.get('password'))
            ad.published = True
            ad.put()
            doc = search.Document(doc_id=str(ad.key()),
                 fields=[search.TextField(name='title', 
                           value=ad.title),search.TextField(name='text', 
                           value=ad.text),search.TextField(name='city', 
                           value=ad.city),search.TextField(name='region', 
                           value=ad.region),search.NumberField(name='cityID', 
                           value=city_entity.key().id()),search.NumberField(name='regionID', 
                           value=region_entity.key().id()),search.NumberField(name='category', 
                           value=int(ad.category)), search.NumberField(name='constant', 
                           value=1), search.NumberField(name='adID', 
                           value=ad.key().id()),                 
                 search.TextField(name='name',
                           value=ad.name
                           )],
         language='en')
            search.Index(name='ad').add(doc) # should this be "put" instead? see https://developers.google.com/appengine/docs/python/search/overview#Deleting_Documents

            self.redirect('/vi/%d.html' % (ad.key().id(), ))
        else:
            logging.info('form did not validate')
            self.render_jinja('preview', form=form, ad=ad) 

更新

通过仔细调试,表明该行不起作用:{% for f in scored_document.fields %}. 我通过调试找到了,但我不知道为什么。所以至少我现在更接近解决方案,但还没有完成。

更新 2

我不明白为什么不访问这些字段。我可以添加数据并将其输出到控制台:

INFO     2013-05-14 01:00:53,944 main.py:4437] result: search.ScoredDocument(doc_id=u'eb24f746-c60a-462c-9f64-a06ad6a823cb', fields=[search.TextField(name=u'author', value=u'test'), search.TextField(name=u'comment', value=u'test'), search.DateField(name=u'date', value=datetime.datetime(2013, 5, 13, 0, 0))], language=u'en', rank=74648319L)
INFO     2013-05-14 01:00:53,944 main.py:4437] result: search.ScoredDocument(doc_id=u'af0de892-0e59-4c12-bd9e-6e8caa2067d4', fields=[search.TextField(name=u'author', value=u'test'), search.TextField(name=u'comment', value=u'test'), search.DateField(name=u'date', value=datetime.datetime(2013, 5, 14, 0, 0))], language=u'en', rank=74653247L)

此日志记录现在是这样进行的:

for r in results:
    logging.info("result: " + str(r))

因此,如果我可以将这样的数据记录到控制台,为什么我不能将其输出到我的页面?

4

2 回答 2

1

我认为你需要returned_fields在你的QueryOptions. (字段名称列表。)

于 2013-05-12T08:26:39.003 回答
1

似乎您应该results.results在模板中进行迭代:

{% for scored_document in results.results %}
于 2013-05-12T12:48:35.510 回答