urlencode 与 urldecode
当 url 中包含中文或者参数包含中文,需要对中文或者特殊字符(/、&)做编码转换。 urlencode 的本质:把字符串转为 gbk 编码,再把 \x 替换成 %。如果终端是 utf8 编码的,需要把结果再转成 utf8 输出,否则会乱码。
urlencode
urllib 库里面的 urlencode 函数,可以把 key-value 健值对的 key、value 都进行 urlencode 并转换成 a=1&b=2 的字符串。
#key-value健值对
>>> from urllib import urlencode
>>> data={'a':'a1','b':'中文'}
>>> print urlencode(data)
a=a1&b=%E4%B8%AD%E6%96%87
>>> data={'a':'a1','b测试':'中文'}
>>> print urlencode(data)
a=a1&b%E6%B5%8B%E8%AF%95=%E4%B8%AD%E6%96%87
urllib 库里面的 quote 函数,可以针对单个字符串进行 urlencode 转换。
#string
>>> from urllib import quote
>>> data="测试"
>>> print quote(data)
%E6%B5%8B%E8%AF%95
urldecode
urllib 只提供了 unquote () 函数。
>>> from urllib import unquote
>>> unquote("%E6%B5%8B%E8%AF%95")
'\xe6\xb5\x8b\xe8\xaf\x95'
>>> print unquote("%E6%B5%8B%E8%AF%95")
测试
>>>
json 处理
两个函数:
函数 | 描述 |
---|---|
json.dumps | 将 python 对象编码成 JSON 字符串(对象 -> 字符串) |
json.loads | 将已经编码的 json 字符串解码为 Python 对象(字符串 -> 对象) |
json.dumps
语法:json.dumps (data, sort_keys=True, indent=4,separators=(self.item_separator, self.key_separator))
>>> import json
>>> data={"a":"a1","b":"b1"}
>>> jsonstr=json.dumps(data)
>>> print jsonstr
{"a": "a1", "b": "b1"}
#输出格式化
>>> print json.dumps(data, sort_keys=True, indent=4,separators=(",",":"))
{
"a":"a1",
"b":"b1"
}
>>>
python 原始类型向 json 类型的转换对照表:
Python | JSON |
---|---|
dict | object |
list,tuple | array |
str,unicode | string |
int,long,float | number |
True | true |
False | false |
None | null |
json.loads
json.loads—— 返回 Python 字段的数据类型
>>> import json
>>> jsonstr='{"a":"a1","b":"b1"}'
>>> print json.loads(jsonstr)
{u'a': u'a1', u'b': u'b1'}
>>> jsonstr='{"a":"a1","b":null,"c":false,"d":{"aa":"aa1","bb":"bb1"}}'
>>> print json.loads(jsonstr)
{u'a': u'a1', u'c': False, u'b': None, u'd': {u'aa': u'aa1', u'bb': u'bb1'}}
>>> jsonstr='[{"a":"a1"},{"b":"b2"}]'
>>> print json.loads(jsonstr)
[{u'a': u'a1'}, {u'b': u'b2'}]
json 类型转换为 python 类型的对照表
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number(int) | int,long |
number(real) | float |
true | True |
false | False |
null | None |
结论:print 只能输出 python 认识的数据类型,python.dumps 才可以格式化输出。
计算字符串 md5
方法一:使用 md5 包
import md5
def calMd5(signdata,signkey,joiner=""):
signdata=signdata+joiner+""+signkey
m=md5.new(signdata)
sign = m.hexdigest()
return sign
方法二:使用 hashlib 包
import hashlib
def calHashMd5(signdata,signkey,joiner=""):
signdata=signdata+joiner+""+signkey
m=hashlib.md5(signdata)
sign = m.hexdigest()
return sign
计算 hmacsha1
hmac: 密钥相关的哈希运算消息认证码,hmac 运算利用哈希算法(可以是 MD5 或者 SHA-1),以一个密钥和一个消息为输入,生成一个消息摘要作为输出。
作用:
(1)验证接受的授权数据和认证数据; (2)确认接受到的命令请求是已经授权的请求且传送过程没有被篡改
import hmac
import base64
def hmacSha1WithBase64(signdata,signkey):
sign = hmac.new(signkey, signdata,sha1).digest()
sign = base64.b64encode(sign)
return sign
字符串拼接
from collections import OrderedDict
def composeStr(data,joiner,withkey=True,key_value_joiner="="):
data = OrderedDict(sorted(data.items(), key=lambda t:t[0]))
if withkey :
signdata = joiner.join([key_value_joiner.join((str(key), str(elem))) for key, elem in data.iteritems()])
else :
signdata= joiner.join([elem for key, elem in data.items()])
return signdata