gpt4 book ai didi

python - 'urllib2.urlopen' 添加主机 header

转载 作者:行者123 更新时间:2023-11-28 20:48:18 26 4
gpt4 key购买 nike

我正在使用 Observium 在本地主机上提取 Nginx 统计信息,但它返回“405 Not Allowed”:

# curl -I localhost/nginx_status
HTTP/1.1 405 Not Allowed
Server: nginx
Date: Wed, 19 Jun 2013 22:12:37 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 166
Connection: keep-alive
Keep-Alive: timeout=5

# curl -I -H "Host: example.com" localhost/nginx_status
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 19 Jun 2013 22:12:43 GMT
Content-Type: text/plain
Connection: keep-alive
Keep-Alive: timeout=5

能否请您告知如何在 Python 中使用“urllib2.urlopen”添加主机 header (Python 2.6.6):

当前脚本:

#!/usr/bin/env python
import urllib2
import re


data = urllib2.urlopen('http://localhost/nginx_status').read()

params = {}

for line in data.split("\n"):
smallstat = re.match(r"\s?Reading:\s(.*)\sWriting:\s(.*)\sWaiting:\s(.*)$", line)
req = re.match(r"\s+(\d+)\s+(\d+)\s+(\d+)", line)
if smallstat:
params["Reading"] = smallstat.group(1)
params["Writing"] = smallstat.group(2)
params["Waiting"] = smallstat.group(3)
elif req:
params["Requests"] = req.group(3)
else:
pass


dataorder = [
"Active",
"Reading",
"Writing",
"Waiting",
"Requests"
]

print "<<<nginx>>>\n";

for param in dataorder:
if param == "Active":
Active = int(params["Reading"]) + int(params["Writing"]) + int(params["Waiting"])
print Active
else:
print params[param]

最佳答案

您可能想查看 urllib2 missing manual了解更多信息,但基本上您创建一个标题标签和值的字典并将其传递给 urllib2.Request 方法。链接手册中代码的(略微)修改版本:

from urllib import urlencode
from urllib2 import Request urlopen

# Define values that we'll pass to our urllib and urllib2 methods
url = 'http://www.something.com/blah'
user_host = 'example.com'
values = {'name' : 'Engineero', # dict of keys and values for our POST data
'location' : 'Interwebs',
'language' : 'Python' }
headers = { 'Host' : user_host } # dict of keys and values for our header

# Set up our request, execute, and read
data = urlencode(values) # encode for sending URL request
req = Request(url, data, headers) # make POST request to url with data and headers
response = urlopen(req) # get the response from the server
the_page = response.read() # read the response from the server

# Do other stuff with the response

关于python - 'urllib2.urlopen' 添加主机 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17202364/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com