How are POST and GET variables handled in Python?

前端 未结 6 660
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 11:59

In PHP you can just use $_POST for POST and $_GET for GET (Query string) variables. What\'s the equivalent in Python?

6条回答
  •  星月不相逢
    2020-11-22 12:16

    I know this is an old question. Yet it's surprising that no good answer was given.

    First of all the question is completely valid without mentioning the framework. The CONTEXT is a PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveniently populated. In PHP, $_GET and $_POST are also convenience variables. They are parsed from QUERY_URI and php://input respectively.

    In Python, these functions would be os.getenv('QUERY_STRING') and sys.stdin.read(). Remember to import os and sys modules.

    We have to be careful with the word "CGI" here, especially when talking about two languages and their commonalities when interfacing with a web server. 1. CGI, as a protocol, defines the data transport mechanism in the HTTP protocol. 2. Python can be configured to run as a CGI-script in Apache. 3. The CGI module in Python offers some convenience functions.

    Since the HTTP protocol is language-independent, and that Apache's CGI extension is also language-independent, getting the GET and POST parameters should bear only syntax differences across languages.

    Here's the Python routine to populate a GET dictionary:

    GET={}
    args=os.getenv("QUERY_STRING").split('&')
    
    for arg in args: 
        t=arg.split('=')
        if len(t)>1: k,v=arg.split('='); GET[k]=v
    

    and for POST:

    POST={}
    args=sys.stdin.read().split('&')
    
    for arg in args: 
        t=arg.split('=')
        if len(t)>1: k, v=arg.split('='); POST[k]=v
    

    You can now access the fields as following:

    print GET.get('user_id')
    print POST.get('user_name')
    

    I must also point out that the CGI module doesn't work well. Consider this HTTP request:

    POST / test.py?user_id=6
    
    user_name=Bob&age=30
    

    Using CGI.FieldStorage().getvalue('user_id') will cause a null pointer exception because the module blindly checks the POST data, ignoring the fact that a POST request can carry GET parameters too.

提交回复
热议问题