Python中的标头检查(GAE)

时间:2013-01-13 17:13:42

标签: python security google-app-engine

我想知道如何检查HTTP标头以确定请求是有效还是格式错误。我怎样才能在Python中执行此操作,更具体地说,我如何在GAE中执行此操作?

1 个答案:

答案 0 :(得分:2)

对于一些调试和使用标题查看请求,我使用以下DDTHandler类。

import cgi
import wsgiref.handlers
import webapp2

class DDTHandler(webapp2.RequestHandler):

    def __start_display(self):
        self.response.out.write("<!--\n")

    def __end_display(self):
        self.response.out.write("-->\n")

    def __show_dictionary_items(self,dictionary,title):
        if (len(dictionary) > 0):
            request = self.request
            out = self.response.out
            out.write("\n" + title + ":\n")
            for key, value in dictionary.iteritems():
                out.write(key + " = " + value + "\n")

    def __show_request_members(self):
        request = self.request
        out = self.response.out
        out.write(request.url+"\n")
        out.write("Query = "+request.query_string+"\n")
        out.write("Remote = "+request.remote_addr+"\n")
        out.write("Path = "+request.path+"\n\n")
        out.write("Request payload:\n")
        if (len(request.arguments()) > 0): 
            for argument in request.arguments():
                value = cgi.escape(request.get(argument))
                out.write(argument+" = "+value+"\n")
        else:
            out.write("Empty\n")

        self.__show_dictionary_items(request.headers, "Headers")
        self.__show_dictionary_items(request.cookies, "Cookies")

    def view_request(self):
        self.__start_display()
        self.__show_request_members()
        self.__end_display()

    def view(self, aString):
        self.__start_display()
        self.response.out.write(aString+"\n")
        self.__end_display()

示例:

class RootPage(DDTHandler):

    def get(self):      
        self.view_request()

将输出请求,包含标题

请检查代码并获取所需内容。如上所述,一个格式错误的“无效”请求可​​能无法点击您的应用。

<!--
http://localhost:8081/
Query = 
Remote = 127.0.0.1
Path = /

Request payload:
Empty

Headers:
Referer = http://localhost:8081/_ah/login?continue=http%3A//localhost%3A8081/
Accept-Charset = ISO-8859-7,utf-8;q=0.7,*;q=0.3
Cookie = hl=en_US; dev_appserver_login="test@example.com:False:185804764220139124118"
User-Agent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Host = localhost:8081
Accept = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language = en-US,en;q=0.8,el;q=0.6

Cookies:
dev_appserver_login = test@example.com:False:185804764220139124118
hl = en_US
-->