编写和图像附加到数据存储作为头像:是可能吗? [英] Writing and image attachment to datastore as an avatar: Is it possible?

查看:116
本文介绍了编写和图像附加到数据存储作为头像:是可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人在收到的电子邮件中处理附件?我在想,而不是用户上传图像,而是可以发送它作为附件,我可以使用它上传到数据存储。



文档有发送附件,但是找不到有关接收附件的文档。 此页面说


附件



邮件的文件附件,作为两值元组的列表,每个附件的一个元组。



每个元组包含文件名作为第一个元素,文件内容作为第二个元素。



附件文件必须是允许的文件类型之一,文件名必须以与类型相对应的扩展名结尾。有关允许的类型和文件名扩展名的列表,请参阅概述:附件。


我认为这也是发送电子邮件。 >

我有这个代码将图像保存到数据存储区:

  class AvatarSave webapp.RequestHandler):
def post(self):
q = User.all()
q.filter(userEmail =,emailAddress)
qTable = q.fetch 10)
如果qTable:
在qTable中的行:
avatar = images.resize(self.request.get(img),50,50)
row.avatar = db.Blob(avatar)
db.put(qTable)
else:
self.response.out.write(user not found)

self .redirect('/')

直观上,似乎 message.attachment 而不是img会做的伎俩。

  avatar = images.resize(self.request.get(message.attachment),50,50)

你觉得怎么样?谢谢。






Update2 (作为回复Nick Johnson评论的新代码)

 类注册(InboundMailHandler):
def receive(self,message):
senderEmail = message.sender
emailTuple = parseaddr(senderEmail)
emailUserName = emailTuple [0]
emailAddress = emailTuple [1]
newAvatar = db.Blob(images.resize(goodDecode(message.attachments [0] [1] ),50,50))
newUser = User(userEmail = emailAddress,
userName = emailUserName,
avatar = newAvatar)

db.put(newUser)






Update1



对于记录,对于有相同问题的任何人,请注意消息属性附件s 附件

 消息。附件

给出了 AttributeError

  AttributeError:'InboundEmailMessage'对象没有属性'attachment'

对象 message.attachment 如下所示:

  [('portrait.png',< EncodedPayload payload =#8461006914571150170 encoding = base64>)] 

所以正确的方式来拉< EncodedPayload payload =#8461006914571150170 encoding = base64> part是

  avatar = images.resize(goodDecode(message.attachments [0] [1]),50,50)
/ pre>

我发布的原始代码

 头像= images.resize(goodDecode(message.attachments [1]),50,50)

工作很明显。



再次感谢 jesmith Robert Kluin 作为答案。






Update0 (关于 jesmith 的答案)



在我的情况下,我从用户上传的表单中获取图片img,并将其写入数据存储区:

  for qTable中的行:
avatar = images.resize(self.request.get(img),50,50)
行。 avatar = db.Blob(avatar)
db.put(qTable)
self.redirect('/')
else:
logging.info(else user not found )
self.redirect('/ user-not-found')

在你的代码这相当于这一节,我相信:

  try:
if hasattr(message,attachment):
for a in message.attachments:
msg.attachmentNames.append(a [0])
msg.attachmentContents.append(append(db.Blob(goodDecode(a [1])) )
msg.put()
除了:
logging.exception(来自%s的电子邮件中的附件解码%message.sender)
假设在我的情况下,只有1个附件;

如何拿起附件的数据部分?



是否 message.attachment [1]

  avatar = images.resize(message.attachment [1],50,50)

message.attachment [1] 附件的数据部分?



谢谢!

解决方案

这是一封来自邮件的片段处理程序我使用:

  bodies = message.bodies(content_type ='text / html')
allBodies = u ;
身体中的身体:
allBodies = allBodies + u\\\
+ unicode(goodDecode(body [1]),errors =ignore)
如果不是全部身体:
bodies = message.bodies(content_type ='text / plain')
在body中的body:
allBodies = allBodies + u\\\
+ unicode(goodDecode(body [1]), errors =ignore)

msg = EmailMessageModel()
...填写各种内容...
msg.sender = message.sender
msg。 date = datetime.datetime.now()
msg.message = allBodies
#在处理附件之前调用put(),因为看起来可能会抛出各种异常
msg.put()
event.email = True
event.put()
event.project.email = True
event.project.put()
#附件是一个元素列表对包含文件名和内容。

try:
if hasattr(message,'attachments'):
for a in message.attachments:
msg.attachmentNames.append(a [0])
msg.attachmentContents.append(db.Blob(goodDecode(a [1])))
msg.put()
除了:
logging.exception(异常解码附件在%s%message.sender的电子邮件中

请注意,goodDecode是我写的一个函数,因为是底层GAE解码中的一个错误(它降低了所有的,基于base64编码的文本):

  def goodDecode(encodedPayload) :
如果不是hasattr(encodedPayload,'encoding'):
返回encodedPayload
encoding = encodedPayload.encoding
payload = encodedPayload.payload
如果encoding and encoding.lower ()!='7bit':
payload = payload.decode(encoding)
返回有效负载

这可能不是必需的,因为我是在我的情况下,我将附件填充到数据库中:

  class EmailMessageModel(db.Model):
....各种东西...
sender = db.StringProperty()
date = db。 DateTimeProperty()
message = db.TextProperty()
attachmentNames = db.StringListProperty()
attachmentContents = db.ListProperty(db.Blob)

当我想显示此电子邮件时,我使用这个:

 < h2> {{e.sender}} {{e.date | date:M j,Y f A}} GMT< / h2> 
< p> From:{{e.sender}}< br />日期:{{e.date | date:M j,Y f A}} GMT({{e.date | timesince}}之前)< br />主题:{{e.subject}}< / p>
{%如果e.attachmentNames%}
< p>附件:
{%e.attachmentNames%}
< a href =/ admin / attachment ?email = {{e.key}}& index = {{forloop.counter0}}target =_ blank> {{a}}< / a>
{%endfor%}
< / p>
{%endif%}
< div style ='background-color:white'> {{e.message}}< / div>

附件处理程序是:

  class AttachmentHandler(webapp.RequestHandler):
def get(self):
email = EmailMessageModel.get(self.request.get('email'))
index = self.request.get('index')
如果索引:
index = int(index)
filename = email.attachmentNames [index]
self.response。 header ['Content-Type'] = str(mimetypes.guess_type(filename)[0])或'application / octet-stream'
self.response.out.write(email.attachmentContents [index])

(所以,基本上,我让浏览器弄清楚附件如何处理。 p>

希望这有帮助!


Has anyone worked with attachments in received emails? I was thinking, instead of the user uploading an image they can send it as an attachment that I can use to upload to datastore.

The documentation has sending attachments but I could not find any documentation about receiving attachments. This page says:

attachments

The file attachments for the message, as a list of two-value tuples, one tuple for each attachment.

Each tuple contains a filename as the first element, and the file contents as the second element.

An attachment file must be one of the allowed file types, and the filename must end with an extension that corresponds with the type. For a list of allowed types and filename extensions, see Overview: Attachments.

I think this is also about sending email.

I have this code to save the image to datastore:

class AvatarSave(webapp.RequestHandler):
    def post(self):
        q = User.all()
        q.filter("userEmail =", emailAddress)
        qTable = q.fetch(10)
        if qTable:
            for row in qTable:
                avatar = images.resize(self.request.get("img"), 50, 50)
                row.avatar = db.Blob(avatar)
            db.put(qTable)
        else:
            self.response.out.write("user not found")

        self.redirect('/')

Intuitively, it seems that message.attachment instead of "img" will do the trick.

avatar = images.resize(self.request.get(message.attachment), 50, 50)

What do you think? Thanks.


Update2 (New code as response to Nick Johnson's comment)

class Register(InboundMailHandler):
    def receive(self, message):
        senderEmail = message.sender
        emailTuple = parseaddr(senderEmail)
        emailUserName = emailTuple[0]
        emailAddress = emailTuple[1]
        newAvatar = db.Blob(images.resize(goodDecode(message.attachments[0][1]), 50, 50))        
        newUser = User(userEmail=emailAddress,
                       userName=emailUserName,
                       avatar=newAvatar)

        db.put(newUser)


Update1 Problem solved:

For the record, and for anyone who has the same question please note that the attribute of message is attachments not attachment:

message.attachment

gives the AttributeError

AttributeError: 'InboundEmailMessage' object has no attribute 'attachment'

And the object message.attachment looks like this:

[('portrait.png', <EncodedPayload payload=#8461006914571150170 encoding=base64>)]

so the correct way to pull the <EncodedPayload payload=#8461006914571150170 encoding=base64> part is

avatar = images.resize(goodDecode(message.attachments[0][1]), 50, 50)

The original code that I posted has

avatar = images.resize(goodDecode(message.attachments[1]), 50, 50)

which does not work, obviously.

Thanks again to jesmith and Robert Kluin for answers.


Update0 (regarding the answer by jesmith)

In my case, I am taking an image "img" from a form uploaded by a user and write it to datastore like this:

       for row in qTable:
            avatar = images.resize(self.request.get("img"), 50, 50)
            row.avatar = db.Blob(avatar)    
        db.put(qTable)
        self.redirect('/')
    else:
        logging.info("else user not found")
        self.redirect('/user-not-found')

In your code this corresponds to this section, I believe:

try:
    if hasattr(message, "attachment"):
        for a in message.attachments:
            msg.attachmentNames.append(a[0])
            msg.attachmentContents.append(append(db.Blob(goodDecode(a[1])))
        msg.put()        
except:
    logging.exception("exception decoding attachments in email from %s" % message.sender)

assuming that, in my case, there is only 1 attachment; how do I pick up the data part of the attachment?

Is it message.attachment[1] ?

avatar = images.resize(message.attachment[1], 50, 50)

is message.attachment[1] data part of the attachment?

Thanks!

解决方案

This is a fragment from an incoming mail handler I use:

   bodies = message.bodies(content_type='text/html')
    allBodies = u"";
    for body in bodies:
      allBodies = allBodies + u"\n" + unicode(goodDecode(body[1]), errors="ignore")
    if not allBodies:
      bodies = message.bodies(content_type='text/plain')
      for body in bodies:
        allBodies = allBodies + u"\n" + unicode(goodDecode(body[1]), errors="ignore")

    msg = EmailMessageModel()
...fill in various stuff...
    msg.sender = message.sender
    msg.date = datetime.datetime.now()
    msg.message = allBodies
    # Calling put() before dealing with attachments because it seems like that could throw various exceptions
    msg.put()
    event.email = True
    event.put()
    event.project.email = True
    event.project.put()
    # attachments is a list of element pairs containing file names and contents.

    try:
      if hasattr(message, 'attachments'):
        for a in message.attachments:
          msg.attachmentNames.append(a[0])
          msg.attachmentContents.append(db.Blob(goodDecode(a[1])))
        msg.put()
    except:
      logging.exception("Exception decoding attachments in email from %s" % message.sender)

Note that goodDecode is a function I wrote because there was a bug in the underlying GAE decode (it lowercased everything, which munged base64-encoded text):

def goodDecode(encodedPayload):
  if not hasattr(encodedPayload, 'encoding'):
    return encodedPayload
  encoding = encodedPayload.encoding
  payload = encodedPayload.payload
  if encoding and encoding.lower() != '7bit':
    payload = payload.decode(encoding)
  return payload

This is probably not necessary any more, because I'm pretty sure they fixed that bug.

In my case, I'm stuffing the attachments into the database:

class EmailMessageModel(db.Model):
....various stuff...
  sender = db.StringProperty()
  date = db.DateTimeProperty()
  message = db.TextProperty()
  attachmentNames = db.StringListProperty()
  attachmentContents = db.ListProperty(db.Blob)

When I want to show this email, I'm using this:

<h2>{{ e.sender }} {{ e.date|date:"M j, Y f A " }} GMT</h2>
<p>From: {{ e.sender }}<br/>Date: {{ e.date|date:"M j, Y f A" }} GMT ({{ e.date|timesince }} ago)<br/>Subject: {{ e.subject }}</p>
{% if e.attachmentNames %}
<p>Attachments: 
  {% for a in e.attachmentNames %}
<a href="/admin/attachment?email={{ e.key }}&index={{ forloop.counter0 }}" target="_blank">{{ a }}</a>
  {% endfor %}
</p>
{% endif %}
<div style='background-color: white'>{{ e.message }}</div>

The attachment handler is:

class AttachmentHandler(webapp.RequestHandler):
  def get(self):
    email = EmailMessageModel.get(self.request.get('email'))
    index = self.request.get('index')
    if index:
      index = int(index)
      filename = email.attachmentNames[index]
      self.response.headers['Content-Type'] = str(mimetypes.guess_type(filename)[0]) or 'application/octet-stream'
      self.response.out.write(email.attachmentContents[index])

(So, basically, I'm letting the browser figure out what to do with the attachments.)

Hope this helps!

这篇关于编写和图像附加到数据存储作为头像:是可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆