[Python] python common functions

Source: Internet
Author: User
Tags comparison table hmac urlencode

UrlEncode and UrlDecode

When the URL contains Chinese or the parameter contains Chinese, the Chinese or special characters (/, &) need to be encoded for conversion.
The essence of UrlEncode: Convert the string to GBK encoding, and then replace the \x with%. If the terminal is UTF8 encoded, you need to turn the result into a UTF8 output, otherwise it will be garbled.

UrlEncode

The UrlEncode function inside the Urllib library can urlencode and convert the key and value of the Key-value health value to the a=1&b=2 string.

#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

The quote function inside the Urllib library can be UrlEncode converted to a single string.

#string>>> from urllib import quote>>> data="测试">>> print quote(data)%E6%B5%8B%E8%AF%95
UrlDecode

Urllib only provides the unquote () function.

>>> 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 processing

Two functions:

function Description
Json.dumps Encode a Python object as a JSON string (Object---string)
Json.loads Decodes an encoded JSON string into a Python object (string--object)
Json.dumps

Syntax: 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"}>>>

The conversion table of the Python primitive type to JSON type:

Python JSON
Dict Object
List,tuple Array
Str,unicode String
Int,long,float Number
True True
False False
None Null
Json.loads

json.loads--returns the data type of the Python field

>>> 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 type conversion to Python type comparison table

JSON Python
Object Dict
Array List
String Unicode
Number (int) Int,long
Number (real) Float
True True
False False
Null None

Conclusion: Print only outputs Python-recognized data types, and python.dumps can format the output.

Computes the string MD5

Method One: Use the MD5 package

import md5def calMd5(signdata,signkey,joiner=""):    signdata=signdata+joiner+""+signkey    m=md5.new(signdata)    sign = m.hexdigest()    return sign

Method Two: Use the Hashlib package

import hashlibdef calHashMd5(signdata,signkey,joiner=""):    signdata=signdata+joiner+""+signkey    m=hashlib.md5(signdata)    sign = m.hexdigest()    return sign
Calculate HMACSHA1

HMAC: Key-related hash operation message authentication code, the HMAC operation takes advantage of a hashing algorithm (either MD5 or SHA-1), with a key and a message as input, generating a message digest as output.

Role:
(1) Verifying the accepted authorization data and authentication data;
(2) Confirm that the received command request is an authorized request and that the transfer process has not been tampered with

import hmacimport base64def hmacSha1WithBase64(signdata,signkey):    sign = hmac.new(signkey, signdata,sha1).digest()    sign = base64.b64encode(sign)    return sign
string concatenation
from collections import OrderedDictdef 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

[Python] python common functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.