【问题标题】:How to check contents of incoming HTTP header request如何检查传入的 HTTP 标头请求的内容
【发布时间】:2011-07-21 20:15:12
【问题描述】:

我正在使用一些 API,我正在尝试解决这个问题。

我正在通过 API 向我的服务器发出基本的 HTTP 身份验证请求。作为此请求的一部分,经过身份验证的密钥作为用户名存储在 HTTP 标头中。

所以我的问题是,如何获取传入请求的内容以便我可以对其进行检查?

我想做什么:

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

对于那些感兴趣的人,我正在努力让this 工作。

更新 我正在使用 Django

【问题讨论】:

  • 您使用的是哪个 Web 框架?他们都应该有一个 API 来轻松访问 HTTP 标头键值对。
  • 我正在使用 Django。它是特定于 Web 框架的吗?
  • 试试the docs for Django's Httprequest,特别是HttpRequest.META。这是一个字典,您可以从中访问客户端发送的 HTTP 标头。

标签: python django http-headers basic-authentication


【解决方案1】:

标头存储在os.environ 中。因此,您可以像这样访问 HTTP 标头:

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

【讨论】:

  • 所以我不一定要通过 Django 来做这件事?这两种方法都有优缺点吗?
  • 这真的取决于应用程序,即你想要做什么。做这个服务器端的好处是安全;您通常可以对用户隐藏详细信息,因为 JavaScript 对最终用户几乎是透明的。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2016-01-01
    • 2021-02-25
    相关资源
    最近更新 更多