Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 38
Текст из файла (страница 38)
The resulting code is surprisingly simple. It canbe made even simpler using Python’s introspection features, as we willshow in Section 10.2.Note that when testing this example, you may need to request a URLon the phone, for example, http://192.168.0.2:9000/camera.jpg, severaltimes before you see the actual result on the browser. The server exitswhen the ‘exit’ resource is requested.This example makes a great showcase of Python’s power and expressiveness: in fewer than 120 lines of code, we have implemented a workingSUMMARY197web server and a proxy, and turned a mobile phone into a web servicewhich features a webcam, a screen capturer and a battery-level indicator!8.8 SummaryThis chapter covered the basics of modern networking in a nutshell.After reading this chapter, you should be prepared to build innovativemobile-device-centric, networked programs and services.This chapter contains a lot of information and you may feel it hard todigest everything at once.
The best approach is to start experimenting,exploring and tinkering around with your own ideas. If you need moreinformation about any subject in this chapter, the web is your friend.The chapter started with examples of TCP, HTTP and JSON clientswhich requested information from the outside world for the mobile phone.The latter part of the chapter focused on using the phone as a server.Techniques of polling, persistent TCP connections, gateways and webproxies were introduced to aid server development on the phone side.This chapter presents several working example applications: a camerawhich saves photos to a server, a voting server with mobile and webinterfaces, a JSON gateway for peer-to-peer communication, an instantmessenger and a web service which lets you control your phone from aweb browser.
These examples may be useful after some polishing or youmay use them as the basis for your own applications.9Web ServicesIn Chapter 8, we showed how you can use PyS60 to build network clientsand servers of your own. In this chapter, we show how to tap into servicesprovided by others. These two approaches are becoming more and morecomplementary. Often the most interesting results emerge when youcombine something of your own, such as your current location, withsome external information, such as Google Maps.Information available in ordinary websites is primarily prepared forhuman consumption. Data is embedded in elaborate visual layouts thatlook pleasing to the eye but from which it is difficult to extract the dataprogrammatically.
Technically, it would be possible to retrieve any webpage using, for example, the urllib.urlopen() function but parsingthe desired data from the midst of complex HTML code is a tedious anderror-prone task. Luckily, some Python libraries, such as Beautiful Soup,exist to make this task easier.However, many websites and web application providers have understood that they can increase the value of their product by making it easilyaccessible to other programs, as well as human users. Increasingly often,they are starting to provide another view to their service that can be usedto retrieve the pure data easily without any decoration. This interface isoften called a web service or a web Application Programming Interface(web API ).For example, Amazon, Google, Yahoo!, Flickr, Facebook and most ofthe blog engines provide a web API through which their service, or someparts of it, can be used programmatically.
Typically, the web API is madefreely available for non-commercial use only. You should always readthe terms of use carefully before using any web API in your program.Note that practically all services require that you apply for an application key to use the service.
The key is used by the service to identify theorigin of third-party requests and to control the number of requests made200WEB SERVICESby an external application. Typically, you receive the key immediatelywhen you register a web API account.9.1 Basic PrinciplesYou can think of a web service as an ordinary Python module whosefunctions are just called in a particular way using urllib. As with ordinary modules, you have to see the API documentation to understand howto use the related functions. However, whereas the API of an ordinaryPython module stays constant, even in different versions of Python, a webservice provider may change the web API any time without prior notice.Because of this, we focus mostly on the basic principles of the Webservice usage here, instead of explaining the current web APIs in detail.To use a web service, you typically have to go through the followingsteps:1.Go to the service provider’s website and find the web API or developer documentation.
Some well-known web APIs can be found atfollowing addresses:• Amazon: http://aws.amazon.com•Flickr: www.flickr.com/services/api•Google: http://code.google.com/apis•Yahoo!: http://developer.yahoo.com/python2.Find documentation for the functionality you need.3.Find out which protocol the service uses on top of HTTP. Many services support several different protocols. The most typical alternativesare JSON, XML or plain HTTP. Some services even provide a custommodule for Python that hides requests to the web service behind normal Python function calls.
However, some of these modules use newfeatures of Python which are not yet supported by Python for S60.4.Find out what kind of input data and parameters the service expectsand how the output looks.5.Add a function to your program that prepares data for the service andhandles the output.6.Add calls to the web service with the urllib.urlopen() function.7.See how it works!Web services are built on top of the techniques that were presentedin Chapter 8. They are accessed over HTTP and responses are typicallyencoded either in JSON or XML. Example 71 in Chapter 8 demonstratedthis approach.MOPYMAPS! MOBILE YAHOO! MAPS201Some services follow REST principles. These services let you accessthe data through simple URL addresses, not unlike ordinary web pages.In Chapter 8, we built a RESTful web service of our own in Example 86.It made some resources of your mobile phone accessible to the networkthrough simple URLs, such as http://192.168.0.2/battery/.
REST is probably the simplest request format to use since it requires only familiarurllib.urlopen() calls.This chapter presents three fully working and useful applications thatare based on three different web services. Each of the examples makessimple requests to the service and gets the response either in XML orJSON. Since many modern web services support an API like this, you caneasily apply the following ideas to your own projects.Note that the web APIs are subject to frequent changes.
It may happenthat the APIs used by the following examples have been changed sincethe publication of this book. In this case, you should be able to findout the new syntax in the service’s API documentation and modify theexample accordingly.9.2 MopyMaps! Mobile Yahoo! MapsMopyMaps! is a mobile map explorer.
It uses the Yahoo! Maps Web APIto receive map images given a desired location. MopyMaps! supportsvertical and horizontal panning of received map images, so you canexplore your surroundings smoothly on the small screen of a mobilephone. MopyMaps! squeezes a full world atlas into a pocket – all infewer than 100 lines of Python!The Map Image API provided by Yahoo! Maps is extremely simple to use. You can give a partial address of a desired location infree-form text and the system infers the most suitable map image foryou. You can specify the desired map size, zoom level and radius forthe image. Full documentation for the Map Image API is available athttp://developer.yahoo.com/maps.Instead of the address, you can specify the longitude and latitudeof the desired location.
If you have a GPS receiver, you can combineMopyMaps! with the GPS reader program that was presented earlier toreceive a map of your current surroundings automatically.You need to get an Application ID from Yahoo! to use the service. Go tohttp://developer.yahoo.com and choose the link ‘Get an Application ID’.Once you have filled in the developer registration form, you are given along data string that is your Application ID. Save this string for future use.The MopyMaps! source code is divided into three parts that should becombined into one file to form the full application.