【问题标题】:GAE renders 'none' but i can see the db entities in datastore viewerGAE 呈现“无”,但我可以在数据存储查看器中看到数据库实体
【发布时间】:2013-03-26 06:45:47
【问题描述】:

我在访问数据存储实体时遇到问题。我是 GAE 和 Python 的新手,所以请善待。我一直在从在线教程和其他示例代码中获取代码,到目前为止一切正常。

最终,我希望能够剥离电子邮件附件,对文件进行一些简单的更改并与其他 .kml 文件(甚至更好的 .kmz,但一次一件事:)合并.

第 1 步。是向应用程序的appspotmail地址发送电子邮件=完成:)

第二步。 ...写入 db.model = 我可以在仪表板/数据存储查看器中看到实体在那里,所以没问题 = 完成 :)

第三步。 - 呈现模板以显示最近收到的 20 封电子邮件。此列表将动态更新..... :( Hmmmmm

相反,我看到none 为 index.html 中的所有变量呈现。你能指出我正确的方向吗?谢谢!

Dav-o

这里是 yaml.app

application: racetracer
version: 1
runtime: python27
api_version: 1
threadsafe: false

libraries:                                                                      
- name: jinja2                                                                  
  version: latest   

handlers:
- url: /_ah/mail/.+ 
  script: handle_incoming_email.py
  login: admin

- url: /favicon.ico
  static_files: images/favicon.ico
  upload: images/favicon.ico

- url: /static/css
  static_dir: static/css

- url: /static/html
  static_dir: static/index.html

- url: .*
  script: main.app

inbound_services:
- mail

这里是handle_incoming_email.py

import logging, email
import cgi
import datetime
import os.path
import os

from os import path
from google.appengine.ext import webapp 
from google.appengine.ext import db
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext.webapp.template import render
import jinja2
import wsgiref.handlers

from main import *
from baseController import *
from authController import *

class Vault(db.Model):
    #fromAddress= db.UserProperty()
    fromAddress= db.StringProperty()
    subject = db.StringProperty(multiline=True)
    #date = db.DateTimeProperty(auto_now_add=True)
    date = db.StringProperty(multiline=True)
    name = db.StringProperty(multiline=True)

class ProcessEmail(InboundMailHandler): 
    def receive(self, mailMessage): 
        logging.info("Email from: " + mailMessage.sender + " received ok")
        logging.info("Email subject: " + mailMessage.subject )
        logging.info("Email date: " + mailMessage.date )

        fromAddress = mailMessage.sender
        subject = mailMessage.subject
        date = mailMessage.date

        if not hasattr(mailMessage, 'attachments'):
            logging.info("Oi, the email has no attachments")
            # raise ProcessingFailedError('Email had no attached documents')
        else:
            logging.info("Email has %i attachment(s) " % len (mailMessage.attachments))

            for attach in mailMessage.attachments:
                name = attach[0] #this is the file name
                contents = str(attach[1]) #and this is the attached files contents
                logging.info("Attachment name: " + name )
                logging.info("Attachment contents: " + contents)
                vault = Vault()
                vault.fromAddress = fromAddress
                vault.subject = subject
                vault.date = date
                vault.name = name
                vault.contents = contents #.decode() EncodedPayload.decode()
                    vault.put()      

                #f = open("aardvark.txt", "r")
                #blah = f.read(30);
                #logging.info("the examined string is : " + blah)
                #f.close() # Close opened file

app = webapp.WSGIApplication([
  ProcessEmail.mapping()
], debug=True)

def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main()

这里是 basecontroller.py

from authController import *
from handle_incoming_email import *
import logging
import os
import webapp2
import jinja2
import wsgiref.handlers

from google.appengine.ext.webapp import template 
from google.appengine.ext import db
from google.appengine.api import users 

TEMPLATE_DIR = os.path.join(os.path.dirname(__file__))
jinja_environment = \
    jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_DIR))

class Vault(db.Model):
    #fromAddress= db.UserProperty()
    fromAddress= db.StringProperty()
    subject = db.StringProperty(multiline=True)
    #date = db.DateTimeProperty(auto_now_add=True)
    date = db.StringProperty(multiline=True)
    name = db.StringProperty(multiline=True)

class MainPage(webapp2.RequestHandler):    
    def get(self):
        logging.info("this is MainPage in baseController")
        list = db.GqlQuery("SELECT * FROM Vault ORDER BY date DESC").fetch(10)
        logging.info("this is in list: " + str(list))

        vault = Vault()

        fromAddress = vault.fromAddress
        subject = vault.subject
        date = vault.date
        name = vault.name

        values = {
                'fromAddress': fromAddress,
            'subject': subject,
            'date': date,
            'name': name,
            }
        templ = jinja_environment.get_template('index.html')
        self.response.out.write(templ.render(values))                        

def main():
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
  main()

我在一个教程中读到,渲染模板比只使用 .py 中的 html 更好,但也许我把它分解成太多的文件?他们的逻辑是,不同的人做前端和后端,所以现在就习惯了。无论如何,上面打算渲染到 index.html 是:

index.html

{% extends "base.html" %}
{% block title %} racetracer {% endblock %}
{% block content %}
<h1>Racetracer </h1>
<h3>Files recently received :</h3>
<br>
        <table>
        <tr>
            <th>Email address:                  </th>
            <th>-----------                     </th>
            <th>Subject:                        </th>
            <th>Date Received:                  </th>
            <th>Attachment:                     </th>
        </tr>           
        <tr>                
            <td> {{ fromAddress }}              </td>
            <td> ---------------                </td>   
            <td> {{ subject }}                  </td>
            <td> {{ date }}                     </td>
            <td> {{ name }}                     </td>
        <blockquote>{{ content|escape }}</blockquote>                     
        </p>
        </tr>                               
    </tr>    
    </table>      
<br>

<hr>
<form action="/sign" method="post">
    <textarea name="content" rows="1" cols="20"></textarea>
    <input type="submit" value="Submit (in index:)">
</form>
{% endblock %}

和 base.html....

<html><head>
<link type="text/css" rel="stylesheet" href="/static/css/main.css" /></head>

<body> From the file base out in the racetracer folder<br>
right now you are logged in as : 
    {% if user %}
        {{ user.nickname }}!
        [<a href="{{ logout }}"><b>sign out</b></a>]
    {% else %}
        anonymous, who are you?
        [<a href="{{ login }}"><b>sign in</b></a>]
    {% endif %}
    {% block content %}
    {% endblock %}
</body></html>

这里是 main.py

import os
import webapp2
from handle_incoming_email import *
from baseController import *
from authController import *
from google.appengine.ext.webapp import template 

app = webapp2.WSGIApplication([
    ('/', MainPage),
    #('/ProcessEmail', ProcessEmail),
], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
  main()

感谢您的帮助!将不胜感激。

【问题讨论】:

  • 你应该将你的模型移动到一个文件中并将它导入到你不同的处理程序中,很容易引入各种错误,因为你有 2 个单独的 Vault 实现。
  • 好的,谢谢蒂姆。所以我会制作一个model.py 文件,它只包含上面的class vault,并在需要时添加from model.py import *,是吗?不确定这会改变渲染问题的任何内容吗???
  • 是的,我并没有解决你的实际问题,需要大量的代码来处理 :-) 但是重复的类作为一个等待咬的一般问题突出:-)

标签: python-2.7 google-app-engine rendering google-cloud-datastore


【解决方案1】:

你得到 None 因为它是 None。您正在声明 Vault 对象,但没有为其分配任何值。作为 GQL 查询的结果,这些值将位于列表实体中。

vault = Vault() # This creates an empty object (assuming you aren't doing any dynamic init

fromAddress = vault.fromAddress  # Still empty....
subject = vault.subject
date = vault.date
name = vault.name

此外,您不应将 list 分配为 var,因为它是为 Py 保留的。

你想要做的是设置如下:

my_list = YOUR GQL QUERY.fetch()

# Create a formatted list
values = []
for ml in my_list:
    value = {
            'fromAddress': ml.fromAddress,
        'subject': ml.subject,
        'date': ml.date,
        'name': ml.name,
        }

    values.append(value) # You could just append the dictionary directly here, of course

然后使用模板参数中的值列表

** 更新**

与您的数据存储库模型相比,您的 GQL 查询看起来不错。

首先,确保您已将“list”变量更改为“my_list”。 接下来,如果您想查看检索到的对象的内容打印为可读字符串, 将此添加到您的模型中:

    def __unicode__(self):
       return ('%s %s %s' % (self.key,self.fromAddress,self.subject)) # etc... for the vars you want printed with you print the object

检查您的 logging.info(my_list) 并查看它是否打印出更具可读性的内容。

如果没有,请在列表上运行 for 循环并记录键和/或 fromAddress,因此:

for vault in my_list:
   logging.info('the key = %s'%vault.key)

如果没有返回任何内容,请直接转到开发环境中的交互式控制台并运行该查询:

from google.appengine.ext import db
from *vault_file* import Vault

my_list = db.GqlQuery("SELECT * FROM Vault ORDER BY date DESC").fetch(10) # run query

for vault in my_list:
   print vault.key
   print vault.fromAddress

让我知道这些测试给你留下了什么,我会继续更新。

* 更新 #2 *

现在您可以确认获取数据存储区值
你想设置一个模板页面参数等于 Vault 列表,所以:

params = dict(values=my_list)
self.response.out.write(templ.render(params)) 

现在在您的页面上,您需要遍历列表以打印每个字典项:

{% for vault in values %}
    <tr>
       <td>{{vault.fromAddress}}}</td>
       etc...
    </tr>

{% endfor %}

那行吗?

【讨论】:

  • 谢谢凯文。我按照您所说的更改了代码,但是 html 页面上没有任何内容(甚至之前的 none 也没有)。有一件事,我在my_list = db.GqlQuery("SELECT * FROM Vault ORDER BY date DESC").fetch(10) logging.info("this is in my_list: " + str(my_list)) 中注意到,在日志中这一行产生INFO 2013-03-26 22:32:24,828 baseController.py:36] this is in list: []。这是否意味着 Vault 已正确写入?你认为我接下来应该看哪里?再次感谢。达沃
  • AND....当我部署应用程序,然后查看日志时,我得到this is in my_list: [&lt;handle_incoming_email.Vault object at 0xfce6c870&gt;, &lt;handle_incoming_email.Vault object at 0xfce6cad0&gt;, &lt;handle_incoming_email.Vault object at 0xfce6c9d0&gt;, &lt;handle_incoming_email.Vault object at 0xfce6cd90&gt;, ... 等。那么我如何最好地将这些转换为字符串?
  • 您的日志看起来好像您的查询没有返回任何结果,所以让我们开始吧。您能否验证您的数据存储区中有哪些内容?
  • 另外,您应该尝试 ndb 并运行 ndb api 查询与 GQL,尤其是像您所拥有的那样的简单查询。 developers.google.com/appengine/docs/python/ndb
  • 谢谢凯文。我一直在阅读 NDB,但现在让我们坚持使用 GQL。我认为当你说 你不应该将 list 分配为 var 因为它是为 Py 保留的 时,你可能会赚钱,但我不知道该去哪里。首先确定数据存储:这是“数据存储查看器”窗口<click this now> 的屏幕截图。在我看来,我发送到appspotmail.com 地址的电子邮件中的内容存储正常......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多