|
参考源码: https://github.com/michaelliao/sinaweibopy/blob/master/weibo.py
1 使用python调用weibo api
2
3 # 调用的url地址 此为获取某人的个人信息的api http://open.weibo.com/wiki/2/users/show
4 the_url = 'https://api.weibo.com/2/users/show.json?uid=105729xxxx&access_token=2.xxx__YJBzk8g4Ddfd33f10237XXXXX'
5
6 http_body = None
7
8 # 发送请求并读取返回 返回的内容是真个html源代码,或者json数据,可以通过文件输出或者包一层repr()来查看内容
9 req = urllib2.Request(the_url, data=http_body)
10
11 #当然也可以用此来发送请求,并读取返回的内容是真个html源代码,可以通过文件输出或者包一层repr()来查看内容
12 req = urllib2.Request("http://www.baidu.com", data=http_body)
13
14 resp = urllib2.urlopen(req)
15 print repr(resp.read())
16
17
18
19 import json
20 # 原配json工具
21 json.loads(resp.read(), object_hook=_obj_hook)
22
23
24 io = StringIO('["streaming API"]')
25 print io.getvalue()
26 # 输出为 ["streaming API"] io输出为一个StringIO对象
27
28 # 注 json工具 提供load和loads2个方法
29 json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
30
31 json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
32
33 其中fp 按照官方的解释[http://docs.python.org/2/glossary.html#term-file-object]是面向文件的系统,或者那种提供.read(),.write()方法的对象,比如上面的StringIO
34 s 为普通的str或者unicode,相应json数据于python数据的对应如下
35
36 [http://docs.python.org/2/library/json.html?highlight=object_hook#json-to-py-table]
37 JSON Python
38 object dict
39 array list
40 string unicode
41 number (int) int, long
42 number (real) float
43 true True
44 false False
45 null None
46
47 # 转换json数据
48 如果json数据如此
49 {
50 "ip_limit": 1000,
51 "limit_time_unit": "HOURS",
52 "remaining_ip_hits": 1000,
53 "remaining_user_hits": 146,
54 "reset_time": "2013-04-19 15:00:00",
55 "reset_time_in_seconds": 3286,
56 "user_limit": 150
57 }
58 # 关于 object_hook 非必选函数 用于替换原本钓鱼json.loads返回的一个dict,
59 # json.loads返回的dict如果遇到一个不存在的量 比如"abc" 则会报错,
60 # 于是用object_hook 返回一个自己定义的dict 让他在遇到"abc"这个不存在的变量时不直接反错
61 # 而是try catch一下 返回None 更稳定
62
63 def _parse_json(s):
64 ' parse str into JsonDict '
65
66 def _obj_hook(pairs):
67 ' convert json object to python object '
68 o = JsonDict()
69 # print pairs['list_id']
70 print 'text' in pairs
71 if 'text' in pairs:
72 # it can output utf8
73 print pairs['text']
74 # ---
75 for k, v in pairs.iteritems():
76 o[str(k)] = v
77 return o
78 #loads is different from load
79 return json.loads(s, object_hook=_obj_hook)
80
81 class JsonDict(dict):
82 ' general json object that allows attributes to be bound to and also behaves like a dict '
83
84 def __getattr__(self, attr):
85 try:
86 return self[attr]
87 except KeyError:
88 raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
89
90 def __setattr__(self, attr, value):
91 self[attr] = value
92
93 # 此 JsonDict 是dict(字典对象)的子类 它重写了 取索引的方法 __getattr__ 和 __setattr__
94
95 # 这里获取dict里的数据有个技巧 在获取JsonDict的对象时有2中方法
96 d1 = JsonDict();
97
98 d1['a'] = 'strra'
99 print d1['a']
100 print d1.get('a')
101 # 此 aaaa 并不在dict中
102 print d1.get('aaaa') # None
103 print d1['aaaa'] # key error~
104
105 # 使用get获取dict里的数据 遇到空的数据的话 可以避免error的产生 自动转成None
|
|
|