views:

57

answers:

2

I am learning Python/Django and my pet project is a photo sharing website. I would like to give users the ability to upload their photos using an email address like Posterous, Tumblr. Research has led me to believe I need to use the following:

-- cron job -- python mail parser -- cURL or libcurl -- something that updates my database

How all these parts will work together is still where I need clarification. I know the cron will run a script that parses the email (sounds simple when reading), but how to get started with all these things is daunting. Any help in pointing me in the right direction, tutorials, or an answer would be greatly appreciated.

A: 

Not sure what you need cURL for in that list - what's it supposed to be doing?

You don't really say where you're having trouble. It seems to me you can do all this in a Django management command, which can be triggered on a regular cron. The standard Python library contains everything you need to access the mailbox (smtplib) and parse the message to get the image (email and email.message). The script can then simply save the image file to the relevant place on disk, and create a matching entry in the database via the normal Django ORM.

Daniel Roseman
+1  A: 

Read messages from maildir. It's not optimized but show how You can parse emails. Of course you should store information about files and users to database. Import models into this code and make right inserts.

import mailbox
import sys
import email
import os
import errno
import mimetypes


mdir = mailbox.Maildir(sys.argv [1], email.message_from_file)


for mdir_msg in mdir:
    counter = 1
    msg = email.message_from_string(str(mdir_msg))
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        fp = open(os.path.join('kupa', filename), 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close()
        #photomodel imported from yourapp.models
        photo = PhotoModel()
        photo.name = os.path.join('kupa', filename)
        photo.email = ....
        photo.save()
iddqd
You will need to import the model
Andrew Sledge
and this script would be called by the cron?
django-d