在使用 python requests 库时,我使用 get 和 head http 方法得到了两种不同的响应 -
使用“head”输入:
requests.head("http://stackoverflow.com")
Run Code Online (Sandbox Code Playgroud)
输出:
<Response [301]>
Run Code Online (Sandbox Code Playgroud)
使用“get”输入时:
requests.get("http://stackoverflow.com")
Run Code Online (Sandbox Code Playgroud)
输出是:
<Response [200]>
Run Code Online (Sandbox Code Playgroud)
虽然很明显“ http://stackoverflow.com ”重定向到“ https://stackoverflow.com ”(作为requests.head("https://stackoverflow.com")返回<Response [200]>),这解释了第一个实例中的 301 响应,但为什么它没有给出相同的结果“get”方法的响应?
get 和 head 如何以不同的方式工作以产生这两个不同的结果?
我阅读了 w3.org 文档和 stackoverflow 中的类似问题(例如,HEAD 请求收到“403禁止”而 GET“200 ok”?)和其他网站,但他们没有解决这个特殊的差异。
在尝试 Python 交互式帮助时,我注意到在尝试查看 python 解释器中所有可用模块的列表时,我们需要在“模块”周围使用引号。
Microsoft Windows [Version 10.0.17763.195]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\amber>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help('modules')
Run Code Online (Sandbox Code Playgroud)
但是,在尝试阅读对象的帮助时,我们不需要使用引号;而是需要使用引号。例如-
>>> help(tuple)
Run Code Online (Sandbox Code Playgroud)
为什么会有这样的差异呢?
我试图通过重复谷歌搜索以及搜索 Stack Overflow 来找到答案,但最接近的问题是返回一些错误或不解决引用问题,而其他网站上的问题没有任何答案。
运行以下代码将引发 io.UnsupportedOperation 错误,因为文件以“写入”模式打开 -
with open("hi.txt", "w") as f:
print(f.read())
Run Code Online (Sandbox Code Playgroud)
输出是 -
io.UnsupportedOperation: not readable
Run Code Online (Sandbox Code Playgroud)
所以,我们可以尝试通过这样做来掩盖这一点——
try:
with open("hi.txt", "w") as f:
print(f.read())
except io.UnsupportedOperation:
print("Please give the file read permission")
Run Code Online (Sandbox Code Playgroud)
输出 -
NameError: name 'io' is not defined
Run Code Online (Sandbox Code Playgroud)
甚至删除“io”。吐出同样的错误 -
try:
with open("hi.txt", "w") as f:
print(f.read())
except UnsupportedOperation:
print("Please give the file read permission")
Run Code Online (Sandbox Code Playgroud)
输出 -
NameError: name 'UnsupportedOperation' is not defined
Run Code Online (Sandbox Code Playgroud)
为什么它不起作用?“io.UnsupportedOperation”不是错误吗?