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

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

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

Attributes When and Sort order require special treatmentsince they contain a list of values and the index of the chosen item in atuple. In this case, we replace the tuple with the chosen value.Example 91: EventFu (2/5)def save_prefs(new_prefs):db = e32dbm.open(CONF_FILE, "nf")for label, type, value in new_prefs:if label == "When" or label == "Sort_order":value = value[0][value[1]]prefs[label] = valueEVENTFU: FINDING EVENTFUL EVENTS211db[label] = value.encode("utf-8")db.close()timer.cancel()timer.after(0, update_list)return Truedef load_prefs():global prefstry:prefs = {}db = e32dbm.open(CONF_FILE, "r")for k, v in db.iteritems():prefs[k] = v.decode("utf-8")db.close()except Exception, x:prefs = {}return prefsOnce the preferences have been stored in the database, a list updateis triggered.

This is done by the timer object which is introduced withthe function update list(). The function returns True to approvethe changes made to the form.The function load prefs() performs the reverse operation: it opensthe database and copies values from it to a dictionary, prefs, that keepsthe current preferences. Strings, which are stored in the UTF-8 formatin the database, are decoded back to Unicode strings. If anything goeswrong in loading (for example, if the database does not exist), an emptyset of preferences is returned.9.3.3 Updating Events using the Eventful APIThe Eventful Web API is used to retrieve events according to the user’spreferences. Titles of the retrieved events are presented in a list, like theone that is shown in Figure 9.2(b). The list is constructed by the functionupdate list() that is presented in Example 92.Example 92: EventFu (3/5)def update_list():global alive, eventslprefs = {'app_key': APP_KEY, 'page_size': '10'}for k, v in prefs.items():if v:lprefs[k.lower()] = vlistbox.set_list([u"Updating..."])appuifw.app.title = u"Updating %s..." % prefs.get('Location', u"")try:url = SEARCH_URL + urllib.urlencode(lprefs)res = urllib.urlopen(url).read()events = json.read(res)['events']['event']titles = []212WEB SERVICESfor event in events:titles.append(unicode(event['title']))listbox.set_list(titles)appuifw.app.title = prefs['Location']except:listbox.set_list([u"Could not fetch events"])appuifw.app.title = u"EventFu"if alive:timer.after(UPDATE_INTERVAL, update_list)Fields of the preferences form map directly to parameters of thecorresponding search request.

Parameters can be given in the requestedURL, so again we can use a standard urllib.urlopen() call to accessthe service. The dictionary lprefs is filled with the parameters: app keyspecifies your personal Eventful application key and page size specifiesthe number of events returned. The other parameters are filled in bylooping over the preferences dictionary, prefs. Keys are converted tolower case and empty values are omitted.Before a call is made to Eventful, the application title is changedto notify the user about the ongoing update. Since the application issingle-threaded, that is, it performs only one operation at time, a call toEventful makes the application unresponsive for a short period. Thus, itis important that we inform the user that the application has not crashed.By making the application multi-threaded, and somewhat more complex,we could avoid the pause.The actual call to Eventful and parsing of the results are enclosed in atry–except block.

If the network is unavailable, as often happens witha mobile device, or the Eventful service returns unknown or erroneousresults, we want to inform the user properly. Since the applicationmakes the same request again after some time to receive new events, atemporary network failure is not a fatal error and the application maycontinue working without the user even noticing the glitch.The service returns the matching event list encoded in JSON, which wasfirst introduced in Section 8.3. A JSON parser translates a JSON-encodedmessage to the corresponding data structures automatically.

The structureof Eventful’s replies are fully documented at http://api.eventful.com. Herewe are only interested in the list of events that match the user’s preferences, which is assigned to the variable events. From this list, we extractthe event titles to the list titles which is then updated to the list box.To receive new events to the list automatically, some mechanism mustbe used to call the function update list() every once in a while.

Wecan employ here the same solution as in the GSM location application inSection 6.4, namely the e32.Ao timer object. After the function hasfinished with updating, we set up the timer to call the same function,update list(), again after UPDATE INTERVAL seconds unless theuser has asked the application to quit and the variable alive is set toFalse.EVENTFU: FINDING EVENTFUL EVENTS213If the user has changed some values in the preferences form, the listmust be updated immediately – we cannot expect the user to wait for,say, ten minutes to see the effect of the new settings. Because of this,the function save prefs() cancels the current timer and sets up anew one that calls update list() immediately. The benefit of usingthe timer object to trigger the update is that save prefs() may returnimmediately and it does not have to wait for update list() to finish,as would be the case with a normal function call.9.3.4 Event Form and Event DescriptionFigure 9.2(c) shows the event form which is constructed by the functionshow event() (see Example 93).

The form shows a subset, specified inEVENT FIELDS, of event attributes that are returned by Eventful. Usuallywe hard-code the structure of UI elements in our applications but, asshown by this example, we can construct the elements on the fly as wellas based on some external data. First, however, we make the attributenames more readable by converting their first characters to upper caseand their values to Unicode, as Eventful returns them in the UTF-8 format.Example 93: EventFu (4/5)def show_description():global descf = file(DESCRIPTION_FILE, "w")f.write(u"<html><body>%s</body></html>" % desc)f.close()lock = e32.Ao_lock()viewer = appuifw.Content_handler(lock.signal)viewer.open(DESCRIPTION_FILE)lock.wait()def show_event():global descif not events:returnevent = events[listbox.current()]form_elements = []for field in EVENT_FIELDS:if field in event and event[field]:key = field.capitalize()value = event[field].decode("utf-8")form_elements.append((key, "text", value))form = appuifw.Form(form_elements, appuifw.FFormViewModeOnly)if 'description' in event:desc = event['description'].decode("utf-8")form.menu = [(u"description", show_description)]form.execute()214WEB SERVICESBesides attributes that contain only a word or two, such as the eventlocation and time, Eventful returns also a free-form description of theevent, which may be arbitrarily long.

The description could hardly fit inthe event form. Instead, we use the phone’s default browser to show thedescription. The user may choose to see the description from the formmenu which calls the function show description().The function show description() works in a straightforward manner: The description, which is embedded in an HTML page, is writtento a temporary file, DESCRIPTION FILE. The appuifw.Contenthandler object is used to open the file. The content handler infers thefile type and opens an appropriate viewer.

A similar pattern was used inExample 67 that showed a downloaded image using the standard imageviewer.9.3.5 Access Point Dialog and User Interface FunctionsExample 94 presents the already familiar UI functions for EventFu. Thefunction access point(), which is triggered by the correspondingmenu item, is used to select the default network connection or accesspoint for the application. If no default access point is chosen, the periodical list update may cause the access point selection dialog to pop upagain and again.

A detailed description of the access point functions canbe found in Chapter 8.Example 94: EventFu (5/5)def access_point():ap_id = socket.select_access_point()apo = socket.access_point(ap_id)socket.set_default_access_point(apo)def quit():global alivealive = Falsetimer.cancel()app_lock.signal()events = Nonealive = Truetimer = e32.Ao_timer()appuifw.app.exit_key_handler = quitappuifw.app.title = u"EventFu"appuifw.app.menu = [(u"Preferences", show_prefs),(u"Access point", access_point),(u"Quit", quit)]appuifw.app.body = listbox = appuifw.Listbox([u""], show_event)load_prefs()update_list()app_lock = e32.Ao_lock()app_lock.wait()INSTAFLICKR: SHOOT AND UPLOAD PHOTOS TO FLICKR215When the application starts, we load preferences (load prefs())and update the event list (update list()). When you run the application for the first time, the update fails because of missing preferences.This is fixed by filling in the preferences form.Note that we need to cancel the timer object when the application isabout to exit.

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

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

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

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