简体   繁体   English

读取 HTTP 标头 Python

[英]Reading HTTP Header Python

I've written a very basic web server in python that can take in requests and spew data back to the client.我已经用 python 编写了一个非常基本的 Web 服务器,它可以接收请求并将数据发送回客户端。 But my issue is reading the HTTP request, is there a library in python for easily breaking down the HTTP header?但是我的问题是读取 HTTP 请求,python 中是否有可以轻松分解 HTTP 标头的库? Because I'd rather not use my clunky code just for retrieving the GET data.因为我宁愿不使用笨重的代码来检索 GET 数据。

You can use Requests module to get all the details from HTTP request, here is a small example below from the documentation您可以使用 Requests 模块从 HTTP 请求中获取所有详细信息,下面是文档中的一个小示例

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

Here's how you get just the response headers using the requests library (implementation in Python3):以下是使用 requests 库(在 Python3 中实现)获取响应标头的方法:

import requests

url = "https://www.google.com"
response = requests.head(url)
print(response.headers) # prints the entire header as a dictionary
print(response.headers["Content-Length"]) # prints a specific section of the dictionary

It's important to use .head() instead of .get() otherwise you will retrieve the whole file/page.使用 .head() 而不是 .get() 很重要,否则您将检索整个文件/页面。

If you wish to retrieve a URL that requires authentication you can replace the above response with this:如果您希望检索需要身份验证的 URL,您可以将上述response替换为:

response = requests.head(url, auth=requests.auth.HTTPBasicAuth(username, password))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM