forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfbook014.html
More file actions
664 lines (642 loc) · 27.4 KB
/
cfbook014.html
File metadata and controls
664 lines (642 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="GENERATOR" content="hevea 1.07" />
<title>
Using Web Services
</title>
</head>
<body>
<a href="cfbook013.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="cfbook015.html"><img src="next_motif.gif" alt="Next" /></a>
<hr />
<h1><font color="black"><a name="htoc157">Chapter 13</a> Using Web Services</font></h1>
<font color="black">Once it became easy to retrieve documents and parse documents
over HTTP using programs, it did not take long to develop
an approach where we started producing documents that were specifically
designed to be consumed by other
programs (i.e. not HTML to be displayed in a browser).<br />
<br />
There are two common formats that we use when exchanging data across the web.
The "eXtensible Markup Language" or XML has been in use for a very long time
and is best suited for exchanging document-style data. When programs just want
to exchange dictionaries, lists, or other internal information with each other,
they use JavaScript Object Notation or JSON (see <tt>www.json.org</tt>).
We will look at both formats.</font><br />
<br />
<a name="toc144"></a>
<h2><font color="black"><a name="htoc158">13.1</a> eXtensible Markup Language - XML</font></h2>
<font color="black">XML looks very similar to HTML, but XML is more structured
than HTML. Here is a sample of an XML document:
</font><pre><font size="4" color="blue">
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>
</font></pre><font color="black">Often it is helpful to think of an XML document as a tree structure
where there is a top tag <tt>person</tt> and other tags such as <tt>phone</tt>
are drawn as <em>children</em> of their parent nodes.<br />
</font><div align="center"><font color="black"><img src="cfbook014.png" /></font></div>
<br />
<a name="toc145"></a>
<h2><font color="black"><a name="htoc159">13.2</a> Parsing XML</font></h2>
<a name="@default768"></a>
<a name="@default769"></a>
<a name="@default770"></a><font color="black">
Here is a simple application that parses some XML
and extracts some data elements from the XML:
</font><pre><font size="4" color="blue">
import xml.etree.ElementTree as ET
data = "'
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>"'
tree = ET.fromstring(data)
print 'Name:',tree.find('name').text
print 'Attr:',tree.find('email').get('hide')
</font></pre><font color="black">Calling <tt>fromstring</tt> converts the string representation
of the XML into a 'tree' of XML nodes. When the
XML is in a tree, we have a series of methods which we can call to
extract portions of data from the XML. <br />
<br />
The <tt>find</tt> function searches through the
XML tree and retrieves a <b>node</b> that matches the specified tag.
Each node can have some text, some attributes (i.e. like hide) and
some "child" nodes. Each node can be the top of a tree of nodes.
</font><pre><font size="4" color="blue">
Name: Chuck
Attr: yes
</font></pre><font color="black">Using an XML parser such as <tt>ElementTree</tt> has the advantage
that while the XML in this example is quite simple, it turns
out there are many rules regarding valid XML and using
<tt>ElementTree</tt> allows us to extract data from XML without
worrying about the rules of XML syntax.</font><br />
<br />
<a name="toc146"></a>
<h2><font color="black"><a name="htoc160">13.3</a> Looping through nodes</font></h2>
<a name="@default771"></a>
<a name="@default772"></a><font color="black">
Often the XML has multiple nodes and we need to write a loop
to process all of the nodes. In the following program,
we loop through all of the <tt>user</tt> nodes:
</font><pre><font size="4" color="blue">
import xml.etree.ElementTree as ET
input = "'
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
</users>
</stuff>"'
stuff = ET.fromstring(input)
lst = stuff.findall('users/user')
print 'User count:', len(lst)
for item in lst:
print 'Name', item.find('name').text
print 'Id', item.find('id').text
print 'Attribute', item.get('x')
</font></pre><font color="black">The <tt>findall</tt> method retrieves a Python list of sub-trees that
represent the <tt>user</tt> structures in the XML tree. Then we can
write a <tt>for</tt> loop that looks at each of the user nodes, and
prints the <tt>name</tt> and <tt>id</tt> text elements as well as the
<tt>x</tt> attribute from the <tt>user</tt> node.
</font><pre><font size="4" color="blue">
User count: 2
Name Chuck
Id 001
Attribute 2
Name Brent
Id 009
Attribute 7
</font></pre>
<a name="toc147"></a>
<h2><font color="black"><a name="htoc161">13.4</a> JavaScript Object Notation - JSON</font></h2>
<a name="@default773"></a>
<a name="@default774"></a>
<font color="black">The JSON format was inspired by the object and array format used in the JavaScript
language. But since Python was invented before JavaScript, Python's syntax
for dictionaries and lists influenced the syntax of JSON. So the format of JSON
is nearly identical to a combination of Python lists and dictionaries.<br />
<br />
Here is a JSON encoding that is roughly equivalent to the simple XML from above:
</font><pre><font size="4" color="blue">
{
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}
}
</font></pre><font color="black">You will notice some differences. First, in XML, we can add attributes like
"intl" to the "phone" tag. In JSON we simply have key-value pairs. Also
the XML "person" tag is gone, replaced by a set of outer curly-braces. <br />
<br />
In general JSON structures are simpler than XML because JSON has less capabilities
than XML. But JSON has the advantage that it maps <em>directly</em> to some combination
of dictionaries and lists. And since nearly all programming languages
have something equivalent to Python's dictionaries and lists, JSON is a very
natural format to have two cooperating programs exchange data.<br />
<br />
JSON is quickly becoming the format of choice for nearly all data exchange between
applications because of its relative simplicity compared to XML.</font><br />
<br />
<a name="toc148"></a>
<h2><font color="black"><a name="htoc162">13.5</a> Parsing JSON</font></h2>
<font color="black">We construct our JSON by nesting dictionaries (objects) and lists as needed. In
this example we represent a list of users where each user is a set of
key value pairs (i.e. a dictionary). So we have a list of dictionaries.<br />
<br />
In the following program, we use the built-in <b>json</b> library parse
the JSON and read through the data. Compare this closely to the equivalent
XML data and code above. The JSON has less detail so we must know in advance
that we are getting a list, and the list is of users and each user is a set of
key value pairs. The JSON is more succinct (an advantage) but also is
less self-describing (a disadvantage).
</font><pre><font size="4" color="blue">
import json
input = "'
[
{ "id" : "001",
"x" : "2",
"name" : "Chuck"
} ,
{ "id" : "009",
"x" : "7",
"name" : "Chuck"
}
]"'
info = json.loads(input)
print 'User count:', len(info)
for item in info:
print 'Name', item['name']
print 'Id', item['id']
print 'Attribute', item['x']
</font></pre>
<font color="black">If you compare the code to extract data from the parsed JSON and XML
you will see that what we get from <b>json.loads()</b>
is a Python list which we traverse with
a <b>for</b> loop and each item within that list
is a Python dictionary which we use the Python
index operator to extract the various bits of each user. Once the JSON has
been parsed - we simply have native Python objects and structures. We don't
have to use the JSON library to dig through the parsed JSON since the returned
data is simply native Python structures.<br />
<br />
The output of this program is exactly the same as the XML version above.
</font><pre><font size="4" color="blue">
User count: 2
Name Chuck
Id 001
Attribute 2
Name Brent
Id 009
Attribute 7
</font></pre><font color="black">In general, there is an industry trend away from XML and towards JSON for
web services. Because the JSON is simpler and more directly maps to native
data structures we already have in programming languages, the parsing
and data extraction code is usually simpler and more direct when using JSON.
But XML is more self-descriptive than JSON and so there are
some applications where XML retains an advantage. For example, most word
processors store documents internally using XML rather than JSON.</font><br />
<br />
<a name="toc149"></a>
<h2><font color="black"><a name="htoc163">13.6</a> Application Programming Interfaces (API)</font></h2>
<font color="black">We now have the ability to exchange data between applications using HyperText
Transport Protocol (HTTP) and a way to represent complex data that we are
sending back and forth between these applications using eXtensible
Markup Language (XML) or JavaScript Object Notation (JSON).<br />
<br />
The next step is to begin to define and document "contracts" between
applications using these techniques. The general name for these
application-to-application contracts is <b>Application Program
Interfaces</b> or APIs. When we use an API, generally one program
makes a set of <b>services</b> available for use by other applications
and publishes the APIs (i.e. the "rules") that must be followed to
access the services provided by the program.<br />
<br />
When we begin to build our programs where the functionality of
our program includes access to services provided by other programs,
we call the approach a <b>Service-Oriented Architecture</b> or SOA.
A SOA approach is one where our overall application makes use of
the services of other applications. A non-SOA approach is where the
application is a single stand-alone application which contains all of the
code necessary to implement the application.<br />
<br />
We see many examples of SOA when we use the web. We can go to a single
web site and book air travel, hotels, and automobiles all from a
single site. The data for hotels is not stored on the airline computers.
Instead, the airline computers contact the services on the hotel computers
and retrieve the hotel data and present it to the user. When the user
agrees to make a hotel reservation using the airline site, the airline site uses
another web service on the hotel systems to actually make the reservation.
And when it comes to charge your credit card for the whole transaction,
still other computers become involved in the process.<br />
</font><div align="center"><font color="black"><img src="cfbook015.png" /></font></div><font color="black">
<br />
A Service-Oriented Architecture has many advantages including: (1) we
always maintain only one copy of data - this is particularly important
for things like hotel reservations where we do not want to over-commit
and (2) the owners of the data can set the rules about the use of their
data. With these advantages, a SOA system must be carefully designed
to have good performance and meet the user's needs.<br />
<br />
When an application makes a set of services in its API available over the web,
we call these <b>web services</b>. </font><br />
<br />
<a name="toc150"></a>
<h2><font color="black"><a name="htoc164">13.7</a> Google geocoding web service</font></h2>
<a name="@default775"></a>
<a name="@default776"></a>
<a name="@default777"></a>
<font color="black">Google has an excellent web service that allows us to make use of their
large database of geographic information. We can submit a geographical
search string like "Ann Arbor, MI" to their geocoding API and have Google
return its best guess as to where on a map we might find our search string and
tells us about the landmarks nearby.<br />
<br />
The geocoding service is free but rate limited so you cannot make unlimited
use of the API in a commercial application. But if you have some survey data
where an end-user has entered a location in a free-format input box, you can use
this API to clean up your data quite nicely. <br />
<br />
<em>When you are using a free API like Google's geocoding API, you need
to be respectful in your use of these resources. If too many people abuse the
service, Google might drop or significantly curtail its free service.</em>
<a name="@default778"></a><br />
<br />
You can read the online documentation for this service, but it is quite simple
and you can even test it using a browser by typing the following URL into your
browser:<br />
<br />
<tt>http://maps.googleapis.com/maps/api/geocode/json?sensor=false &address=Ann+Arbor%2C+MI</tt><br />
<br />
Make sure to un-wrap the URL and remove any spaces from the URL before pasting
it into your browser.<br />
<br />
The following is a simple application to prompt the user for a search string
and call the Google geocoding API and extract information from the returned
JSON.
</font><pre><font size="4" color="blue">
import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false',
'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
print data
continue
print json.dumps(js, indent=4)
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print 'lat',lat,'lng',lng
location = js['results'][0]['formatted_address']
print location
</font></pre><font color="black">The program takes the search string and constructs a URL with the
search string as a properly encoded parameter and then uses
<b>urllib</b> to retrieve the text from the Google geocoding API.
Unlike a fixed web page, the data we get depends on the parameters
we send and the geographical data stored in Google's servers.<br />
<br />
Once we retrieve the JSON data, we parse it with the <b>json</b>
library and do a few checks to make sure that we received good data
and then extract the information that we are looking for.<br />
<br />
The output of the program is as follows (some of the returned
JSON has been removed):
</font><pre><font size="4" color="blue">
$ python geojson.py
Enter location: Ann Arbor, MI
Retrieving http://maps.googleapis.com/maps/api/
geocode/json?sensor=false&address=Ann+Arbor%2C+MI
Retrieved 1669 characters
{
"status": "OK",
"results": [
{
"geometry": {
"location_type": "APPROXIMATE",
"location": {
"lat": 42.2808256,
"lng": -83.7430378
}
},
"address_components": [
{
"long_name": "Ann Arbor",
"types": [
"locality",
"political"
],
"short_name": "Ann Arbor"
}
],
"formatted_address": "Ann Arbor, MI, USA",
"types": [
"locality",
"political"
]
}
]
}
lat 42.2808256 lng -83.7430378
Ann Arbor, MI, USA
Enter location:
</font></pre><font color="black">You can download
<tt>www.py4inf.com/code/geojson.py</tt> and
<tt>www.py4inf.com/code/geoxml.py</tt> to explore the JSON
and XML variants of the Google geocoding API. </font><br />
<br />
<a name="toc151"></a>
<h2><font color="black"><a name="htoc165">13.8</a> Security and API usage</font></h2>
<a name="@default779"></a>
<a name="@default780"></a>
<font color="black">It is quite common that you need some kind of
"API key" to make use of a vendor's API. The
general idea is that they want to know who is using
their services and how much each user is using.
Perhaps they have free and pay tiers of their services
or have a policy that limits the number of requests
that a single individual can during a particular
time period.<br />
<br />
Sometimes once you get your API key, you simply include
the key as part of POST data or perhaps as a parameter
on the URL when calling the API.<br />
<br />
Other times, the vendor wants increased assurance of
the source of the requests and so they add expect you
to send cryptographically signed messages using shared
keys and secrets. A very common technology that is used
to sign requests over the Internet is called <b>OAuth</b>.
You can read more about the OAuth protocol at
<tt>http://www.oauth.net</tt>.<br />
<br />
As the Twitter API became increasingly valuable, Twitter
went from an open and public API to an API that required
the use of OAuth signatures on each API request. Thankfully
there are a number of convenient and free OAuth libraries
are available
so you can avoid writing an OAuth implementation from scratch
by reading the specification. These libraries are of
varying complexity and have varying
richness. The OAuth web site has information about various
OAuth libraries.<br />
<br />
For this next sample program we will download these files:
<b>twurl.py</b>, <b>hidden.py</b>,
<b>oauth.py</b>,
and
<b>twitter1.py</b> from
<tt>www.py4inf.com/code</tt> and put them all in a folder
on your computer.<br />
<br />
To make use of these programs you will need to have a Twitter
account, and authorize your Python code as an application,
set up a key, secret, token and token secret. You will edit
the file <b>hidden.py</b> and put these four strings into the
appropriate variables in the file:
</font><pre><font size="4" color="blue">
def auth() :
return { "consumer_key" : "h7L...GNg",
"consumer_secret" : "dNK...7Q",
"token_key" : "101...GI",
"token_secret" : "H0yM...Bo" }
</font></pre><font color="black">The Twitter web service are accessed using a URL like this:<br />
<br />
<tt>https://api.twitter.com/1.1/statuses/user_timeline.json</tt><br />
<br />
But once all of the security information has been added, the URL
will look more like:
</font><pre><font size="4" color="blue">
https://api.twitter.com/1.1/statuses/user_timeline.json?count=2
&oauth_version=1.0&oauth_token=101...SGI&screen_name=drchuck
&oauth_nonce=09239679&oauth_timestamp=1380395644
&oauth_signature=rLK...BoD&oauth_consumer_key=h7Lu...GNg
&oauth_signature_method=HMAC-SHA1
</font></pre><font color="black">You can read the OAuth specification if you want to
know more about the meaning of the various parameters that
are added to meet the security requirements of OAuth. <br />
<br />
For the programs we run with Twitter, we hide all the
complexity in the files <b>oauth.py</b> and <b>twurl.py</b>.
We simply set the secrets in <b>hidden.py</b> and then
send the desired URL to the <b>twurl.augment()</b>
function and the library code adds all the necessary
parameters to the URL for us.<br />
<br />
This program (<b>twitter1.py</b>) retrieves the timeline
for a particular Twitter user and returns it to us in JSON
format in a string. We simply print the first 250 characters
of the string:
</font><pre><font size="4" color="blue">
import urllib
import twurl
TWITTER_URL='https://api.twitter.com/1.1/statuses/user_timeline.json'
while True:
print "
acct = raw_input('Enter Twitter Account:')
if ( len(acct) < 1 ) : break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '2'} )
print 'Retrieving', url
connection = urllib.urlopen(url)
data = connection.read()
print data[:250]
headers = connection.info().dict
# print headers
print 'Remaining', headers['x-rate-limit-remaining']
</font></pre><font color="black">When the program runs it produces the following output:
</font><pre><font size="4" color="blue">
Enter Twitter Account:drchuck
Retrieving https://api.twitter.com/1.1/ ...
[{"created_at":"Sat Sep 28 17:30:25 +0000 2013","
id":384007200990982144,"id_str":"384007200990982144",
"text":"RT @fixpert: See how the Dutch handle traffic
intersections: http:\/\/t.co\/tIiVWtEhj4\n#brilliant",
"source":"web","truncated":false,"in_rep
Remaining 178
Enter Twitter Account:fixpert
Retrieving https://api.twitter.com/1.1/ ...
[{"created_at":"Sat Sep 28 18:03:56 +0000 2013",
"id":384015634108919808,"id_str":"384015634108919808",
"text":"3 months after my freak bocce ball accident,
my wedding ring fits again! :)\n\nhttps:\/\/t.co\/2XmHPx7kgX",
"source":"web","truncated":false,
Remaining 177
Enter Twitter Account:
</font></pre><font color="black">Along with the returned timeline data, Twitter also returns
metadata about the request in the HTTP response headers.
One header in particular, <b>x-rate-limit-remaining</b> informs
us how many more requests we can make before we will be shut
off for a short time period. You can see that our remaining
retrievals drop by one each time we make a request to the
API.<br />
<br />
In the following example, we retrieve a user's Twitter friends
and parse the returned JSON and extract some of the information
about the friends. We also dump the JSON after parsing and
"pretty-print" it with an indent of four characters to allow
us to pore through the data when we want to extract more fields.
</font><pre><font size="4" color="blue">
import urllib
import twurl
import json
TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json'
while True:
print "
acct = raw_input('Enter Twitter Account:')
if ( len(acct) < 1 ) : break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '5'} )
print 'Retrieving', url
connection = urllib.urlopen(url)
data = connection.read()
headers = connection.info().dict
print 'Remaining', headers['x-rate-limit-remaining']
js = json.loads(data)
print json.dumps(js, indent=4)
for u in js['users'] :
print u['screen_name']
s = u['status']['text']
print ' ',s[:50]
</font></pre><font color="black">Since the JSON becomes a set of nested Python lists and dictionaries,
we can use a combination of the index operation and for loops to
wander through the returned data structures with very little
Python code.<br />
<br />
The output of the program looks as follows (some of the data items
are shortened to fit on the page):
</font><pre><font size="4" color="blue">
Enter Twitter Account:drchuck
Retrieving https://api.twitter.com/1.1/friends ...
Remaining 14
{
"next_cursor": 1444171224491980205,
"users": [
{
"id": 662433,
"followers_count": 28725,
"status": {
"text": "@jazzychad I just bought one .__.",
"created_at": "Fri Sep 20 08:36:34 +0000 2013",
"retweeted": false,
},
"location": "San Francisco, California",
"screen_name": "leahculver",
"name": "Leah Culver",
},
{
"id": 40426722,
"followers_count": 2635,
"status": {
"text": "RT @WSJ: Big employers like Google ...",
"created_at": "Sat Sep 28 19:36:37 +0000 2013",
},
"location": "Victoria Canada",
"screen_name": "_valeriei",
"name": "Valerie Irvine",
],
"next_cursor_str": "1444171224491980205"
}
leahculver
@jazzychad I just bought one .__.
_valeriei
RT @WSJ: Big employers like Google, AT&amp;T are h
ericbollens
RT @lukew: sneak peek: my LONG take on the good &a
halherzog
Learning Objects is 10. We had a cake with the LO,
scweeker
@DeviceLabDC love it! Now where so I get that "etc
Enter Twitter Account:
</font></pre><font color="black">The last bit of the output is where we see the for loop reading the
five most recent "friends" of the <b>drchuck</b> Twitter account
and printing the most recent status for each friend. There is a
great deal more data available in the returned JSON. Also if you look
in the output of the program, you can see that the "find the friends"
of a particular account has a different rate limitation than
the number of timeline queries we are allowed to run per time period.<br />
<br />
These secure API keys allow Twitter to have solid confidence that they
know who is using their API and data and at what level. The rate
limiting approach allows us to do simple, personal data retrievals but
does not allow us to build a product that pulls data from their API
millions of times per day.</font><br />
<br />
<a name="toc152"></a>
<h2><font color="black"><a name="htoc166">13.9</a> Glossary</font></h2>
<dl compact="compact"><dt><font color="black"><b>API:</b></font></dt><dd><font color="black"> Application Program Interface - A contract between
applications that defines the patterns of interaction between
two application components.
</font><a name="@default781"></a><br />
<br />
</dd><dt><font color="black"><b>ElementTree:</b></font></dt><dd><font color="black"> A built-in Python library used to parse XML data.
</font><a name="@default782"></a><br />
<br />
</dd><dt><font color="black"><b>JSON:</b></font></dt><dd><font color="black"> JavaScript Object Notation- A format that allows for
the markup of structured data based on the syntax of JavaScript
Objects.
</font><a name="@default783"></a>
<a name="@default784"></a><br />
<br />
</dd><dt><font color="black"><b>REST:</b></font></dt><dd><font color="black"> REpresentational State Transfer - A style of Web Services
that provide access to resources within an application using the HTTP
protocol.
</font><a name="@default785"></a><br />
<br />
</dd><dt><font color="black"><b>SOA:</b></font></dt><dd><font color="black"> Service Oriented Architecture - when an application is
made of components connected across a network.
</font><a name="@default786"></a>
<a name="@default787"></a><br />
<br />
</dd><dt><font color="black"><b>XML:</b></font></dt><dd><font color="black"> eXtensible Markup Language - A format that allows for
the markup of structured data.
</font><a name="@default788"></a>
<a name="@default789"></a></dd></dl>
<a name="toc153"></a>
<h2><font color="black"><a name="htoc167">13.10</a> Exercises</font></h2><br />
<div align="left"><font color="black"><b>Exercise 1</b> <em>
Change either the
<tt>www.py4inf.com/code/geojson.py</tt> or
<tt>www.py4inf.com/code/geoxml.py</tt> to print out the
two-character country code from the retrieved data.
Add error checking so your program does not traceback
if the country code is not there. Once you have it
working, search for "Atlantic Ocean" and make sure
it can handle locations that are not in any country.
</em></font></div><br />
<hr />
<a href="cfbook013.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="cfbook015.html"><img src="next_motif.gif" alt="Next" /></a>
</body>
</html>