Archive - January, 2012

python ftp and get recent file

the following is a script which downloads the latest image from  one of the NASA ftp server at eol.jsc.nasa.gov and to my amazement there are new images every 5 mins!, so I sent python to grab that image….

python supports ftp by importing the ftplib module and ftplib.FTP class.

connecting to an ftp server is very straightforward…

1
2
3
4
5
>>>from ftplib import FTP
>>>f = FTP('my ftp server ')
>>>f.login('anonymous', 'your@email.address')
:
>>>f.quit()

The core job inside in this script is to first dump the listing of files into a list, then reading that list line by line, split the date and convert it to a datetime object and store it in a new list, also i created another list which stores the filenames, next i combined these two lists to form a dictionary, and sorted the dictionary using the KEY(datetime object) in reverse order, and ran the loop only once as i need only the first image.

here is the full script..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python

import ftplib
import os
import socket
import sys
import time
import datetime

HOST = 'eol.jsc.nasa.gov'


def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print 'cannot reach to %s' % HOST
        return
    print "Connect to ftp server"

    try:
        f.login('anonymous','alpha@krisindigitalage.com')
    except ftplib.error_perm:
        print 'cannot login anonymously'
        f.quit()
        return
    print "logged on to the ftp server"


    data = []
    f.dir(data.append)
    datelist = []
    filelist = []
    for line in data:
        col = line.split()
        datestr = ' '.join(line.split()[0:2])
        date = time.strptime(datestr, '%m-%d-%y %H:%M%p')
        datelist.append(date)
        filelist.append(col[3])

    combined = zip(datelist,filelist)
    new_dict = dict(combined)
#    print who
#    for key,value in sorted(new_dict.iteritems(), key =lambda (k,v): (v,k)):

    for key in sorted(who.iterkeys(), reverse=True):
       print "%s: %s" % (key,new_dict[key])
       filename = new_dict[key]
       print "file to download is %s" % filename
       try:
           f.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
       except ftplib.err_perm:
           print "Error: cannot read file %s" % filename
           os.unlink(filename)
       else:
           print "***Downloaded*** %s " % filename
       return

    f.quit()
    return


if __name__ == '__main__':
    main()
 

Active vs Passive Ftp

a simple diagram which shows the difference between active and passive ftp

ACTIVE FTP

 

PASSIVE FTP

 

 

generating a QRcode in Vcard format in python

You can create a QRcode using the python pygooglechart wrapper for Google chart API. Here i used the wrapper to generate the QRcode as a django app but right now I wont go into the specifics of how to create a django app, maybe will do later,

but this is the view i made for the qr app, i passed the form results to the QRChart and formatted the results in a Vcard format and its then rendered to the page.

You can see the script in action here

http://www.cacoos.com/qr/

test it using an QR android/iphone app

Now the Views….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.template.loader import get_template
from django.template import Template, Context
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from cacoos_com.qr.qr_form import QrForm
from pygooglechart import QRChart


def qr(request):
    if request.method == 'POST':
        qform = QrForm(request.POST)
        if qform.is_valid():
            qc = qform.cleaned_data
            chart = QRChart(300,300)
            mecard = "BEGIN:VCARD"+"\n"+"VERSION:3.0 \n"+"FN:"+qc['name']+"\n"+"TEL;type=CELL:"+qc['phone']+"\n"+"EMAIL;type=INTERNET;type=WORK;type=pref:"+qc['email']+"\n"+"URL;type=pref:"+qc['url']+"\n"
            chart.add_data(mecard)
            chart.set_ec('H', 0)
            chart.download('/usr/share/pyshared/django/contrib/admin/media/qr-hello.png')
            return render_to_response('qr_results.html', {'url': qc['url'] })
    else:
        qform = QrForm(initial={'url': 'type your url here'})
    return render_to_response('qr_form.html', {'form': qform})

You can use the following template to generate a Vcard, quite handy…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;;
FN:John Doe
ORG:Example.com Inc.;
TITLE:Imaginary test person
EMAIL;type=INTERNET;type=WORK;type=pref:johnDoe@example.org
TEL;type=WORK;type=pref:+1 617 555 1212
TEL;type=CELL:+1 781 555 1212
TEL;type=HOME:+1 202 555 1212
TEL;type=WORK:+1 (617) 555-1234
item1.ADR;type=WORK:;;2 Example Avenue;Anytown;NY;01111;USA
item1.X-ABADR:us
item2.ADR;type=HOME;type=pref:;;3 Acacia Avenue;Newtown;MA;02222;USA
item2.X-ABADR:us
NOTE:John Doe has a long and varied history\, being documented on more police files that anyone else. Reports of his death are alas numerous.
item3.URL;type=pref:http\://www.example/com/doe
item3.X-ABLabel:_$!<HomePage>!$_
item4.URL:http\://www.example.com/Joe/foaf.df
item4.X-ABLabel:FOAF
item5.X-ABRELATEDNAMES;type=pref:Jane Doe
item5.X-ABLabel:_$!<Friend>!$_
CATEGORIES:Work,Test group
X-ABUID:5AD380FD-B2DE-4261-BA99-DE1D1DB52FBE\:ABPerson
END:VCARD
 
Page 1 of 11
Theme Tweaker by Unreal