How are POST and GET variables handled in Python?
suppose you're posting a html form with this:
<input type="text" name="username">
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.
How to use variable's value as HTTP POST parameter?
You can use an f-string (as long as you are using Python 3.7+).
url1 = "https://example.com/api/req"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
Variable_1 = "Direction"
data = f"""
{{
"type": "{Variable_1}",
"station": "Dept",
"status": "check",
"values": {{
"Par1": "5",
"Par2" : "2",
"Par3": "3",
"Par4": "1",
"Par5": "4"
}}
}}
"""
resp1 = requests.post(url1, headers=headers, data=data)
How to Get All POST Variables In A Request
If you need names of data sends by POST
then you have to first GET
this page and find all <input>
, <button>
, <text>
in <form>
For example - login page on facebook.com
import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.facebook.com/')
soup = BeautifulSoup(r.content, 'lxml')
for x in soup.find_all('form'):
for i in x.find_all(['input', 'button', 'text']):
print(i.name, i.get('name'))
print('---')
result:
input lsd
input email
input pass
input None
input persistent
input default_persistent
input timezone
input lgndim
input lgnrnd
input lgnjs
input ab_test_data
input locale
input next
---
input lsd
input firstname
input lastname
input reg_email__
input reg_email_confirmation__
input reg_passwd__
input sex
input sex
button websubmit
input referrer
input asked_to_login
input terms
input ab_test_data
input contactpoint_label
input locale
input reg_instance
input captcha_persist_data
input captcha_session
input extra_challenge_params
input recaptcha_type
input captcha_response
button None
---
As you see there are many input
s so sometimes it is better to use browser
manually and see what "names" are send from browser to server :)
Handling GET and POST in same Flask view
You can distinguish between the actual method using request.method
.
I assume that you want to:
- Render a template when the route is triggered with
GET
method - Read form inputs and register a user if route is triggered with
POST
So your case is similar to the one described in the docs: Flask Quickstart - HTTP Methods
import flask
app = flask.Flask('your_flask_env')
@app.route('/register', methods=['GET', 'POST'])
def register():
if flask.request.method == 'POST':
username = flask.request.values.get('user') # Your form's
password = flask.request.values.get('pass') # input names
your_register_routine(username, password)
else:
# You probably don't have args at this route with GET
# method, but if you do, you can access them like so:
yourarg = flask.request.args.get('argname')
your_register_template_rendering(yourarg)
can I get the POST data from environment variables in python?
the possible duplicate link solved it, as syntonym pointed out in the comments and user Schien explains in one of the answers to the linked question:
the raw http post data (the stuff after the query) can be read through stdin.
so the sys.stdin.read()
method can be used.
my code now works looking like this:
#!/usr/bin/python3
import sys
import os
f = open('test','w')
f.write(str(sys.stdin.read()))
f.close()
Accessing $_GET and $_POST query string or form value equivalents in Python
All the web frameworks do it differently. As you say, Python is not a templating language, so there is no automatic way to handle HTTP requests.
There is a cgi
module which is part of the standard library, and which you can use to access POSTed data via cgi.FieldStorage()
- but serving an app via standard CGI is horribly inefficient and only suitable for very small-scale stuff.
A much better idea is to use a simple WSGI framework (WSGI is the standard for serving web applications with Python). There are quite a few - my current favourite is flask although I hear good things about bottle too.
Get the data received in a Flask request
The docs describe the attributes available on the request
object (from flask import request
) during a request. In most common cases request.data
will be empty because it's used as a fallback:
request.data
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.
request.args
: the key/value pairs in the URL query stringrequest.form
: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encodedrequest.files
: the files in the body, which Flask keeps separate fromform
. HTML forms must useenctype=multipart/form-data
or files will not be uploaded.request.values
: combinedargs
andform
, preferringargs
if keys overlaprequest.json
: parsed JSON data. The request must have theapplication/json
content type, or userequest.get_json(force=True)
to ignore the content type.
All of these are MultiDict
instances (except for json
). You can access values using:
request.form['name']
: use indexing if you know the key existsrequest.form.get('name')
: useget
if the key might not existrequest.form.getlist('name')
: usegetlist
if the key is sent multiple times and you want a list of values.get
only returns the first value.
Related Topics
Why Python 3.6.1 Throws Attributeerror: Module 'Enum' Has No Attribute 'Intflag'
Plot a Horizontal Line on a Given Plot
How to Get the Logical Xor of Two Variables in Python
How to Get the Original Variable Name of Variable Passed to a Function
Saving and Loading Multiple Objects in Pickle File
Error Unicodedecodeerror: 'Utf-8' Codec Can't Decode Byte 0Xff in Position 0: Invalid Start Byte
Convert Python Sequence to Numpy Array, Filling Missing Values
Numpy Where Function Multiple Conditions
Django Urls Typeerror: View Must Be a Callable or a List/Tuple in the Case of Include()
Comparing Two Lists Using the Greater Than or Less Than Operator
How to Reset Index in a Pandas Dataframe
How to Get Attribute of Element from Selenium
How to Fix Overlapping Annotations/Text
Check If Something Is (Not) in a List in Python
Calling a Python Script with Input Within a Python Script Using Subprocess