Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 42
Текст из файла (страница 42)
A timer that is left active after the application has quit causesthe PyS60 interpreter to crash eventually. By setting alive = False, wemake sure that the timer is not activated again by the update list()function after it has been cancelled.The current version of Eventfu uses only one function in the EventfulWeb API. Given that the API contains over 100 functions in total, itshould not be hard to find ways to extend the application. Consider alsocombining EventFu with the next application, InstaFlickr.
For example,with this combination you could automatically tag any photos taken, say,in a pony exhibition with appropriate attributes fetched from Eventfulbefore sending them to Flickr!9.4 InstaFlickr: Shoot and Upload Photos to FlickrWith InstaFlickr, it takes only about 10 seconds to shoot a photo andupload it to your Flickr account (the actual time depends on your networkconnection). No need to configure or type anything – just point, shootand upload! This application is made possible by the Flickr Web API(www.flickr.com/services/api) which allows you to upload photos toyour account programmatically.There are two tricky issues in the implementation of this application.First, as the photos are uploaded to a personal Flickr account, we mustgo through Flickr’s four-step authentication process.
Second, since thisapplication sends a lot of data, in contrast to MopyMaps! and EventFu,(a)Figure 9.3(b)(c)InstaFlickr (a) menu, (b) viewfinder and (c) upload progress bar216WEB SERVICESwhich mostly receive it, we have to use a special method for making therequests. Luckily, we can solve these tasks using techniques that havebeen introduced already.The InstaFlickr source code is divided into six parts. As before, theparts should be combined into one file to form the full application. Theparts cover the following functionalities:•constants and result parsing•handling Flickr tokens•making signed calls to Flickr•data uploading•taking photos and implementing a progress bar•user interface functions.You need to apply for a Flickr API key to use the application. Youcan get one at www.flickr.com/services/api/keys/apply.
Apart fromthe uploading functionality, the application is similar to the previousexamples that use the camera, such as Example 36. The user maystart the viewfinder from a menu item (start viewfinder()) andtake a photo with the select key (take photo()). The photo is thensent automatically (flickr signed call()) to a previously defined(new token()) Flickr account.9.4.1 Constants and Result ParsingExample 95 defines the constants and the naive xml parser() function that was first introduced in MopyMaps! Example 87. In a similar wayto the Yahoo! Map API, functions in the Flickr API return a small XMLmessage that can be parsed using this simple approach.Example 95: InstaFlickr (1/6)import e32, md5, urllib, httplib, camera, key_codes, os, os.pathAPI_KEY = "c62dcNiOgTeVhAaLdIxDsdf17ee3afe9"SECRET = "c932fFxAkK9E648d"API_URL = "http://flickr.com/services/rest/"UPLOAD_URL = "http://api.flickr.com/services/upload/"IMG_FILE = u"E:\\Data\\Instaflickr\\instaflickr.jpg"TOKEN_FILE = u"E:\\Data\\Instaflickr\\instaflickr.txt"BLOCKSIZE = 8192PROGRESS_COLOR = (0, 255, 0)TEXT_COLOR = (255, 0, 0)INSTAFLICKR: SHOOT AND UPLOAD PHOTOS TO FLICKR217if not os.path.exists("E:\\Data\\Instaflickr"):os.makedirs("E:\\Data\\Instaflickr")def naive_xml_parser(key, xml):key = key.lower()for tag in xml.split("<"):tokens = tag.split()if tokens and tokens[0].lower().startswith(key):return tag.split(">")[1].strip()return NoneThe Flickr API key consists of two parts: the public application key andits secret counterpart.
Once you have applied for your personal key, youcan see it and the corresponding secret key at www.flickr.com/services/api/keys. Replace API KEY in the code with your personal key andSECRET with the secret key that corresponds to it. The constants API URLand UPLOAD URL contain the base address of Flickr API functions andthe photo upload function, correspondingly.TOKEN FILE specifies a file which is used to save a token thatgives access to a chosen Flickr account. Given this token, API KEYand SECRET, it is possible to modify the Flickr account of the personthat approved the token originally.
Thus, you should keep these stringsprivate. IMG FILE is used to save the image in a file temporarily.BLOCK SIZE specifies how many bytes of image data is sent ata time to Flickr. The progress bar is updated after each block hasbeen sent. However, there should be no need to change this value.PROGRESS COLOR defines the color of the progress bar in RGB andTEXT COLOR defines the color of the text, unsurprisingly.9.4.2 Handling Flickr TokensTo upload photos to a Flickr account, we need permission from theaccount holder. However, the account holder should not trust her username and password to our application – or to any third-party applicationwhatsoever. Instead, she can request a token from Flickr that is specifically assigned to a certain application and which she can reject at anytime.This is how the token is generated.
The developer must perform thefollowing steps:1. Request an application key from Flickr (if you have not done thatalready).2. Go to the ‘Your API keys’ page at www.flickr.com/services/api/keys.3. Choose ‘Edit key details’.4. For ‘Authentication Type’ choose ‘Mobile Application’.218WEB SERVICES5.For ‘Mobile permissions’ choose ‘Write’.6.Write down the newly generated ‘Your authentication URL’.Now, the person to whose account the photos are to be uploaded mustperform the following steps:1.Go to the authentication URL that was shown in Step 6, above.2.Log in to your account and select the button ‘Ok, I’ll allow it’ whenyou are asked about an application wanting to link to your account.3.Write down the nine-digit code that is shown.4.Open InstaFlickr.5.Choose ‘New Token’ menu item.6.Type in the nine-digit code.If the token is accepted, InstaFlickr says ‘Token saved!’.
If InstaFlickrcould not save the token, you should double-check that API KEY,SECRET and the nine-digit code have been typed in correctly. Note thatthe nine-digit code can be used only once. If you request a new code,the previous code becomes invalid.
If you want to change the accountto which the photos are uploaded, the owner of the new account mustrequest a new nine-digit code from the authentication URL and input itto the ‘New Token’ dialog in InstaFlickr.You can find detailed instructions about the authentication process atthe Flickr services website. At time of printing, the how-to for mobileapplications can be found at www.flickr.com/services/api/auth.howto.mobile.html.Example 96 shows how the tokens are handled internally.
The function new token() is called when the user chooses the menu item‘New Token’. The token given by the user is assigned to the variablemini token. Since there is no guarantee that this is actually the application for which the nine-digit code was granted by the user, we mustcertify our identity to Flickr with the nine-digit code.Example 96: InstaFlickr (2/6)def load_token():global flickr_tokentry:flickr_token = file(TOKEN_FILE).read()except:new_token()def new_token():global flickr_tokenINSTAFLICKR: SHOOT AND UPLOAD PHOTOS TO FLICKR219mini_token = appuifw.query(u"Give Flickr mini-token " +"(e.g. 123456100)", "number")if not mini_token:returnparams = {"method": "flickr.auth.getFullToken","api_key": API_KEY,"mini_token": str(mini_token)}flickr_token = naive_xml_parser("token", flickr_signed_call(params))if flickr_token:try:f = file(TOKEN_FILE, "w")f.write(flickr_token)f.close()appuifw.note(u"Token saved!", "info")except:appuifw.note(u"Could not save token", "error")else:appuifw.note(u"Invalid token", "error")This is done by sending a request to a Flickr API function calledflickr.auth.getFullToken().