python脚本调用对应btcoin-cli 接口

#!/usr/bin/python3

from flask import Flask, request, jsonify
import subprocess
import re
import logging

app = Flask(__name__)

class BitcoinWallet:
    def __init__(self, bitcoin_cli_cmd):
        self.bitcoin_cli_cmd = bitcoin_cli_cmd

    def run_command(self, command):
        try:
            result = subprocess.run(command, capture_output=True, text=True)

            if result.returncode != 0:
                match = re.search(r'error:.*', result.stderr, re.IGNORECASE)
                processed_error_message = match.group(0) if match else "Unknown error"
                logging.error("Error in command execution: %s", result.stderr)
                response = jsonify({"error": processed_error_message, "normal_output": result.stdout.strip()})
                response.status_code = 500
                return response

            logging.info("Normal output in command execution: %s", result.stdout)
            return result.stdout.strip()

        except Exception as e:
            logging.error("Error in command execution: %s", str(e))
            return str(e), 500

    def execute_wallet_method(self, wallet_method_params):
        command = self.bitcoin_cli_cmd + wallet_method_params
        return self.run_command(command)

@app.route('/wallet', methods=['POST'])
def wallet_receive():
    try:
        wallet_method_params = request.json['wallet_method_params']
        return bitcoin_wallet.execute_wallet_method(wallet_method_params)
    except Exception as e:
        return str(e), 400

if __name__ == '__main__':
    bitcoin_cli_cmd=["/data/btc/bin/bitcoin-cli", "-regtest", "--conf=/data/btc/conf/bitcoin.conf", "-rpcwallet=btcregtest"]
    bitcoin_wallet = BitcoinWallet(bitcoin_cli_cmd)
    app.run(debug=False, host="0.0.0.0", port=5001)

调用方式:
调用地址:http://192.168.25.128:5001/wallet
调用参数:

{
    "wallet_method_params": ["getrawchangeaddress", "bech32m"]
}

python脚本调用对应btcoin-cli 接口_第1张图片
调用参数:

{
    "wallet_method_params": ["listwallets"]
}

python脚本调用对应btcoin-cli 接口_第2张图片
调用参数

{
    "wallet_method_params": ["listaddressgroupings"]
}

python脚本调用对应btcoin-cli 接口_第3张图片
调用参数

{
    "wallet_method_params": ["getrawchangeaddress"]
}

python脚本调用对应btcoin-cli 接口_第4张图片
调用参数

{
    "wallet_method_params": ["listlockunspent"]
}

python脚本调用对应btcoin-cli 接口_第5张图片
调用参数

{
    "wallet_method_params": ["getbalances"]
}

python脚本调用对应btcoin-cli 接口_第6张图片

你可能感兴趣的:(ordinals,python,python,ordinals)