étant donné le serveur HTTP le plus simple, comment puis-je obtenir des variables de publication dans un BaseHTTPRequestHandler?
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
# post variables?!
server = HTTPServer(('', 4444), Handler)
server.serve_forever()
# test with:
# curl -d "param1=value1¶m2=value2" http://localhost:4444
Je voudrais simplement pouvoir obtenir les valeurs de param1 et param2. Merci!
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(self.rfile, pdict)
Elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers.getheader('content-length'))
postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
else:
postvars = {}
...
J'ai essayé de modifier le message et j'ai été rejeté, il y a donc ma version de ce code qui devrait fonctionner sur Python 2.7 et 3.2:
from sys import version as python_version
from cgi import parse_header, parse_multipart
if python_version.startswith('3'):
from urllib.parse import parse_qs
from http.server import BaseHTTPRequestHandler
else:
from urlparse import parse_qs
from BaseHTTPServer import BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
...
def parse_POST(self):
ctype, pdict = parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = parse_multipart(self.rfile, pdict)
Elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = parse_qs(
self.rfile.read(length),
keep_blank_values=1)
else:
postvars = {}
return postvars
def do_POST(self):
postvars = self.parse_POST()
...
...