我在访问数据存储区实体时遇到问题。我是GAE和Python的新手,所以要善待。我一直在从在线教程和其他示例代码中获取代码,到目前为止一切顺利。
最终我希望能够剥离电子邮件附件,对文件进行一些简单的更改并与其他.kml文件合并(甚至更好.kmz,但一次只能做一件事:) 。
步骤1。是发送电子邮件到应用程序的appspotmail地址=完成:)
步骤2。 ...写入db.model =我可以在仪表板/数据存储区查看器中看到实体在那里,所以没问题=完成:)
步骤3。 - 渲染模板以显示最近收到的20封电子邮件。这个列表会动态更新..... :(嗯)
相反,我看到none
为index.html中的所有变量呈现了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
。你能指点我正确的方向吗?谢谢!
DAV-O
这里是yaml.app
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()
这里是handle_incoming_email.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()
这是basecontroller.py
{% 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 %}
我在教程中读到,渲染模板比使用.py中的html更优越,但也许我已经在太多文件中将其分解了?他们的逻辑是不同的人做前端和后端,所以现在就习惯了。无论如何,上面打算渲染到index.html,它是:
的index.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>
和base.html ....
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()
这是main.py
{{1}}
感谢您的帮助!非常感谢。
答案 0 :(得分:1)
你得到的是因为它是无。您正在声明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
然后使用模板参数中的值列表
**更新**
与数据存储库模型相比,您的GQL查询看起来不错。
首先,确保您已将'list'var更改为'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 %}
那工作?