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

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

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

A timer that is left active after the application has quit causesthe PyS60 interpreter to crash eventually. By setting alive = False, wemake sure that the timer is not activated again by the update list()function after it has been cancelled.The current version of Eventfu uses only one function in the EventfulWeb API. Given that the API contains over 100 functions in total, itshould not be hard to find ways to extend the application. Consider alsocombining EventFu with the next application, InstaFlickr.

For example,with this combination you could automatically tag any photos taken, say,in a pony exhibition with appropriate attributes fetched from Eventfulbefore sending them to Flickr!9.4 InstaFlickr: Shoot and Upload Photos to FlickrWith InstaFlickr, it takes only about 10 seconds to shoot a photo andupload it to your Flickr account (the actual time depends on your networkconnection). No need to configure or type anything – just point, shootand upload! This application is made possible by the Flickr Web API(www.flickr.com/services/api) which allows you to upload photos toyour account programmatically.There are two tricky issues in the implementation of this application.First, as the photos are uploaded to a personal Flickr account, we mustgo through Flickr’s four-step authentication process.

Second, since thisapplication sends a lot of data, in contrast to MopyMaps! and EventFu,(a)Figure 9.3(b)(c)InstaFlickr (a) menu, (b) viewfinder and (c) upload progress bar216WEB SERVICESwhich mostly receive it, we have to use a special method for making therequests. Luckily, we can solve these tasks using techniques that havebeen introduced already.The InstaFlickr source code is divided into six parts. As before, theparts should be combined into one file to form the full application. Theparts cover the following functionalities:•constants and result parsing•handling Flickr tokens•making signed calls to Flickr•data uploading•taking photos and implementing a progress bar•user interface functions.You need to apply for a Flickr API key to use the application. Youcan get one at www.flickr.com/services/api/keys/apply.

Apart fromthe uploading functionality, the application is similar to the previousexamples that use the camera, such as Example 36. The user maystart the viewfinder from a menu item (start viewfinder()) andtake a photo with the select key (take photo()). The photo is thensent automatically (flickr signed call()) to a previously defined(new token()) Flickr account.9.4.1 Constants and Result ParsingExample 95 defines the constants and the naive xml parser() function that was first introduced in MopyMaps! Example 87. In a similar wayto the Yahoo! Map API, functions in the Flickr API return a small XMLmessage that can be parsed using this simple approach.Example 95: InstaFlickr (1/6)import e32, md5, urllib, httplib, camera, key_codes, os, os.pathAPI_KEY = "c62dcNiOgTeVhAaLdIxDsdf17ee3afe9"SECRET = "c932fFxAkK9E648d"API_URL = "http://flickr.com/services/rest/"UPLOAD_URL = "http://api.flickr.com/services/upload/"IMG_FILE = u"E:\\Data\\Instaflickr\\instaflickr.jpg"TOKEN_FILE = u"E:\\Data\\Instaflickr\\instaflickr.txt"BLOCKSIZE = 8192PROGRESS_COLOR = (0, 255, 0)TEXT_COLOR = (255, 0, 0)INSTAFLICKR: SHOOT AND UPLOAD PHOTOS TO FLICKR217if not os.path.exists("E:\\Data\\Instaflickr"):os.makedirs("E:\\Data\\Instaflickr")def naive_xml_parser(key, xml):key = key.lower()for tag in xml.split("<"):tokens = tag.split()if tokens and tokens[0].lower().startswith(key):return tag.split(">")[1].strip()return NoneThe Flickr API key consists of two parts: the public application key andits secret counterpart.

Once you have applied for your personal key, youcan see it and the corresponding secret key at www.flickr.com/services/api/keys. Replace API KEY in the code with your personal key andSECRET with the secret key that corresponds to it. The constants API URLand UPLOAD URL contain the base address of Flickr API functions andthe photo upload function, correspondingly.TOKEN FILE specifies a file which is used to save a token thatgives access to a chosen Flickr account. Given this token, API KEYand SECRET, it is possible to modify the Flickr account of the personthat approved the token originally.

Thus, you should keep these stringsprivate. IMG FILE is used to save the image in a file temporarily.BLOCK SIZE specifies how many bytes of image data is sent ata time to Flickr. The progress bar is updated after each block hasbeen sent. However, there should be no need to change this value.PROGRESS COLOR defines the color of the progress bar in RGB andTEXT COLOR defines the color of the text, unsurprisingly.9.4.2 Handling Flickr TokensTo upload photos to a Flickr account, we need permission from theaccount holder. However, the account holder should not trust her username and password to our application – or to any third-party applicationwhatsoever. Instead, she can request a token from Flickr that is specifically assigned to a certain application and which she can reject at anytime.This is how the token is generated.

The developer must perform thefollowing steps:1. Request an application key from Flickr (if you have not done thatalready).2. Go to the ‘Your API keys’ page at www.flickr.com/services/api/keys.3. Choose ‘Edit key details’.4. For ‘Authentication Type’ choose ‘Mobile Application’.218WEB SERVICES5.For ‘Mobile permissions’ choose ‘Write’.6.Write down the newly generated ‘Your authentication URL’.Now, the person to whose account the photos are to be uploaded mustperform the following steps:1.Go to the authentication URL that was shown in Step 6, above.2.Log in to your account and select the button ‘Ok, I’ll allow it’ whenyou are asked about an application wanting to link to your account.3.Write down the nine-digit code that is shown.4.Open InstaFlickr.5.Choose ‘New Token’ menu item.6.Type in the nine-digit code.If the token is accepted, InstaFlickr says ‘Token saved!’.

If InstaFlickrcould not save the token, you should double-check that API KEY,SECRET and the nine-digit code have been typed in correctly. Note thatthe nine-digit code can be used only once. If you request a new code,the previous code becomes invalid.

If you want to change the accountto which the photos are uploaded, the owner of the new account mustrequest a new nine-digit code from the authentication URL and input itto the ‘New Token’ dialog in InstaFlickr.You can find detailed instructions about the authentication process atthe Flickr services website. At time of printing, the how-to for mobileapplications can be found at www.flickr.com/services/api/auth.howto.mobile.html.Example 96 shows how the tokens are handled internally.

The function new token() is called when the user chooses the menu item‘New Token’. The token given by the user is assigned to the variablemini token. Since there is no guarantee that this is actually the application for which the nine-digit code was granted by the user, we mustcertify our identity to Flickr with the nine-digit code.Example 96: InstaFlickr (2/6)def load_token():global flickr_tokentry:flickr_token = file(TOKEN_FILE).read()except:new_token()def new_token():global flickr_tokenINSTAFLICKR: SHOOT AND UPLOAD PHOTOS TO FLICKR219mini_token = appuifw.query(u"Give Flickr mini-token " +"(e.g. 123456100)", "number")if not mini_token:returnparams = {"method": "flickr.auth.getFullToken","api_key": API_KEY,"mini_token": str(mini_token)}flickr_token = naive_xml_parser("token", flickr_signed_call(params))if flickr_token:try:f = file(TOKEN_FILE, "w")f.write(flickr_token)f.close()appuifw.note(u"Token saved!", "info")except:appuifw.note(u"Could not save token", "error")else:appuifw.note(u"Invalid token", "error")This is done by sending a request to a Flickr API function calledflickr.auth.getFullToken().

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

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

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

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