'urllib2.urlopen'添加主机标头

时间:2013-06-19 22:19:11

标签: python

我正在使用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中添加带有'urllib2.urlopen'的Host头(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]

1 个答案:

答案 0 :(得分:7)

您可能需要查看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