0

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

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

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

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

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

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

达沃

这是 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 ,即:

索引.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()

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

4

1 回答 1

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 *

因此,现在您可以确认获取数据存储区值
,您希望将模板页面参数设置为等于保管库列表,因此:

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

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

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

{% endfor %}

那个工作?

于 2013-03-26T14:46:06.473 回答