How are POST and GET variables handled in Python?

前端 未结 6 615
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    suppose you're posting a html form with this:

    
    

    If using raw cgi:

    import cgi
    form = cgi.FieldStorage()
    print form["username"]
    

    If using Django, Pylons, Flask or Pyramid:

    print request.GET['username'] # for GET form method
    print request.POST['username'] # for POST form method
    

    Using Turbogears, Cherrypy:

    from cherrypy import request
    print request.params['username']
    

    Web.py:

    form = web.input()
    print form.username
    

    Werkzeug:

    print request.form['username']
    

    If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

    def index(self, username):
        print username
    

    Google App Engine:

    class SomeHandler(webapp2.RequestHandler):
        def post(self):
            name = self.request.get('username') # this will get the value from the field named username
            self.response.write(name) # this will write on the document
    

    So you really will have to choose one of those frameworks.

提交回复
热议问题