Accediendo a datos POST desde WSGI
-
22-08-2019 - |
Pregunta
Parece que no puedo entender cómo acceder a los datos POST usando WSGI.Probé el ejemplo en el sitio web wsgi.org y no funcionó.Estoy usando Python 3.0 ahora mismo.No recomiende un marco WSGI ya que eso no es lo que estoy buscando.
Me gustaría descubrir cómo introducirlo en un objeto de almacenamiento de campo.
Solución
Suponiendo que usted está tratando de obtener sólo los datos POST en un objeto FieldStorage:
# env is the environment handed to you by the WSGI server.
# I am removing the query string from the env before passing it to the
# FieldStorage so we only have POST data in there.
post_env = env.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
fp=env['wsgi.input'],
environ=post_env,
keep_blank_values=True
)
Otros consejos
body= '' # b'' for consistency on Python 3.0
try:
length= int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
length= 0
if length!=0:
body= environ['wsgi.input'].read(length)
Tenga en cuenta que WSGI todavía no está especificado completamente para Python 3.0, y gran parte de la infraestructura WSGI popular no ha sido convertida (o se ha 2to3d, pero no probado adecuadamente). (Incluso wsgiref.simple_server no se ejecutará.) Usted se encontrará con un tiempo medio estimado en 3.0 haciendo WSGI hoy.
Esto funcionó para mí (en Python 3.0):
import urllib.parse
post_input = urllib.parse.parse_qs(environ['wsgi.input'].readline().decode(),True)
Aún más corto
l = int(env.get('CONTENT_LENGTH')) if env.get('CONTENT_LENGTH') else 0
body = env['wsgi.input'].read(l) if l > 0 else ''
Este código funciona en producción.
Yo sugeriría nos fijamos en cómo algunos marcos hacen por ejemplo. (No estoy recomendando uno solo, simplemente utilizarlos como un ejemplo.)
Aquí está el código de Werkzeug :
http://dev.pocoo.org/projects /werkzeug/browser/werkzeug/wrappers.py#L150
que llama
http://dev.pocoo.org/projects /werkzeug/browser/werkzeug/utils.py#L1420
Es un poco complicado de resumir aquí, así que no lo haré.