请求Flask接口报AttributeError:'str'对象无'get'属性
AttributeError: 'str' object has no attribute 'get' Issue Let's break down what's causing this error and how to fix it step by step.
The Root Cause
You're getting this error because you're passing a pre-serialized JSON string to the json parameter of requests.post(). The json parameter expects a Python dictionary, not a string. When you pass the string, your API receives it as a JSON string value (not an object), so request.json becomes a string instead of a dictionary. Strings don't have a .get() method, hence the error.
Step-by-Step Fixes
1. Update powershell.py
Remove the json.dumps() call and keep the dataPw dictionary as a native Python object (we'll let requests handle the JSON serialization):
import subprocess import sys import json from flask import Flask, json processDefender = subprocess.Popen(["powershell", "get-process | Select-string lsass"], stdout=subprocess.PIPE, shell=False) resultDef = processDefender.communicate()[0].decode('utf-8').strip() dataPw = {} dataPw['Defender'] = resultDef # Optional: Print JSON for debugging, but don't assign to a string variable print(json.dumps(dataPw, sort_keys=True, indent=4))
2. Fix run.py
Use the dataPw dictionary directly in the requests.post() call instead of the string dataFn:
import os import json import requests import subprocess from powershell import * from DetectOS import * # Pass the Python dict to the json parameter r = requests.post('http://127.0.0.1:5000/connection', json=dataPw, headers={'Content-type': 'application/json', 'Accept': 'text/plain'})
Why This Works
When you pass a Python dictionary to the json parameter, requests automatically serializes it to valid JSON and sets the correct headers. Your API endpoint will then receive a JSON object, so request.json will be a Python dictionary—allowing you to use .get() or any other dictionary methods without errors.
Side Note (Optional Process Query Improvement)
Your PowerShell command uses Select-string lsass to search for the string "lsass" in process output. If you want to directly retrieve the lsass process details, use this command instead:
get-process lsass
This will return the actual process object rather than searching for the string in output lines.
内容的提问来源于stack exchange,提问作者Ricardo Pinto




