LoginSignup
0
0

More than 1 year has passed since last update.

CURLのHeaderやBody(JSON)を指定文字で置換する

Posted at

概要

pthon勉強中です。
curlのテキストを読み込み、header、bodyの任意項目を置換して出力します。

import pathlib
import re
import json


curl_path = pathlib.Path('.\\curl.txt')
output_curl_path = pathlib.Path('.\\curl_new.txt')


# 正規表現
BODY_PATTERN = r"-d \'([^*]*?)\'"
ID = "id"
HEADER_PATTERN = r"-H \'" + ID + ": ([^*]*?)\'"

# ファイルを読み込む
with open(curl_path, 'r', encoding="utf-8") as f:
    with open(output_curl_path, 'w', encoding="utf-8") as w:
        data = f.read()

        # Headerを取得
        replace_header_pattern = re.compile(HEADER_PATTERN)
        id = "2"
        new_data = replace_header_pattern.sub(r"-H '" +  ID + ": " + id + "'", data)
        print(new_data)

        # Bodyを取得
        r_body = re.findall(BODY_PATTERN, new_data)

        # JSONを変更
        body = json.loads((r_body[0]).encode())
        body['review_user_id'] = 3
        print(json.dumps(body, ensure_ascii=False))

        # 置換したBodyを出力
        replace_pattern = re.compile(BODY_PATTERN)
        new_data = replace_pattern.sub(r'-d \'' + json.dumps(body, ensure_ascii=False, indent=2, skipkeys=True) + '\'', new_data)

        w.write(new_data)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0