How to check contents of incoming HTTP header request

那年仲夏 提交于 2019-12-06 08:09:55

问题


I'm playing around with some APIs and I'm trying to figure this out.

I am making a basic HTTP authenticated request to my server via the API. As part of this request, the authenticated key is stored in the HTTP header as username.

So my question is, how do I get the contents of the incoming request such that I can perform a check against it?

What I am trying to do:

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

For those interested, I am trying to get this to work.

UPDATE I am using Django


回答1:


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.

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

So:

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



回答2:


The headers are stored in os.environ. So you can access the HTTP headers like this:

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


来源:https://stackoverflow.com/questions/5414687/how-to-check-contents-of-incoming-http-header-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!