Reading a client's header from Python CGI script?

前端 未结 4 2143
我在风中等你
我在风中等你 2021-02-12 20:21

I\'m writing a very simple web service, written in Python and run as CGI on an Apache server.

According to Python docs (somewhere... I forgot where), I can use sys.stdin

4条回答
  •  一整个雨季
    2021-02-12 20:34

    This is how I capture in Python 3 from CGI (A) URL, (B) GET parameters and (C) POST data:

    =======================================================

    import sys, os, io

    CAPTURE URL

    myDomainSelf = os.environ.get('SERVER_NAME')

    myPathSelf = os.environ.get('PATH_INFO')

    myURLSelf = myDomainSelf + myPathSelf

    CAPTURE GET DATA

    myQuerySelf = os.environ.get('QUERY_STRING')

    CAPTURE POST DATA

    myTotalBytesStr=(os.environ.get('HTTP_CONTENT_LENGTH'))

    if (myTotalBytesStr == None):

    myJSONStr = '{"error": {"value": true, "message": "No (post) data received"}}'
    

    else:

    myTotalBytes=int(os.environ.get('HTTP_CONTENT_LENGTH'))
    
    myPostDataRaw = io.open(sys.stdin.fileno(),"rb").read(myTotalBytes)
    
    myPostData = myPostDataRaw.decode("utf-8")
    

    Write RAW to FILE

    mySpy = "myURLSelf: [" + str(myURLSelf) + "]\n"

    mySpy = mySpy + "myQuerySelf: [" + str(myQuerySelf) + "]\n"

    mySpy = mySpy + "myPostData: [" + str(myPostData) + "]\n"

    You need to define your own myPath here

    myFilename = "spy.txt"

    myFilePath = myPath + "\" + myFilename

    myFile = open(myFilePath, "w")

    myFile.write(mySpy)

    myFile.close()

    =======================================================

    Here are some other useful CGI environment vars:

    AUTH_TYPE

    CONTENT_LENGTH

    CONTENT_TYPE

    GATEWAY_INTERFACE

    PATH_INFO

    PATH_TRANSLATED

    QUERY_STRING

    REMOTE_ADDR

    REMOTE_HOST

    REMOTE_IDENT

    REMOTE_USER

    REQUEST_METHOD

    SCRIPT_NAME

    SERVER_NAME

    SERVER_PORT

    SERVER_PROTOCOL

    SERVER_SOFTWARE

    =================================

    I am using this methods on Windows Server with MIIS and Python 3 in CGI mode.

提交回复
热议问题