Главная » Просмотр файлов » 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), страница 40

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

Текст из файла (страница 40)

If theresult is not pleasing to your eye, you can ensure that the boundariesare not exceeded by adding a few additional if statements in thehandle keys() function.The function handle redraw() takes care of drawing the map andthe status message – if the corresponding variables are not empty. It’s agood habit to handle all drawing in a centralized manner in the redrawcallback. This makes sure that the screen is redrawn correctly after,say, a screensaver or an external dialog has been drawn on top of ourapplication.

The status message is updated by way of the show text()function, which is just a shorthand for the required three lines of code.MopyMaps! could be extended easily. As mentioned above, the mapcould be retrieved based on the current GPS coordinates instead ofEVENTFU: FINDING EVENTFUL EVENTS207an address. The map could be zoomable or alternatively the user couldspecify how many miles the map should cover (see the radius parameterin the API).You can combine maps with some other information source. Forexample, Yahoo! provides a traffic API for some parts of the world whichshows real-time traffic information that can be plotted on the map.

It alsoprovides a search API that lists establishments in proximity to a givenlocation – maybe you can come up with a trendy mashup that combinesthe maps with the event information that is used in Section 9.3.9.3 EventFu: Finding Eventful EventsHave you ever been in a foreign city without anything to do? Have youever seen an advertisement about a concert but forgotten where it willhappen and when? EventFu is here to help: it connects to the Eventfulservice at http://eventful.com/ to retrieve information and keeps youupdated about events that are interesting to you.Eventful is an event database with an extensive web API which can befound at http://api.eventful.com.

EventFu uses only one of the providedfunctions, event search, and shows a list of events that match the user’spreferences. The list is updated at regular intervals so new events appearon the list after a short delay once they have been listed in the service.Requests are made to the Eventful API using a simple URL-encodedinterface similarly to the previous example.

However, Eventful supportsresponses in JSON, so the results can be converted directly to a convenientdata structure. To use the service, you have to request an applicationkey from Eventful at http://api.eventful.com/keys/new. The key is a longrandom string not unlike the Yahoo! Application ID.Note that the json module is needed in the example. It is not includedin the standard PyS60 distribution; see Section 8.2.2 for how to installthis module.EventFu contains several features that are worth noticing:•It presents a straightforward mapping between the UI and the webAPI – for example, the event description form is constructed on the flybased on the Eventful response fields.•It shows how to update data from an external source continuously atregular intervals.•It gives a practical example of how to save user preferences to a localdatabase and how to use the phone’s default browser to show HTMLpages.•It lets the user select the default access point for networking – acrucial feature when the application must use the network withoutuser intervention.208WEB SERVICESThe EventFu source code is divided into five parts.

Again, the partsshould be combined into one file to form the full application. The partscover the following functionalities:•constants and preferences form•storing preferences•event form and event description•updating events using the Eventful API•access point dialog and user interface functions.EventFu uses the standard UI extensively. The main view is based onan appuifw.ListBox object and preferences and event descriptionsare shown using an appuifw.Form object (Figure 9.2). The core function is update list(), which, not surprisingly, updates the eventlist. The list is retrieved according to the user’s preferences whichare handled by the show preferences(), save preferences()and load preferences() functions.

If the user selects an event(a)(b)(a)(b)Figure 9.2 EventFu (a) menu, (b) event list, (c) event form and (d) preferences dialogEVENTFU: FINDING EVENTFUL EVENTS209in the list, an event description form is opened (show event()).In this form, the user may choose to see the full event description(show description()) that is returned in HTML format from Eventful.9.3.1Constants and Preferences FormExample 90 presents the first part of EventFu. First, you should replace theapplication key constant APP KEY with the personal key you receivedfrom Eventful. The search requests are made to the address specifiedin SEARCH URL. The next three constants are related to configuration:CONF FILE gives a file name for the local database that keeps theuser’s preferences, DESCRIPTION FILE specifies a file in which eventdescription text is saved temporarily for showing; UPDATE INTERVALspecifies the interval in seconds between event list updates.

Note that ashort interval may incur higher bandwidth usage and cost, depending onyour data plan and it drains the battery faster.Constant lists WHEN and ORDER correspond to parameters when andsort order which are part of the service request. The lists contain allpossible values for the parameters. The user may choose values in thepreferences form that presents these lists in combo fields, as we see soon.Example 90: EventFu (1/5)import appuifw, e32, urllib, socket, e32dbm, json, os.path, osAPP_KEY = "5IsN4V9AdLwI3Dde"SEARCH_URL = "http://api.evdb.com/json/events/search?"CONF_FILE = u"E:\\Data\\Eventfu\\eventfu.cfg"DESCRIPTION_FILE = u"E:\\Data\\Eventfu\\eventfu.html"UPDATE_INTERVAL = 600if not os.path.exists("E:\\Data\\Eventfu"):os.makedirs("E:\\Data\\Eventfu")WHEN = [u"All", u"Future", u"Past", u"Today",u"Last week", u"This Week", u"Next Week"]ORDER = [u"relevance", u"date", u"title",u"venue_name", u"distance"]EVENT_FIELDS = [u"title", u"start_time", u"venue_name",u"venue_address"]def show_prefs():if appuifw.app.title.find("Updating") != -1:returnform = appuifw.Form([(u"Location", "text", prefs.get("Location", u"")),(u"Keywords", "text", prefs.get("Keywords", u"")),(u"When", "combo", (WHEN, 3)),(u"Sort_order", "combo", (ORDER, 0))],appuifw.FFormEditModeOnly)form.menu = []210WEB SERVICESform.save_hook = save_prefsform.execute()EVENT FIELDS lists the event attributes that are included in the eventform.

The list is a subset of all possible attributes that the Eventful servicerecords for an event. The full list, available at http://api.eventful.com/docs/events/search, contains over 20 attributes, so showing all of them tothe user would be rather impractical. You may change the list to containthe attributes that are most interesting to you.Figure 9.2(d) shows the preferences form which is constructed by thefunction show prefs. In this form, the user can specify the city or otherlocation where the returned events should take place.

To restrict thelisting further, she may give a keyword that describes the event. She mayalso specify when the event should take place, the choices being listed inthe list WHEN. The matching events are ordered according to one of theattributes in ORDER which is specified in the last field.First, the function show prefs() makes sure that a previous searchrequest is not in progress, as we do not want the requests to queue up.After this, an editable form is constructed. When the user closes theform or saves it explicitly with the Save option in the menu, the functionsave prefs() is called, as specified in the form.save hook variable.Finally, form.execute() makes the form visible.9.3.2 Storing PreferencesChoices in the preference form are saved in a local database, so the userdoes not have to type them in every time she starts the application.

Localdatabases were first introduced in Section 6.3. They look and behave likean ordinary dictionary. However, in contrast to dictionaries, which aredestroyed when the application closes, local databases are backed up toa file.Example 91 shows the function save prefs() that saves the currentpreferences. The function is given a dictionary new prefs that containsthe values from the preferences form. A new database is opened in fileCONF FILE.

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

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

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

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