本文整理汇总了Python中cgi.FieldStorage方法的典型用法代码示例。如果您正苦于以下问题:Python cgi.FieldStorage方法的具体用法?Python cgi.FieldStorage怎么用?Python cgi.FieldStorage使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cgi
的用法示例。
在下文中一共展示了cgi.FieldStorage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def main():
"""Runs the login and logout CGI script."""
form = cgi.FieldStorage(environ=os.environ)
login_url = os.environ['PATH_INFO']
email = os.environ.get('USER_EMAIL', '')
admin = os.environ.get('USER_IS_ADMIN', '0') == '1'
action = form.getfirst(ACTION_PARAM)
set_email = form.getfirst(EMAIL_PARAM, '')
set_admin = form.getfirst(ADMIN_PARAM, '') == 'True'
continue_url = form.getfirst(CONTINUE_PARAM, '')
LoginCGI(login_url,
email,
admin,
action,
set_email,
set_admin,
continue_url,
sys.stdout)
return 0
示例2: get_post_form
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def get_post_form(environ):
assert is_post_request(environ)
input = environ['wsgi.input']
post_form = environ.get('wsgi.post_form')
if (post_form is not None
and post_form[0] is input):
return post_form[2]
# This must be done to avoid a bug in cgi.FieldStorage
environ.setdefault('QUERY_STRING', '')
fs = cgi.FieldStorage(fp=input,
environ=environ,
keep_blank_values=1)
return fs
# from https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py
示例3: _decode_value
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def _decode_value(self, value):
"""
Decode the specified value to unicode. Assumes value is a ``str`` or
`FieldStorage`` object.
``FieldStorage`` objects are specially handled.
"""
if isinstance(value, cgi.FieldStorage):
# decode FieldStorage's field name and filename
value = copy.copy(value)
if self.decode_keys:
value.name = value.name.decode(self.encoding, self.errors)
value.filename = value.filename.decode(self.encoding, self.errors)
else:
try:
value = value.decode(self.encoding, self.errors)
except AttributeError:
pass
return value
示例4: transcode_fs
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def transcode_fs(self, fs, content_type):
# transcode FieldStorage
if PY3: # pragma: no cover
decode = lambda b: b
else:
decode = lambda b: b.decode(self.charset, self.errors)
data = []
for field in fs.list or ():
field.name = decode(field.name)
if field.filename:
field.filename = decode(field.filename)
data.append((field.name, field))
else:
data.append((field.name, decode(field.value)))
# TODO: transcode big requests to temp file
content_type, fout = _encode_multipart(
data,
content_type,
fout=io.BytesIO()
)
return fout
# TODO: remove in 1.4
示例5: __parse_post_body
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def __parse_post_body(environ, ignore_get=False):
post_data = {}
# accept post json
if environ["CONTENT_TYPE"].strip(';') == "application/json" and environ["REQUEST_METHOD"] == "POST":
storage = environ['wsgi.input'].read()
if storage:
return json.loads(storage)
storage = FieldStorage(environ['wsgi.input'], environ=environ, keep_blank_values=True)
# accept get querystring
if not ignore_get:
for k in storage.keys():
post_data[k] = storage.getvalue(k)
return post_data
示例6: do_POST
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_POST(self):
if self.path=="/send":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
self.nsa_queue.put(form["le_texte"].value[::-1])
print "Le texte en clair: %s" % form["le_texte"].value
self.send_response(200)
self.end_headers()
self.wfile.write(form["le_texte"].value[::-1])
return
if self.path=="/decrypt":
le_texte = self.nsa_queue.get()
print "Le texte en encode: %s" % le_texte
self.send_response(200)
self.end_headers()
self.wfile.write("Le texte intercepte: %s." % le_texte)
self.wfile.write(" Le texte decode: %s" % le_texte[::-1])
return
示例7: do_POST
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_POST(self):
if self.path == "/play":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type'],})
print "Client -> Le tableau: %s" % form["le_tableau"].value
i = random.randint(1, 9)
while form["le_tableau"].value[i] != "0":
# print "index ", i, " value ", form["le_tableau"].value[i]
i = random.randint(1, 9)
print "Server played %s ->" % i
self.send_response(200)
self.end_headers()
self.wfile.write(i-1)
return
示例8: files
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def files(self):
""" File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise None; this is the client
side filename, *not* the file name on which it is stored (that's
a temporary file you don't deal with)
file
The file(-like) object from which you can read the data.
value
The value as a *string*; for file uploads, this transparently
reads the file every time you request the value. Do not do this
on big files.
"""
files = FormsDict()
for name, item in self.POST.iterallitems():
if hasattr(item, 'filename'):
files[name] = item
return files
示例9: POST
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def POST(self):
""" The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
"""
post = FormsDict()
safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
if key in self.environ: safe_env[key] = self.environ[key]
if NCTextIOWrapper:
fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
else:
fb = self.body
data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
for item in (data.list or [])[:self.MAX_PARAMS]:
post[item.name] = item if item.filename else item.value
return post
示例10: extract_data_from_multipart_request
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def extract_data_from_multipart_request(self, environ: dict) -> Any:
try:
form = FieldStorage(
fp=environ["wsgi.input"], environ=environ, keep_blank_values=True
)
except (TypeError, ValueError):
raise HttpBadRequestError("Malformed request data")
try:
operations = json.loads(form.getvalue("operations"))
except (TypeError, ValueError):
raise HttpBadRequestError(
"Request 'operations' multipart field is not a valid JSON"
)
try:
files_map = json.loads(form.getvalue("map"))
except (TypeError, ValueError):
raise HttpBadRequestError(
"Request 'map' multipart field is not a valid JSON"
)
return combine_multipart_data(operations, files_map, form)
示例11: test_app
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_app(environ, start_response):
"""Probably not the most efficient example."""
import cgi
start_response('200 OK', [('Content-Type', 'text/html')])
yield '<html><head><title>Hello World!</title></head>\n' \
'<body>\n' \
'<p>Hello World!</p>\n' \
'<table border="1">'
names = environ.keys()
names.sort()
for name in names:
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
name, cgi.escape(`environ[name]`))
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
keep_blank_values=1)
if form.list:
yield '<tr><th colspan="2">Form data</th></tr>'
for field in form.list:
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
field.name, field.value)
yield '</table>\n' \
'</body></html>\n'
示例12: do_test
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def do_test(buf, method):
env = {}
if method == "GET":
fp = None
env['REQUEST_METHOD'] = 'GET'
env['QUERY_STRING'] = buf
elif method == "POST":
fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes
env['REQUEST_METHOD'] = 'POST'
env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
env['CONTENT_LENGTH'] = str(len(buf))
else:
raise ValueError("unknown method: %s" % method)
try:
return cgi.parse(fp, env, strict_parsing=1)
except Exception as err:
return ComparableException(err)
示例13: test_strict
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_strict(self):
for orig, expect in parse_strict_test_cases:
# Test basic parsing
d = do_test(orig, "GET")
self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig))
d = do_test(orig, "POST")
self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig))
env = {'QUERY_STRING': orig}
fs = cgi.FieldStorage(environ=env)
if isinstance(expect, dict):
# test dict interface
self.assertEqual(len(expect), len(fs))
self.assertCountEqual(expect.keys(), fs.keys())
##self.assertEqual(norm(expect.values()), norm(fs.values()))
##self.assertEqual(norm(expect.items()), norm(fs.items()))
self.assertEqual(fs.getvalue("nonexistent field", "default"), "default")
# test individual fields
for key in expect.keys():
expect_val = expect[key]
self.assertIn(key, fs)
if len(expect_val) > 1:
self.assertEqual(fs.getvalue(key), expect_val)
else:
self.assertEqual(fs.getvalue(key), expect_val[0])
示例14: test_fieldstorage_multipart
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_fieldstorage_multipart(self):
#Test basic FieldStorage multipart parsing
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH': '558'}
fp = BytesIO(POSTDATA.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 4)
expect = [{'name':'id', 'filename':None, 'value':'1234'},
{'name':'title', 'filename':None, 'value':''},
{'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
{'name':'submit', 'filename':None, 'value':' Add '}]
for x in range(len(fs.list)):
for k, exp in expect[x].items():
got = getattr(fs.list[x], k)
self.assertEqual(got, exp)
示例15: test_fieldstorage_multipart_leading_whitespace
# 需要导入模块: import cgi [as 别名]
# 或者: from cgi import FieldStorage [as 别名]
def test_fieldstorage_multipart_leading_whitespace(self):
env = {
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': 'multipart/form-data; boundary={}'.format(BOUNDARY),
'CONTENT_LENGTH': '560'}
# Add some leading whitespace to our post data that will cause the
# first line to not be the innerboundary.
fp = BytesIO(b"\r\n" + POSTDATA.encode('latin-1'))
fs = cgi.FieldStorage(fp, environ=env, encoding="latin-1")
self.assertEqual(len(fs.list), 4)
expect = [{'name':'id', 'filename':None, 'value':'1234'},
{'name':'title', 'filename':None, 'value':''},
{'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
{'name':'submit', 'filename':None, 'value':' Add '}]
for x in range(len(fs.list)):
for k, exp in expect[x].items():
got = getattr(fs.list[x], k)
self.assertEqual(got, exp)