Python 2.7 GAE呈现';无';但我可以在数据存储查看器中看到db实体

Python 2.7 GAE呈现';无';但我可以在数据存储查看器中看到db实体,python-2.7,google-app-engine,rendering,google-cloud-datastore,Python 2.7,Google App Engine,Rendering,Google Cloud Datastore,我在访问数据存储实体时遇到问题。我对GAE和Python还不熟悉,所以要友善。我一直在从在线教程和其他示例代码中寻找代码,直到现在,这一切都很顺利 最终,我希望能够剥离电子邮件附件,对文件进行一些简单的更改,并与其他.kml文件合并(甚至更好的是.kmz,但每次只做一件事:) 第一步。将电子邮件发送到应用程序的appspotmail地址=完成:) 第二步。。。写入db.model=我可以在dashboard/datastore viewer中看到实体在那里,因此无问题=完成:) 步骤3-呈现一个

我在访问数据存储实体时遇到问题。我对GAE和Python还不熟悉,所以要友善。我一直在从在线教程和其他示例代码中寻找代码,直到现在,这一切都很顺利

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

第一步。将电子邮件发送到应用程序的appspotmail地址=完成:)

第二步。。。写入db.model=我可以在dashboard/datastore viewer中看到实体在那里,因此无问题=完成:)

步骤3-呈现一个模板以显示最近收到的电子邮件,例如20封。此列表将动态更新…:(嗯

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

达沃

这里是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\u incoming\u 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 %}

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

您将获得“无”,因为它是“无”。您正在声明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
另外,您不应该将列表指定为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
然后使用模板参数中的值列表

**更新**

与数据存储Vault模型相比,您的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_列表),看看它是否打印出更可读的内容

如果没有,请在列表上运行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 %}
{%用于vault中的值%}
{{vault.fromAddress}}}
等
{%endfor%}

工作正常吗?

您应该将模型移动到一个文件中,并将其导入到不同的处理程序中,因为您有两个单独的Vault实现,所以很容易引入各种错误。好的,谢谢Tim。因此,我将创建一个model.py文件,该文件由上面的
类Vault
组成,并添加
from model.py import*
无论何时需要,是吗?不确定这会改变渲染问题上的任何东西,但是???是的,我没有解决您的实际问题,因为有太多代码需要涉猎:-)但是复制类作为一个一般性问题突出出来等待解决:-)谢谢Kevin。正如您所说,我更改了代码,但是html页面上没有任何内容(甚至没有以前的
none
)。有一件事,我注意到在
my_list=db.GqlQuery(“按日期描述从保险库订单中选择*).fetch(10)logging.info(“这在我的列表中:“+str(我的列表))
中,此行在日志中生成
info 2013-03-26 22:32:24828 baseController.py:36]这在列表中:[]
。这是否意味着Vault已正确写入?你认为我下一步该去哪里?再次感谢。达夫奥德。。。。当我部署应用程序,然后查看日志时,我得到
这在我的列表中:[,,…
等。那么如何最好地将这些转换为字符串呢?您的日志看起来您的查询没有返回结果,所以让我们从这个开始。您可以验证您的数据存储中有什么吗?另外,您应该尝试ndb并运行ndb api查询,而不是GQL,特别是对于像您这样的简单查询。谢谢Kevin。我一直在阅读ndb,但让我们坚持w现在使用GQL。我想当你说你不应该将列表分配为var时,你可能是在花钱,因为这是为Py保留的,但我不知道该从哪里获取。首先确定数据存储:这是“数据存储查看器”窗口的屏幕截图。在我看来,我发送到appspotmail.com地址的电子邮件中的内容存储正常。。。
params = dict(values=my_list)
self.response.out.write(templ.render(params)) 
{% for vault in values %}
    <tr>
       <td>{{vault.fromAddress}}}</td>
       etc...
    </tr>

{% endfor %}