python requests - ryhara/Webserv GitHub Wiki

python requests

実行方法

python3 test.py

GET

使用例

import requests

url = 'http://localhost:4242'

response = requests.get(url)
print("Status Code ", response.status_code)
print("Response Headers ", response.headers)
print(response.text)

クエリパラメータを指定したい時

https://www.google.com/?gl=us&hl=en&gws_rd=cr&pws=0
# 上記の場合、 gl=us&hl=en&gws_rd=cr&pws=0 がパラメータ部分
url = 'https://www.google.co.jp/'
params = {'q': 'Python',
          'oe': 'utf-8'}
response = requests.get(url, params=params)

POST

使用例

url = 'https://www.google.co.jp/'
data = {'key1': 'value1'}
response = requests.post(url, data=data)

file転送したい時

url = 'https://www.google.co.jp/'
# 画像ファイルの場合
img_data = open('image.jpg', 'rb')
files = {'file': img_data}
response = requests.post(url, files=files)

中身を転送したい時

with open('hoge.dummy', 'rb') as f:
	file_data = f.read()
response = requests.post(url, data=file_data)

headerを使用したい時

import requests

url = 'http://localhost:4242'
headers = {'Transfer-Encoding': 'chunked'}
data = {'key1': 'value1'}
response = requests.post(url, headers=headers, data=data)
print(response.text)

chunkedのテスト例

  • yieldとは yieldを使うと1つずつdataを作成して、次に進むまで一度止めてくれるので、結果的にchunkedを再現できていると考えられる。

yield 式は ジェネレータ 関数や 非同期ジェネレータ 関数を定義するときに使われます。従って、関数定義の本体でのみ使えます。 関数の本体で yield 式 を使用するとその関数はジェネレータ関数になり、 async def 関数の本体で使用するとそのコルーチン関数は非同期ジェネレータ関数になります。

import requests

url = 'http://localhost:4242'
headers = {'Transfer-Encoding': 'chunked'}

def generate_data():
    # ここでチャンクデータを生成します
    yield 'hello'
    yield 'world'

response = requests.post(url, headers=headers, data=generate_data())
print(response.text)

DELETE

url = 'http://localhost:4242/delete.html'
response = requests.delete(url)

出力

# request
print("--------------------")
print("URL:", response.request.url)
print("Method:", response.request.method)
print("Headers:")
for key, value in response.request.headers.items():
	print(key, ":", value)
print("Body:", response.request.body)
print("--------------------")
# response
print("Status Code:", response.status_code)
print("Headers:")
for key, value in response.headers.items():
	print(key, ":", value)
print(response.text)