<p>如果动态填充,PyCharm不知道<code>dict</code>包含什么。所以你必须事先提示PyCharm关于<code>dict</code>的键。<a href="https://github.com/ramazanpolat/prodict" rel="nofollow noreferrer">Prodict</a>这样做正是为了提示PyCharm,这样就可以完成代码。</p>
<p>首先,如果希望能够访问response对象,则必须获取json响应并将其转换为<code>dict</code>。这是通过<code>.json()</code>方法实现的,就像这样:</p>
<pre><code>response = requests.get("https://some.restservice.com/user/1").json()
</code></pre>
<p>好的,我们将其加载到一个<code>dict</code>对象,现在您可以使用括号语法访问键:</p>
<pre><code>print(response['name'])
</code></pre>
<p>既然您要求自动完成代码,那么肯定需要提示PyCharm关于<code>dict</code>的键。如果您已经知道respone模式,可以使用Prodict提示PyCharm:</p>
<pre><code>class Response(Prodict):
name: str
price: float
response_dict = requests.get("https://some.restservice.com/user/1").json()
response = Response.from_dict(response_dict)
print(response.name)
print(response.price)
</code></pre>
<p>在上面的代码中,<code>name</code>和<code>price</code>属性都是自动编译的。</p>
<p>如果您不知道响应的模式,那么您仍然可以使用点表示法来访问像这样的<code>dict</code>属性:</p>
<pre><code>response_dict = requests.get("https://some.restservice.com/user/1").json()
response = Prodict.from_dict(response_dict)
print(response.name)
</code></pre>
<p>但是代码完成将不可用,因为PyCharm不知道模式是什么。</p>
<p>更重要的是,Prodict类直接从<code>dict</code>派生,因此您也可以将其用作<code>dict</code>。</p>
<p>这是Prodict repo的屏幕截图,显示了代码完成:</p>
<p><a href="https://raw.githubusercontent.com/ramazanpolat/prodict/master/auto-complete1.png" rel="nofollow noreferrer"><img src="https://raw.githubusercontent.com/ramazanpolat/prodict/master/auto-complete1.png" alt="Prodict code completion"/></a></p>
<p><strong>免责声明</strong>:我是Prodict的作者。</p>