Skip to content

Commit aadfc63

Browse files
committed
Added JSON and requests examples
1 parent 0473865 commit aadfc63

3 files changed

Lines changed: 176 additions & 32 deletions

File tree

JSON/json_sample.py

Lines changed: 88 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,77 @@
66
An object is an unordered set of name/value pairs. An object begins with
77
{ left brace and ends with right brace }. Each name is followed by : (color)
88
and the name/value pairs are separated by , (comma)
9+
10+
json.tool can be used to validate json from the shell
11+
$echo '{"json":"obj"}' | python -mjson.tool
12+
{
13+
"json": "obj"
14+
}
15+
$echo '{1.2:3.4}' | python -mjson.tool
16+
Returns "Expecting property name enclosed in double quotes
17+
18+
Tutorial here: http://pymotw.com/2/json/
919
"""
1020

1121
import json
1222

1323

24+
def print_original_object(myobject):
25+
""" Helper function to find out what the original object is """
26+
print "Original object is type: ", type(myobject)
27+
print "Original object is: ", repr(myobject)
28+
29+
30+
def print_returned_object(myobject):
31+
""" Helpter function to find out what the returned object is """
32+
print "Returned object is type: ", type(myobject)
33+
print "Returned object is: ", repr(myobject)
34+
35+
1436
def encoding_basic_python_object():
37+
print "ENCODING BASIC PYTHON OBJECT"
1538
print "Example 1:"
16-
a = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
17-
print type(a) #<type 'str'>
18-
print a # ["foo", {"bar": ["baz", null, 1.0, 2]}]
39+
myobject = ['foo', {'bar': ('baz', None, 1.0, 2)}]
40+
print_original_object(myobject)
41+
# Original object is type: <type 'list'>
42+
# Original object is ['foo', {'bar': ('baz', None, 1.0, 2)}]
43+
a = json.dumps(myobject)
44+
print_returned_object(myobject)
45+
# Returned object is type: <type 'list'>
46+
# Returned object is: ['foo', {'bar': ('baz', None, 1.0, 2)}]
1947

2048
print "Example 2:"
21-
b = json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
22-
print type(b) #<type 'str'>
23-
print b # {"a": 0, "b": 0, "c": 0}
49+
myobject = {"c": 0, "b": 0, "a": 0}
50+
print_original_object(myobject)
51+
# Original object is type: <type 'dict'>
52+
# Original object is {'a': 0, 'c': 0, 'b': 0}
53+
b = json.dumps(myobject, sort_keys=True)
54+
print_returned_object(myobject)
55+
# Returns type: <type 'str'>
56+
# Original object is: {"a": 0, "b": 0, "c": 0}
2457

2558

2659
def compact_encoding():
60+
print "COMPACT ENCODING"
2761
print "Example 1:"
28-
c = json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':'))
29-
print type(c) #<type 'str'>
30-
print c # [1,2,3,{"4":5,"6":7}]
62+
myobject = [1,2,3,{'4': 5, '6': 7}]
63+
print_original_object(myobject)
64+
# Original object is type: <type 'list'>
65+
# Original object is [1, 2, 3, {'4': 5, '6': 7}]
66+
c = json.dumps(myobject, separators=(',', ':'))
67+
print_returned_object(myobject)
68+
# Returned object is type: <type 'list'>
69+
# Returned object is: [1, 2, 3, {'4': 5, '6': 7}]
3170

3271

3372
def pretty_print():
73+
print "PRETTY PRINTING (tldr; use indent to make it look nice"
3474
print "Example 1:"
35-
d = json.dumps({'4': 5, '6': 7}, sort_keys=True,
75+
myobject = {'4': 5, '6': 7}
76+
print_original_object(myobject)
77+
# Original object is type: <type 'dict'>
78+
# Original object is {'4': 5, '6': 7}
79+
d = json.dumps(myobject, sort_keys=True,
3680
indent=2, separators=(',', ':'))
3781
print type(d) #<type 'str'>
3882
print d
@@ -43,10 +87,16 @@ def pretty_print():
4387

4488

4589
def decoding_JSON():
90+
print "DECODING JSON"
4691
print "Example 1:"
47-
e = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
48-
print type(e) #<type 'list'>
49-
print e #[u'foo', {u'bar': u['baz', None, 1.0, 2]}]
92+
myobject = '["foo", {"bar":["baz", null, 1.0, 2]}]'
93+
print_original_object(myobject)
94+
# Original object is type: <type 'str'>
95+
# Original object is ["foo", {"bar":["baz", null, 1.0, 2]}]
96+
e = json.loads(myobject)
97+
print_returned_object(myobject)
98+
# Returned object is type: <type 'str'>
99+
# Returned object is: ["foo", {"bar":["baz", null, 1.0, 2]}]
50100

51101

52102
#For specializing_JSON_object_decoding() example
@@ -57,14 +107,34 @@ def as_complex(dct):
57107

58108

59109
def specializing_JSON_object_decoding():
110+
print "Specializing JSON object decoding"
60111
print "Example 1:"
61-
print json.loads('{"__complex__": true, "real": 1, "imag": 2}',
112+
myobject = '{"__complex__": true, "real": 1, "imag": 2}'
113+
print_original_object(myobject)
114+
# Original object is type: <type 'str'>
115+
# Original object is {"__complex__": true, "real": 1, "imag": 2}
116+
f = json.loads(myobject,
62117
object_hook=as_complex) #(1+2j)
118+
print_returned_object(myobject)
119+
# Returned object is type: <type 'str'>
120+
# Returned object is: {"__complex__": true, "real": 1, "imag": 2}
121+
122+
123+
def dumped_length():
124+
""" Shows different file sizes of each """
125+
print "DUMPED LENGTH"
126+
data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
127+
print 'DATA:', repr(data) # DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}]
128+
print 'repr(data) :', len(repr(data)) # 35
129+
print 'dumps(data) :', len(json.dumps(data)) # 35
130+
print 'dumps(data, indent=2) :', len(json.dumps(data, indent=2)) # 76
131+
print 'dumps(data, separators):', len(json.dumps(data, separators=(',',':'))) # 29
63132

64133

65134
if __name__ == '__main__':
66-
encoding_basic_python_object()
67-
compact_encoding()
68-
pretty_print()
135+
#encoding_basic_python_object()
136+
#compact_encoding()
137+
#pretty_print()
69138
decoding_JSON()
70-
specializing_JSON_object_decoding()
139+
#specializing_JSON_object_decoding()
140+
#dumped_length()

python.sublime-workspace

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@
116116
"buffers":
117117
[
118118
{
119-
"file": "learn.TODO",
119+
"file": "Pickle/pickle_sample.py",
120120
"settings":
121121
{
122-
"buffer_size": 2854,
122+
"buffer_size": 1447,
123123
"line_ending": "Unix"
124124
}
125125
}
@@ -202,8 +202,14 @@
202202
"side_bar_visible": false,
203203
"status_bar_visible": false
204204
},
205+
"expanded_folders":
206+
[
207+
"/Users/williamliu/GitHub/Python",
208+
"/Users/williamliu/GitHub/Python/Pickle"
209+
],
205210
"file_history":
206211
[
212+
"/Users/williamliu/GitHub/Python/learn.TODO",
207213
"/Users/williamliu/GitHub/Python/Celery/tasks.py",
208214
"/Users/williamliu/GitHub/surveys/login",
209215
"/Users/williamliu/Downloads/xkcd.py",
@@ -330,8 +336,7 @@
330336
"/Users/williamliu/GitHub/MHADjango/datasite/static/css/images/ui-bg_gloss-wave_35_f6a828_500x100.png",
331337
"/Users/williamliu/GitHub/MHADjango/datasite/static/css/cover.css",
332338
"/Users/williamliu/GitHub/MHADjango/datasite/static/js/custom.js",
333-
"/Users/williamliu/GitHub/WebDev/jQuery/tutsplus/jquery-1.11.1.js",
334-
"/Users/williamliu/GitHub/WebDev/jQuery/tutsplus/index.html"
339+
"/Users/williamliu/GitHub/WebDev/jQuery/tutsplus/jquery-1.11.1.js"
335340
],
336341
"find":
337342
{
@@ -486,19 +491,19 @@
486491
[
487492
{
488493
"buffer": 0,
489-
"file": "learn.TODO",
494+
"file": "Pickle/pickle_sample.py",
490495
"semi_transient": false,
491496
"settings":
492497
{
493-
"buffer_size": 2854,
498+
"buffer_size": 1447,
494499
"regions":
495500
{
496501
},
497502
"selection":
498503
[
499504
[
500-
626,
501-
626
505+
825,
506+
825
502507
]
503508
],
504509
"settings":
@@ -610,9 +615,7 @@
610615
"remote_loading": false,
611616
"sublime_auto_complete": true,
612617
"synced": false,
613-
"syntax": "Packages/PlainTasks/PlainTasks.tmLanguage",
614-
"tab_size": 2,
615-
"translate_tabs_to_spaces": true
618+
"syntax": "Packages/Djaneiro/Syntaxes/Python Django.tmLanguage"
616619
},
617620
"translation.x": 0.0,
618621
"translation.y": 0.0,
@@ -701,6 +704,7 @@
701704
],
702705
"width": 0.0
703706
},
707+
"selected_group": 0,
704708
"settings":
705709
{
706710
},

requests/example_requests.py

Lines changed: 73 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,82 @@
11
""" Using Python's requests library """
22

3+
import json
34
import requests
45

56

6-
def get_webpage(site):
7-
""" GET """
7+
def get_webpage_details(site):
8+
""" GET details of a request """
89
r = requests.get(site)
10+
print "Status Code: ", r.status_code
11+
#print r.headers # Gets all headers as a dict
12+
print "Get specific field (e.g. 'content-type'):", r.headers['content-type'] # Get specific field
13+
print "Get encoding: ", r.encoding
14+
#print "Get Text: ", r.text # Get all text of page
15+
print "Get JSON: ", r.json() #
16+
print "GET Response Code: ", r.status_code
17+
18+
19+
def request_API_calls():
20+
""" Using all HTTP request types (POST, PUT, DELETE, HEAD, OPTIONS) """
21+
r = requests.post('http://httpbin.org/post') # Example of POST
22+
print "POST: ", r
23+
r = requests.put('http://httpbin.org/put') # Example of PUT
24+
print "PUT: ", r
25+
r = requests.delete('http://httpbin.org/delete') # Example of DELETE
26+
print "DELETE: ", r
27+
r = requests.head('http://httpbin.org/get') # Example of HEAD
28+
print "HEAD: ", r
29+
r = requests.options('http://httpbin.org/get') # Example of OPTIONS
30+
print "OPTIONS: ", r
31+
32+
33+
def pass_params_in_urls():
34+
""" How to pass data in the URL's query string
35+
By hand, getting URL would be given as key/value pairs in the URL
36+
after the question mark (e.g. httpbin.org/get?key=val)
37+
"""
38+
39+
# If you want to pass 'key1=value1' and 'key2=value2' to 'httpbin.org/get'
40+
payload = {'key1': 'value1', 'key2': 'value2'}
41+
r = requests.get("http://httpbin.org/get", params=payload)
42+
43+
# Verify that URL has been encoded correctly by printing out URL
44+
print "URL is: ", r.url # http://httpbin.org/get?key2=value2&key1=value1
45+
46+
47+
def pass_headers_in_request():
48+
""" Add HTTP headers to a request by adding a dict to the 'headers' param """
49+
url = 'https://api.github.com/some/endpoint'
50+
payload = { 'some': 'data' }
51+
headers = { 'content-type': 'application/json' }
52+
r = requests.post(url, data=json.dumps(payload), headers=headers)
53+
print r
54+
55+
56+
def response_content():
57+
""" We can read the server's response """
58+
r = requests.get('https://developer.github.com/v3/activity/events/#list-public-events')
59+
print "Server's Response is: ", r.text
60+
61+
# When you make a request, Requests makes an educated guess on encoding
62+
# based on the response of the HTTP headers
63+
print "Guessed encoding is: ", r.encoding # utf-8
64+
#print "Peak at content if unsure of encoding, sometimes specified in here ", r.content
65+
66+
67+
def json_response_content():
68+
""" There's a builtin JSON decoder for dealing with JSON data """
69+
r = requests.get('http://www.json-generator.com/api/json/get/bVVKnZVjpK?indent=2')
70+
print "Getting JSON: ", r # Should be 200 or else if error, then 401 (Unauthorized)
71+
#print r.json()
972

1073

1174
if __name__ == '__main__':
12-
get_webpage('https://api.github.com/events')
75+
#get_webpage_details('https://api.github.com/events')
76+
#request_API_calls()
77+
#pass_params_in_urls()
78+
pass_headers_in_request()
79+
#response_content()
80+
#json_response_content()
81+
82+

0 commit comments

Comments
 (0)