Python 3 のメモ諸々post

Python 3 を最近ちゃんと触っている。 その途中で知ったこと雑多な諸々をメモ。

開発関係

venv を使おう

Python 3 でプログラム書くときは、 venv を使おう。

v3 から virtualenv と同等の機能として venv が組み込まれているのでそれを使ってパッケージを管理するとGOOD

使い方は

$ python3 -m venv .venv

で実行環境を .venv として作成。 名前は任意の名前だけど、git に登録しないよって意味がわかりやすいように .env としています。

$ source .venv/bin/active
(.venv) $

で PATH などを適用し利用できるようにする。

(.venv) $ deactivate

で、専用の環境を解除。

requirements.txt

requirements.txt でパッケージを管理する場合は requirements.lock を作るといい感じ。

pipでもlockで依存パッケージバージョンを管理しよう を参考にした。

#!/bin/bash
REQUIREMENTS=$1
if [ "" == "$REQUIREMENTS" ]; then
  REQUIREMENTS=requirements.txt
fi
VENV_DIR=.venv_temp_$(date +%s)
python3 -m venv $VENV_DIR
source $VENV_DIR/bin/activate
pip3 install -U pip wheel
pip3 install -r $REQUIREMENTS
(
echo "# auto generated by update-pip-lock.sh"
pip3 freeze
) >| $(basename $REQUIREMENTS .txt).lock
rm -rf $VENV_DIR

こんな感じ。

また、開発時のみに必要なパッケージをインストールするための requirements.dev.txtrequirements.dev.lock も作成。

# common packages
-r requirements.txt
# dev only packages
sphinx

-r FILENAME とすることで別のリストを読み込めるので、それを利用して記述を最小にする。

requests

HTTP/HTTPS クライアントライブラリ requests のメモ

使い方

$ pip install requests
import requests
res = requests.get('https://example.net/hoge/fuga')
print(res.json) # content-type: application/json のみ
print(res.request.url) # 要求した URL
print(res.request.headers) # 要求したヘッダ
print(res.request.body) # 要求したコンテンツ内容
print(res.status_code) # 応答されたステータスコード
print(res.headers) # 応答されたヘッダ
print(res.cookies) # クッキー
print(res.content) # コンテンツ内容(bytes 型)
print(res.text) # コンテンツ内容(str 型)
print(res.history) # リダイレクト処理がされた場合の要求履歴

リダイレクト処理

requests 標準ではリダイレクトは自動で処理される。 が... リダイレクト処理の流れを取得したり、COOKIEの指定を途中でしたい場合はオプションで指定する必要がある。

import requests
res = requests.get("http://google.co.jp/")
print(res.history[0])                     # <Response [301]>
print(res.history[0].url)                 # 'http://google.co.jp/'
print(res.history[0].headers["Location"]) # 'http://www.google.co.jp/'
print(res.history[0].status_code)         # 301
print(res.url)                            # 'http://www.google.co.jp/'
print(res.status_code)                    # 200

allow_redirects オプションでリダイレクトの自動処理を無効にできる。

import requests
res = requests.get("http://google.co.jp/", allow_redirects=False)
print(res.url)                 # 'http://google.co.jp/'
print(res.headers["Location"]) # 'http://www.google.co.jp/'
print(res.status_code)         # 301
res2 = requests.get(res.headers["Location"], allow_redirects=False)
print(res2.url)                            # 'http://www.google.co.jp/'
print(res2.status_code)                    # 200

ログイン処理などを行う場合はセッションを使う、みたいなことを書いてあるところもあるが、クッキーを受け渡すだけで十分処理できそう。

import requests
# Cookieを取得
res = requests.get('http://httpbin.org/cookies/set/foo/bar?domain=mydomain.com&path=%2F&httponly=true&secure=true')
print(res.cookies['foo']) # 'bar'
# Cookieを設定
res2 = requests.get('http://httpbin.org/cookies', cookies=res.cookies)
print(res2.text) # '{"cookies": {"foo": "bar"}}'
# マージしたCookieを設定
res3 = requests.get('http://httpbin.org/cookies/set/hoge/fuga')
print(res3.cookies['hoge']) # 'fuga'
res3.cookies.update(res.cookies)
res4 = requests.get('http://httpbin.org/cookies', cookies=res3.cookies)
print(res4.text) # '{"cookies": {"foo": "bar","hoge": "fuga"}}'

参考


   /   変更履歴  /   Permalink  /  このエントリーをはてなブックマークに追加 
 カテゴリ: ブログ  /   タグ: Python, Python3