如何检查传入HTTP头请求的内容

3 投票
2 回答
10358 浏览
提问于 2025-04-16 14:18

我正在玩一些API,想弄明白一些事情。

我通过API向我的服务器发送一个基本的HTTP认证请求。在这个请求中,认证密钥被存储在HTTP头部,作为用户名。

所以我想问的是,如何获取到这个请求的内容,以便我可以进行检查?

我想做的事情是:

if incoming request has header == 'myheader':
    do some stuff
else:
    return ('not authorised')

对那些感兴趣的人,我正在尝试让这个工作。

更新 我正在使用Django。

2 个回答

2

这些头信息是存储在 os.environ 里的。所以你可以这样来获取HTTP头信息:

import os
if os.environ.haskey("SOME_HEADER"):
  # do something with the header, i.e. os.environ["SOME_HEADER"]
6

http://docs.djangoproject.com/en/dev/ref/request-response/

HttpRequest.META

A standard Python dictionary containing all available HTTP headers. 
Available headers depend on the client and server, but here are some examples:

        CONTENT_LENGTH
        CONTENT_TYPE
        HTTP_ACCEPT_ENCODING
        HTTP_ACCEPT_LANGUAGE
        HTTP_HOST -- The HTTP Host header sent by the client.
        HTTP_REFERER -- The referring page, if any.
        HTTP_USER_AGENT -- The client's user-agent string.
        QUERY_STRING -- The query string, as a single (unparsed) string.
        REMOTE_ADDR -- The IP address of the client.
        REMOTE_HOST -- The hostname of the client.
        REMOTE_USER -- The user authenticated by the Web server, if any.
        REQUEST_METHOD -- A string such as "GET" or "POST".
        SERVER_NAME -- The hostname of the server.
        SERVER_PORT -- The port of the server.

除了 CONTENT_LENGTH 和 CONTENT_TYPE 这两个例外,其他所有的 HTTP 请求头都会被转换成 META 键。转换的规则是:把所有字母变成大写,把中间的连字符(-)换成下划线(_),并在名字前面加上 HTTP_ 前缀。举个例子,一个叫 X-Bender 的请求头会被转换成 META 键 HTTP_X_BENDER。

所以:

if request.META['HTTP_USERNAME']:
    blah
else:
    blah

撰写回答