2

我正在使用 Observium 在 localhost 上提取 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(Python 2.6.6)中使用“urllib2.urlopen”添加主机标头:

当前脚本:

#!/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]
4

1 回答 1

7

您可能想查看urllib2 缺失手册以获取更多信息,但基本上您创建标题标签和值的字典并将其传递给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
于 2013-06-19T22:24:02.640 回答