User:Andre Castro/prototyping/1.2/traces: Difference between revisions

From XPUB & Lens-Based wiki
Line 15: Line 15:
TO DO: date format not necessarily the best format - check others
TO DO: date format not necessarily the best format - check others


http://pzwart3.wdka.hro.nl/~acastro/traces/email_form_handler-test.cgi
http://pzwart3.wdka.hro.nl/~acastro/cgi-bin/traces_form_handler.cgi:


<source lang="python">
<source lang="python">
Line 21: Line 21:
import cgi, cgitb, lxml.etree, datetime, os
import cgi, cgitb, lxml.etree, datetime, os


today = datetime.datetime.now().strftime("%Y%m%d") #not sure is this is the best format
today = datetime.datetime.now().strftime("%Y-%m-%d") #not sure is this is the best format


# Create instance of FieldStorage  
# Create instance of FieldStorage  
Line 33: Line 33:
print "<TITLE>Form</TITLE>"
print "<TITLE>Form</TITLE>"
print "<H4>Your form was successfully added.<br />Shortly you will receive a message at %s </H4>" % (email)
print "<H4>Your form was successfully added.<br />Shortly you will receive a message at %s </H4>" % (email)


#APPEND EMAIL AND DATE TO XML FILE
#APPEND EMAIL AND DATE TO XML FILE
if os.path.exists('../traces/email-database.xml'):
if os.path.exists('traces-email-database.xml'):
print   
print   
else:  
else:
root = lxml.etree.Element('email-address')
root = lxml.etree.Element('email-address')
son = lxml.etree.SubElement(root, 'entries')
son = lxml.etree.SubElement(root, 'entries')
tree = lxml.etree.ElementTree(root)
tree = lxml.etree.ElementTree(root)
tree.write('../traces/email-database.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
tree.write('traces-email-database.xml', pretty_print=True, xml_declaration=True,encoding='utf-8')
tree.close()


doc = lxml.etree.parse(database_url) #f = 'email-database.xml'


#f = 'email-database.xml'
doc = lxml.etree.parse('traces-email-database.xml')
entries = doc.find('entries') # find root element
entries = doc.find('entries') # find root element
#print entries


#append date SubElement date
#check if todays date element is present
date = lxml.etree.SubElement(entries, "date", attrib={'date':today} )   
if today not in doc.xpath('//@date'):
date = lxml.etree.SubElement(entries, "date", attrib={'date':today} ) #append date SubElement date
addrs = lxml.etree.SubElement(date, "address")#append grandchild
addrs.text = email
doc.write('traces-email-database.xml', xml_declaration=True, encoding='utf-8') #write
else:
date_node = "//date[@date="+today+"]"
date = doc.xpath(date_node)
addrs = lxml.etree.SubElement(date[0], "address")#append grandchild
addrs.text = email
doc.write('traces-email-database.xml', xml_declaration=True,  encoding='utf-8')#write


#append grandchild
addrs = lxml.etree.SubElement(date, "address")
addrs.text = email
#write
doc.write('../traces/email-database.xml', xml_declaration=True,  encoding='utf-8')
#print(lxml.etree.tostring(doc))
</source>
</source>
email-database.xml structure:
<source lang="xml">
<email-address>
  <entries>
<date date="20120216">
<address>test@test.org</address>
<address>test2@test.org</address>
</date>
  </entries>
</email-address>
</source>


==******part2******==
==******part2******==

Revision as of 16:43, 23 February 2012

Links

https://docs.google.com/Doc?docid=dcwxmjc8_17pr7bbsgz original text

http://pzwart3.wdka.hro.nl/~slorusso/email-form.html

http://pzwart3.wdka.hro.nl/~acastro/cgi-bin/traees_form_handler.cgi

******part1******

Form and email / date appending email-database.xml

  • online form
  • cgi receives email address and appends it to email-database.xml file

TO DO: date format not necessarily the best format - check others

http://pzwart3.wdka.hro.nl/~acastro/cgi-bin/traces_form_handler.cgi:

#!/usr/bin/python2.6
import cgi, cgitb, lxml.etree, datetime, os

today = datetime.datetime.now().strftime("%Y-%m-%d") #not sure is this is the best format

# Create instance of FieldStorage 
form = cgi.FieldStorage() 
# Get email from form 
email = form.getvalue('email') 


print "Content-Type: text/html"  
print                         
print "<TITLE>Form</TITLE>"
print "<H4>Your form was successfully added.<br />Shortly you will receive a message at %s </H4>" % (email)


#APPEND EMAIL AND DATE TO XML FILE
if os.path.exists('traces-email-database.xml'):
	print  
else:  
	root = lxml.etree.Element('email-address')
	son = lxml.etree.SubElement(root, 'entries')
	tree = lxml.etree.ElementTree(root)
	tree.write('traces-email-database.xml', pretty_print=True, xml_declaration=True,encoding='utf-8')
	tree.close()


	#f = 'email-database.xml'
doc = lxml.etree.parse('traces-email-database.xml')
entries = doc.find('entries') # find root element
#print entries

#check if todays date element is present
if today not in doc.xpath('//@date'):
	date = lxml.etree.SubElement(entries, "date", attrib={'date':today} )  	#append date SubElement date
	addrs = lxml.etree.SubElement(date, "address")#append grandchild
	addrs.text = email
	doc.write('traces-email-database.xml', xml_declaration=True,  encoding='utf-8') #write
else:
	date_node = "//date[@date="+today+"]"
	date = doc.xpath(date_node)
	addrs = lxml.etree.SubElement(date[0], "address")#append grandchild
	addrs.text = email
	doc.write('traces-email-database.xml', xml_declaration=True,  encoding='utf-8')#write

******part2******

Days and Emails calculations

Other py script which:

  • parse the email-database.xml (every day)

Script which parses xml database. Checks the dates and email address under each dat3.

According the date decide what part of story will be told

#! /usr/bin/python
# coding: utf-8
import lxml.etree, urllib2
#Script which parses xml database. Checks the dates and email address under each date
 
f = ('traces-email-database.xml') # change to local
#f = urllib2.urlopen('http://pzwart3.wdka.hro.nl/~acastro/cgi-bin/traces-email-database.xml') #ERROR! ??permissions
 
 
doc = lxml.etree.parse(f)
 
# find dates
dates = doc.xpath('//date')



#create the dictionary {date: [address, address]}
dateDict = {}
for date in dates:
    #print lxml.etree.tostring(date)
    date_is_attr = date.get("date")
    myAddrs = doc.xpath("//date[@date='{0}']/address/text()".format(date_is_attr))
    dateDict[date_is_attr] = myAddrs


# compare the dates with the current
from datetime import *
import re
today = str(date.today())
yesterday = str(date.today()-timedelta(days=1))
beforeyesterday = str(date.today()-timedelta(days=2))



for date, addrs in dateDict.iteritems():
    #print date
    #print addrs
    print
    if str(date) == today :
        print "send first mail to:"
        for a in addrs :
            print a
    elif date == yesterday :
        print "send second mail to:"
        for a in addrs :
            print a
    elif date == beforeyesterday : 
        print "send third mail to:"
        for a in addrs :
            print a


  • check the dates
  • see what section of the text needs to send to whom


**part3 Email the sections**

  • multipart email - allows imgs attachments
import smtplib, email.utils
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

#Reference: http://docs.python.org/library/email-examples.html


# address list
addr = ['andrecastro@c-e-m.org', 'andrecastro83@gmail.com']#, 'silviolorusso@gmail.com']

msg = MIMEMultipart()
#msg = MIMEText('This is the b@dy of the message.') #Create the message (simple ASCII)
msg['To'] = email.utils.formataddr(('Recipient', 'readers@traces.net'))
msg['From'] = email.utils.formataddr(('Traces', 'traces@noreply.net'))
msg['Subject'] = 'Traces Multipart - test'

msg.attach( MIMEText('This is the b@dy of the email') )

#attach a picture
fp = open('animpnky_e0.gif', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)


server = smtplib.SMTP('mail')
server.set_debuglevel(False) # show communication with the server
try:
    server.sendmail('traces@noreply.net', addr, msg.as_string())
finally:
    server.quit()


  • text email - plain text
import smtplib, email.utils
from email.mime.text import MIMEText

# address list
addr = ['andrecastro@c-e-m.org', 'andrecastro83@gmail.com']
#, 'silviolorusso@gmail.com']

msg = MIMEText('This is the b@dy of the message.') #Create the message (simple ASCII)
msg['To'] = email.utils.formataddr(('Recipient', 'readers@traces.net'))
msg['From'] = email.utils.formataddr(('Traces', 'traces@noreply.net'))
msg['Subject'] = 'Traces plain - test '


server = smtplib.SMTP('mail')
server.set_debuglevel(False) # show communication with the server
try:
    server.sendmail('traces@noreply.net', addr, msg.as_string())
finally:
    server.quit()