You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Bash CURL命令转Python脚本及Python转CURL并保存输出

Hey there! Let's tackle your two tech requirements step by step—first we'll finish that JIRA API Python script you started, then cover how to convert requests code to a curl command and save it to a file.

1. Completing the Python Script for JIRA API Request

Your existing code has the headers and JQL params sorted, so let's fill in the rest with proper authentication, request handling, JSON formatting, and file output (matching what your original bash command does). Here's the full script:

import requests
import json

# Your existing headers and params
headers = {'Content-Type': 'application/json'}
params = (
    ('jql', 'project="Technology" AND summary~"Remove User*" AND issuetype="Task" AND status!="DONE"'),
)

# Authentication credentials (matches your bash command's -u user:Pass)
auth = ('user', 'Pass')
url = 'https://jira.company.com/rest/api/2/search'

try:
    # Send the GET request
    response = requests.get(url, headers=headers, params=params, auth=auth)
    # Raise an error if the request fails (e.g., invalid credentials, 404)
    response.raise_for_status()
    
    # Format JSON output to match `python -m json.tool` behavior
    formatted_json = json.dumps(response.json(), indent=4)
    
    # Save to the specified file path
    with open('/var/lib/rundeck/1.json', 'w') as f:
        f.write(formatted_json)
        
    print("Success! Response saved to /var/lib/rundeck/1.json")

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

Key details about this script:

  • auth=('user', 'Pass') replicates the -u user:Pass flag from your bash command for basic authentication.
  • response.raise_for_status() ensures we catch HTTP errors instead of silently proceeding with a failed response.
  • json.dumps(..., indent=4) pretty-prints the JSON output, just like your original python -m json.tool pipe.
  • The try/except block handles network issues or file write errors gracefully.
2. Converting Python requests Code to CURL Command and Saving to File

You can do this either with a helper library for simplicity, or build the curl command manually if you want to avoid extra dependencies.

Option 1: Use requests-toolbelt (Easiest Method)

The requests-toolbelt library has a built-in utility to convert requests objects to curl commands. First install it:

pip install requests-toolbelt

Then modify your script to generate and save the curl command:

import requests
from requests_toolbelt.utils import dump

headers = {'Content-Type': 'application/json'}
params = (
    ('jql', 'project="Technology" AND summary~"Remove User*" AND issuetype="Task" AND status!="DONE"'),
)
auth = ('user', 'Pass')
url = 'https://jira.company.com/rest/api/2/search'

# Create a prepared request object
request = requests.Request('GET', url, headers=headers, params=params, auth=auth)
prepared_request = request.prepare()

# Convert to curl command string
curl_command = dump.dump_request(prepared_request, request_prefix='curl').decode('utf-8')

# Save to a file
with open('jira_curl_command.txt', 'w') as f:
    f.write(curl_command)

print("CURL command saved to jira_curl_command.txt")

Option 2: Manual CURL Command Construction (No Dependencies)

If you don't want to install an extra library, build the curl command by assembling each component:

import requests

headers = {'Content-Type': 'application/json'}
params = (
    ('jql', 'project="Technology" AND summary~"Remove User*" AND issuetype="Task" AND status!="DONE"'),
)
auth = ('user', 'Pass')
url = 'https://jira.company.com/rest/api/2/search'

# Build curl command parts
curl_parts = ['curl']
# Add authentication
curl_parts.append(f'-u {auth[0]}:{auth[1]}')
# Add method (GET is default, included for clarity)
curl_parts.append('-X GET')
# Add headers
for key, value in headers.items():
    curl_parts.append(f'-H "{key}: {value}"')
# Generate full URL with encoded params
full_url = requests.Request('GET', url, params=params).prepare().url
curl_parts.append(f'"{full_url}"')

# Combine into a single command
curl_command = ' '.join(curl_parts)

# Save to file
with open('jira_curl_command.txt', 'w') as f:
    f.write(curl_command)

print("CURL command saved to jira_curl_command.txt")

This manual method replicates the exact structure of your original bash curl command, including properly encoded JQL parameters.

内容的提问来源于stack exchange,提问作者Milister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:37:18