Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 44
Текст из файла (страница 44)
The request contains both the applicationkey API KEY that identifies this particular application and the tokenflickr token that identifies the Flickr account which should receivethe photo.At this point, the user could assign a title or tags to the photo. In thisexample, the title is fixed to ‘InstaFlickr’. See the Flickr API documentationat www.flickr.com/services/api/upload.api.html for possible attributesthat can be attached to the photo.The function progress bar is called whenever a block of data hasbeen sent. The parameter p is a floating-point value between 0 and 1.0that denotes the progress. Based on this value, we draw a rectangle inthe middle of canvas that grows from left to right as the data is sent.
Theeffect can be seen in Figure 9.3(c).224WEB SERVICESThe function show text() is used to draw status messages in themiddle of canvas. The function should be rather self-explanatory.9.4.6 User Interface FunctionsExample 100 explains the remaining functions related to the user interface. The function access point() is familiar from the previousapplication, EventFu. It is described with Example 94.Example 100: InstaFlickr (6/6)def access_point():ap_id = socket.select_access_point()apo = socket.access_point(ap_id)socket.set_default_access_point(apo)def quit():camera.stop_finder()app_lock.signal()appuifw.app.exit_key_handler = quitappuifw.app.title = u"InstaFlickr"appuifw.app.menu = [(u"Take photo", start_viewfinder),(u"New token", new_token),(u"Access point", access_point),(u"Quit", quit)]appuifw.app.body = canvas = appuifw.Canvas()canvas.clear((255, 255, 255))show_text(u"Welcome to InstaFlickr")load_token()app_lock = e32.Ao_lock()app_lock.wait()Note that the Flickr token is loaded with the function load token()when the application starts.
If no token has been defined previously, thefunction shows a ‘New token’ dialog.You may find inspiration for your own extensions in the Flickr mobiletools page at www.flickr.com/tools/mobile. For example, InstaFlickrcould be combined with the GSM location example (Example 50) so thatthe photos could be tagged with the current location – see Zonetag athttp://zonetag.research.yahoo.com for a reference.9.5 SummaryIn this chapter, we have presented three working applications, MopyMaps!, EventFu and InstaFlickr, which are based on three different webservices.
These applications delegate most of the difficult work to anSUMMARY225external service, which results in remarkably light processing on theclient side. For example, consider MopyMaps!, which implements aworking global map client in around 100 lines of code! With modernweb services and a bit of imagination you can build amazingly functionalapplications with unbelievably few lines of code.10Effective Python for S60In the previous chapters we have deliberately avoided some advancedprogramming techniques to focus on the functionalities of the mobileplatform.
Many of the examples could be made shorter and more elegantwith techniques that are in this chapter.Section 10.1 presents some powerful constructs of the Python languagethat we omitted in the earlier chapters. In Section 10.2, we describe howyou can avoid clumsy static constructs by deciding what to do withrun-time introspection.Techniques presented in Section 10.3 really put the word rapid intorapid development. These methods, related to modularization, extensibility and updating of PyS60 programs, have proven to be immenselyuseful not only during the development process, but also for deploymentand maintenance.Section 10.4 shows another viewpoint of the examples in this book. Wesummarize notable recurring patterns in the structure of PyS60 programs,which help you to generalize the examples of this book to practically anyreal-world setting.
Finally, in Section 10.5, we present seven crystallizedthoughts about PyS60 programming.All in all, be prepared for a serious productivity boost!10.1 Powerful Language ConstructsPython is a very expressive programming language. You can performcomplex operations with just a few lines of code. In many cases, compactexpressions translate to easy readability and efficient processing, thusthese forms are often preferred over lengthier ones.
Luckily, Pythoninvites you to write clean and simple code once you know the nuancesof the language. As a matter of fact, the following language constructs arethe bread and butter of elegant Python.228EFFECTIVE PYTHON FOR S6010.1.1 List ComprehensionsAs seen in the previous chapters, many tasks boil down to variousoperations on lists. Python provides a compact syntax for constructingnew lists, called list comprehensions. Using list comprehensions you canconstruct a new list either from scratch or based on a previous sequenceof objects.Using a simple loop, you can construct a list of ten user names asfollowsa = []for x in range(10):a.append("user%d" % x)However, you can get the same result with a list comprehension usingonly one line of code (as shown in Example 101).Example 101: List comprehensiona = ["user%d" % x for x in range(10)]Not only is this expression shorter, but it is also more efficient since wedon’t have to call the append() function ten times.
List comprehensionshave the following syntax:[<list item expression> for <iterator variable> in <list expression>(if <conditional>)]In Example 101, the list item expression is "user%d"% x, the iteratorvariable is x and the list expression is range(10). This example did nothave any conditional element. No other elements are allowed in the listcomprehension.
The list item expression can be arbitrarily complex but itcannot contain statements such as print, while or return. However,it can contain another list comprehension, so you can create nested ormulti-dimensional lists.Recall the SMS search tool, Example 15, from Chapter 4. The examplewas similar to the following code:import inbox, appuifwbox = inbox.Inbox()query = appuifw.query(u"Type in the query", "text")hits = []for sms_id in box.sms_messages():msg = box.content(sms_id)if msg.find(query) != -1:hits.append(sms_id)POWERFUL LANGUAGE CONSTRUCTS229We can condense the example and make it more understandable usinglist comprehensions.Example 102: SMS search using list comprehensionsimport inbox, appuifwbox = inbox.Inbox()query = appuifw.query(u"Type in the query", "text")hits = [sms_id for sms_id in box.sms_messages()\if box.content(sms_id).find(query) != -1]The above list comprehension becomes clear when you read it asfollows: pick sms id for each item of the list returned by box.smsmessages() where the return value of the function box.content()contains the string query.This sentence captures the idea of the search tool much more comprehensively than a corresponding explanation for the original five-lineversion of the code.You can solve many practical tasks using list comprehensions.
Forexample, if you need to perform any operation for each element of alist and save the return values, you can use an expression such as thefollowing:results = [f(x) for x in my_list]Python includes a built-in function called map() that produces thesame result as the previous list comprehension as follows:results = map(f, my_list)Here, f is a callback function that is called for each item in the listmy list. For example, the following two lines produce an equivalentresult: they convert a list of integers between 0 and 9 to a list of Unicodestrings:results = [unicode(x) for x in range(10)]results = map(unicode, range(10))Note that you do not have to use a list comprehension to construct alist whose elements are all equal.
For example, you can initialize a list ofN zero values simply as follows:N = 10zeros = [0] * N230EFFECTIVE PYTHON FOR S60You can choose all elements that satisfy a condition as followsresults = [x for x in my_list if x > 0]Here you can replace x > 0 with any valid if condition. For example,you can filter out all illegal characters in a string (Example 103).Example 103: Input sanitization using list comprehensionsinput = " this is, a TEST input!"allowed = "abcdefghijklmnopqrstuvwxyz"print "".join([c for c in input if c in allowed])The output is thisisainput.
The trick here is that the loop cancontain any iterable object, in this case a string, that loops over allcharacters in it when treated as a sequence.10.1.2 Dictionary ConstructorBesides lists, another data type that can be found in almost every Pythonprogram is a dictionary. The most typical use for the dictionary is to geta value, given the corresponding key, in an efficient manner. However,sometimes you can just use the fact that the dictionary cannot containduplicate keys.For example, you can count the number of distinct items in a list asfollows:a = [1, 2, "a", 1, "b", 2, "b"]d = {}for x in a:d[x] = Trueprint len(d)The output is 4 in this case. As with the lists above, it may feelunnecessarily verbose to use four lines of code to say ‘Construct adictionary d whose keys are the items of a ’.Luckily, the built-in dict() function saves us.
The function takes alist of key–value pairs as tuples and returns a new dictionary based onthe list. We can re-write the previous example as Example 104.Example 104: Dictionary constructora = [1, 2, "a", 1, "b", 2, "b"]print len(dict([(x, True) for x in a]))INTROSPECTION231Here, we use a list comprehension to build a list of tuples based on theoriginal list a. The new list is given to the dictionary constructor dict(),which returns a new dictionary whose size is then printed out.In some cases you would like to retrieve a key given a value – theopposite operation of the normal dictionary usage. Since there may bemultiple keys that have an equal value, you need to return a list of keysgiven a single value:keys = [k for k, v in d.items() if v == x]Here d is the dictionary and x is the value of interest.
On the otherhand, if only one key per value is enough and you need to perform theoperation for multiple values, it makes sense to make a new dictionaryby reversing the roles of the keys and values.reverse_d = dict([(v, k) for k, v in d.items()])key = reverse_d[x]10.2 IntrospectionOne of the great strengths of a dynamic programming language, such asPython, is that it is possible to examine and even manipulate the programcode at run-time. The idea of introspective programs may sound esotericand mind-bending, but on examination it provides a clean way to solvesome rather mundane tasks.The core idea is simple: given that your program includes a functionor an object named xyzzy, you can use the string "xyzzy" to accessthat object, rather than specifying the name in your source code.