Python Framework for Symbian Series 60 phones

1 2 >

Monday 26 March 2007

Write the content of appuifw.Text() into a file

import e32, appuifw
 
def __exit__( ):
    APP_LOCK.signal( )
 
def doSave( ):
    try:
        f = open( 'c:\\yourFile.txt', 'wb' )
        yourText = appuifw.app.body.get( )
        f.write( yourText.encode("utf-8") )
        f.close
        appuifw.note( u'Saved :)', 'conf' )
        
    except IOError, e:
        appuifw.note( u'Wrong file path!', 'error' )
 
    except UnicodeError, e:
        appuifw.note( unicode( e ), 'error' )
 
 
if __name__ == "__main__":
    APP_LOCK = e32.Ao_lock( )
    appuifw.app.title = u'Text to file'
    appuifw.app.exit_key_handler = __exit__
    appuifw.app.body = appuifw.Text()
    appuifw.app.menu = [( u'Save', doSave ),
                        ( u'Exit', __exit__ )]
    APP_LOCK.wait( )

Use of Form

Here is an implementation that uses appuifw.Form I recently posted on the forum:

# Copyright (c) 2006-2007 LEFEVRE Damien
# appuifw.Form implementation example
 
import appuifw
 
## Simple MyFormView class to demonstrate the use of forms.
class MyFormView( object ):
    
    ## The constructor.
    def __init__( self ):
        ## Bool
        self._iIsSaved = False
 
        ## Model list.
        self._iModels = [u'6600', u'6630', u'7610', u'N90', u'N70']
        ## Form fields.
        self._iFields = [( u'Mobile', 'text', u'Nokia'),
                         ( u'Model', 'combo', ( self._iModels, 0 ) ),
                         ( u'Amount','number', 5 ),
                         ( u'Date','date' ),
                         ( u'Time','time' )]
 
 
    ## Displays the form.
    def setActive( self ):
        self._iIsSaved = False
        self._iForm = appuifw.Form(self._iFields, appuifw.FFormEditModeOnly)
        self._iForm.save_hook = self._markSaved
        self._iForm.flags = appuifw.FFormEditModeOnly
        self._iForm.execute( )
 
 
    ## save_hook send True if the form has been saved.
    def _markSaved( self, aBool ):
        self._iIsSaved = aBool
 
                
    ## _iIsSaved getter.
    def isSaved( self ):
        return self._iIsSaved
 
    # here you can put for example all the getters you need:
    #---------------------------------------------------------
 
    ## Return mobile field value.
    def getMobile( self ):
        return self._iForm[0][2].encode( "utf-8" )
 
 
    ## Return model field value..
    def getModel( self ):
        ## This would return the index
        #return self._iForm[1][2][1]
        ## This returns the model
        return self._iModels[self._iForm[1][2][1]].encode( "utf-8" )
 
 
    ## Return amount field value.
    def getAmount( self ):
        return self._iForm[2][2]
 
 
    ## Return date field value.
    def getDate( self ):
        return self._iForm[3][2]
 
 
    ## Return time field value.
    def getTime( self ):
        return self._iForm[4][2]    
 
 
 
if __name__ == "__main__":
    appuifw.app.title = u'Try Forms'
    myForm = MyFormView( )
    myForm.setActive( )
    if myForm.isSaved( ):
        print myForm.getMobile( )
        print myForm.getModel( )
        print myForm.getAmount( )
        print myForm.getDate( )
        print myForm.getTime( )

Tuesday 13 March 2007

Get XML file from the net and parse it

In that piece of source I demonstrate how I get info on a server via XML file. You just need to write the XML parser to extract an condition the data as you need.

For parsing XML documents, I'm using cElementTree ported on PyS60 by Simo Salminen (available 2nd & 3rd edition).

You need to write a server script that generate your XML document if it is not static. PHP, JSP, Python... Up to you :)

import httplib
 
class StockEngine( object ):
    def __init__( self, aHost, aPort=80 ):
        self._iHost = aHost
        self._iPort = aPort
 
        # creates connection with the server
        self._iConn = httplib.HTTPConnection( self._iHost, self._iPort )
 
 
    def get( self ):
        # tags are sent in the header
        headers = {
            "Content-type"  : "multipart/form-data",
            "Accept"        : "text/plain",
            # you can hide in the header some authentication info or relevant 
            # stuff
            "cipher"        : "blablablablablabla"
         }
 
        params = None
 
        # send a request
        self._iConn.request("POST",
                            "/yourPage/stock.jsp",  # could also be php or 
                                                    # others...
                            params,                 # here you can put some 
                                                    # parameter to get only one
                                                    # category of product for 
                                                    # example
                            headers)
 
        # get the response to be parsed from the server
        response = self._iConn.getresponse()
 
        # status == 200 means that the request was successfully received
        if response.status == 200:
            # parse login to extrat statement and UID
            try:
                return self._parseStock( response.read( ) )
            except:
                return False
        else:
            return False
 
    def _parseStock( self, aSting ):
        stock = None
        # parse document from string
        # write your own parser here to store in stock
        return stock
 
 
    def __del__( self ):
        # make sure that the connection is closed
        if self._iConn:
            self._iConn.close( )
            
if __name__ == "__main__":
    stockEngine = StockEngine( "yourHostServer.XXX" )
    stock = stockEngine.get()
    print stock

Thursday 15 February 2007

Upload file to URL with multipart/form-data

First of all make sure to download HTTPFileUploader and install in as a library.

Client source:

import os
from HTTPFileUploader import * # uploader class
 
# path of the file to download
filePath = "001.jpg"
 
# new HTTPFileUploader instance
uploader = HTTPFileUploader('yourServer.xxx', port = 80) # port optional if 80
 
# set page
uploader.setPage('/uploaderFolder/file_uploader.php')
 
# Add fields in HTTP: ex file name for or past example
uploader.setField("fileName", os.path.split(filePath)[1])
 
# upload file - returns True or False.
if not uploader.uploadFile(filePath, "picture"):
    print uploader.getResult()

Server source (file_uploader.php):

<?php
# Copyright (c) 2007 LEFEVRE Damien
# file_uploader.php implementation
 
// In this example a directory "images" needs to be present on the same directory where
// image_uploader.php is, with the necessary rights for the script to write data inside
$content_dir = 'images/';
$filename = Null;
 
if(isset($_POST['fileName'])){
    $filename = $_POST['fileName'];
}
 
if(isset($_FILES['picture'])){
    if ($filename == Null){
        $filename = $_FILES['picture']['name'];
    }
    if( !move_uploaded_file($_FILES['picture']['tmp_name'], $content_dir . $filename) ){
        exit("Couldn't write the file in $content_dir");
    }
}
else{
    // something when wrong
    exit("False");
}
// return
echo "True";
?>

Friday 9 February 2007

Upload Image to URL

Many people have been asking for help. Here is a working example of an image uploader:

Python script:

# Copyright (c) 2007 LEFEVRE Damien
# image uploader: python implementation
import httplib, urllib
import base64, os.path
 
 
def imageToURL( aPath ):
    # read the binary data of the picture
    data = open(aPath, 'rb').read()
    # encoded it to base64
    encodedData = base64.encodestring( data )
    headers = { "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain",
                }
 
    params = urllib.urlencode({ u'fileName': os.path.split(aPath)[1],
                                u'data':encodedData})
 
    conn = httplib.HTTPConnection( "yourURL.xxx" )
    conn.request( "POST", "/uploaderFolder/image_uploader.php", params, headers )
    response = conn.getresponse( )
    # returns "True" or "False" if failed
    print response.read( )
    # status for debugging
    print response.status
    conn.close( )
 
 
if __name__ == "__main__":
    imageToURL("yourImage.jpg")



Now the image uploader (image_uploader.php):

<?php
// Copyright (c) 2007 LEFEVRE Damien
// image_uploader.php implementation
 
// In this example a directory "images" needs to be present on the same directory where
// image_uploader.php is, with the necessary rights for the script to write data inside
 
if(isset($_POST['fileName'])){
    $filename = $_POST['fileName'];
}
else{
    // if not: just stop here
    print "False";
    die();
}
 
if(isset($_POST['data'])){
    $encodedData = $_POST['data'];
    $data = base64_decode($encodedData);
}
else{
    // if not: just stop here
    print "False";
    die();
}
 
// full path for the image
$filepathname = 'images/'.$filename;
 
// write the file to the server into the images directory
$handle = fopen($filepathname, 'wb');
fputs($handle, $data, strlen($data));
fclose($handle);
 
// return
echo "True";
?>

1 2 >

LEFEVRE Damien
http://www.lfdm.net
contact@lfdm.net