如何在JSON-RPC调用脚本执行后打印POST请求状态码?
Fixing the Missing Status Code Printout in Your Script
Hey there! I see your script can complete the task but isn't printing the request status code—let's get that sorted out quickly. The main issue here is that your current code defines all the necessary parameters, but it doesn't actually send the HTTP request or access the status code from the response.
Here's the updated version of your script with the missing pieces added, plus some error handling to make it more robust:
import requests import json url = 'http://10.3.198.100/ins' switchuser = 'user' switchpassword = 'password' myheaders = {'content-type' : 'application/json-rpc'} payload = [ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "vrf context management", "version": 1 }, "id": 1 }, # Add your remaining payload objects here { "jsonrpc": "2.0", # Your other method/parameter details go here } ] try: # Send the POST request with authentication and JSON payload response = requests.post( url, data=json.dumps(payload), headers=myheaders, auth=(switchuser, switchpassword) ) # Print the HTTP status code print(f"Request Status Code: {response.status_code}") # Optional: Uncomment below to see the full response content # print("Full Response:", json.dumps(response.json(), indent=2)) except requests.exceptions.RequestException as e: # Catch and print any request errors (connection issues, timeouts, etc.) print(f"Request failed with error: {e}")
Key Changes Explained:
- Sending the Request: The
requests.post()call is the missing piece—it sends your payload to the device's API endpoint, using the authentication credentials you defined. We usejson.dumps(payload)to convert your Python list into a JSON string, which matches theapplication/json-rpccontent type in your headers. - Accessing the Status Code:
response.status_codegives you the HTTP status code directly. Common codes you might see:200: Request succeeded401: Authentication failed (check your username/password)500: Server-side error on the network device
- Error Handling: The
try-exceptblock catches common request issues (like failed connections or timeouts) so your script doesn't crash unexpectedly, and gives you a clear error message.
Just fill in the rest of your payload objects, run the script, and you'll see the status code printed out every time!
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

