Web,暗号,正規表現 ライブラリメモ (python3.4)

Web

urllib.parse

URLのパースを行う

result = parse.urlparse(
    'https://www.google.co.jp?q=example&qq=1#hoge')

print(result)
print(result.geturl()) # URL取得
print(result.path) # パス名取得
print(parse.parse_qs(result.query)) # クエリ取得

reqests

GET,POSTメソッドとかをわかりやすく使いやすく。

まずはpipあたりでインストールする。

import requests
headers = {'Accept': 'application/json'} # 任意のヘッダの追加
r = requests.get('http://httpbin.org/get',params='example') # GET
r = requests.post('http://httpbin.org/post',headers=headers) # POST
print(r.text) # レスポンス表示

base64

文字列をbase64に変換

import base64
s = 'Pythonおもしろいです'
print((base64.b64decode((base64.b64encode(s.encode())))).decode())

email

メールの解析を行う。

import email
import email.parser
parser = email.parser.Parser()  # Parser生成
with open("email.txt") as f:
    m = parser.parse(f) # parse
    print(type(m))
    print(m.items()) # ヘッダ取得
    print(m.get_payload()) # 本文取得
    print(m.as_string()) # 全体取得

暗号

ハッシュ関数

from Crypto.Hash import MD5, SHA512
hash_md5 = MD5.new(b'Python')
print(hash_md5.hexdigest()) # MD5

hash_md5 = MD5.new(b'Py')
hash_md5.update(b'thon') # update関数を使うと文字列の連結が可能
print(hash_md5.hexdigest()) 

hash_sha512 = SHA512.new()
hash_sha512.update(b'Python')
print(hash_sha512.hexdigest()) # SHA512

RSA

from Crypto.PublicKey import RSA

# 鍵ペアの作成
rsa = RSA.generate(2048)

# 秘密鍵の作成
private_pem = rsa.exportKey(format='PEM', passphrase='password')
with open("private.pem", 'wb') as f:
    f.write(private_pem)

# 公開鍵の作成
public_pem = rsa.publickey().exportKey()
with open('public.pem',"wb") as f:
    f.write(public_pem)

# 鍵を保存したファイルの読み込み
public_key_file = open('public.pem',"r")
private_key_file = open('private.pem',"r")

# 鍵の読み込み
public_key = RSA.importKey(public_key_file.read())
private_key = RSA.importKey(private_key_file.read(),passphrase='password')

# 暗号化
text = 'Python'
print(text)
import random
encrypted = public_key.encrypt(text.encode('utf8'),random.random)
print(encrypted)

# 復号
decrypted = private_key.decrypt(encrypted)
print(decrypted.decode('utf8'))

正規表現

import re
print(re.match('a.c','abc'))
print(re.match('b','abc')) # match は先頭から見ていくのでヒットしない
print(re.search('a.c','abc'))
print(re.search('b','abc'))

regex = re.compile('[a-n]+') # 正規表現オブジェクトの生成
print(regex.search("Python"))
regex2 = re.compile('[-+()]')
print(regex2.split("090-1234-5678")) # 一致したところで分割
print(regex2.sub("","+81-80-1234-5678")) # 一致したところを置き換える

# 一致したものの取り出し
regex3 = re.compile('(\d+)-(\d+)-(\d+)')
m = regex3.match("090-1234-5678")
print(m.group())

参考文献

Python ライブラリ厳選レシピ

Python ライブラリ厳選レシピ