Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 38

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 38 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 382018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 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.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее