本文整理汇总了Python中webob.Request.body方法的典型用法代码示例。如果您正苦于以下问题:Python Request.body方法的具体用法?Python Request.body怎么用?Python Request.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Request
的用法示例。
在下文中一共展示了Request.body方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse_params
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def _parse_params(self, environ):
# Try to find the parameters in various sources,
# reflecting preference order:
# Query string
params = dict(parse_querystring(environ))
# POST body
request = Request(environ)
if request.content_type == 'application/x-www-form-urlencoded':
body = request.body
params.update(parse_formvars(environ, include_get_vars=False))
request.body = body
# Authorization header
auth_header = AUTHORIZATION(environ)
if auth_header:
try:
params.update(oauth2.Request._split_header(auth_header))
except:
pass
# Remove the non-oauth params
if params:
for key in params.keys():
if not (key.startswith('oauth_') or key == 'realm'):
del params[key]
return dict(params)
示例2: __call__
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def __call__(self, environ, start_response):
# Before we go any further, gzip is hard to parse, don't ask for it
del environ['HTTP_ACCEPT_ENCODING']
request = Request(environ)
if request.method == "POST":
NotImplemented
valid = captcha in self.valid_captchas
params = urllib.urlencode(request.POST)
post = request.POST.copy()
post['isHuman'] = valid
request.body = urllib.urlencode(post)
response = request.get_response(self.app)
# We don't want to deal with images and the like
if response.content_type == 'text/html':
try:
parsed = html.fromstring(response.body)
except (XMLSyntaxError, TypeError):
return response(environ, start_response)
response.body = html.tostring(parsed)
NotImplemented
return response(environ, start_response)
示例3: PUT
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def PUT(self, env, start_response):
""" Handle Container update and create request """
# First check if the resource exists and if it is a directory
path = '/' + concat_parts('v1', self.account_name, self.container_name,
self.parent_name, self.object_name)
exists, headers, body = check_resource(env, 'HEAD', path,
self.logger, False)
if exists:
content_type = headers.get('content-type', '')
content_type = content_type.lower() if content_type else ''
if (content_type.find('application/directory') < 0 and
self.object_name):
return get_err_response('Conflict')
else:
res = self._check_parent(env, start_response)
if res:
return res
req = Request(env)
req.headers['content-type'] = 'application/directory'
req.headers['content-length'] = '0'
req.body = ''
res = req.get_response(self.app)
return res
示例4: test_request_post_valid
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def test_request_post_valid(self):
environ = {'wsgi.input': StringIO('')}
req=Request(environ)
req.method = 'POST'
req.body='dblistform_d:0:name=a&dblistform_d:0:id=1'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
r = self.widget().request(req)
assert r.body == """Form posted successfully [{'id': 1, 'name': u'a'}]""", r.body
示例5: test_request_post_redirect
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def test_request_post_redirect(self):
environ = {'wsgi.input': StringIO('')}
req=Request(environ)
req.method = 'POST'
req.body='dbformpage_d:name=a'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
r = self.widget(redirect="/foo").request(req)
assert( r.status_int == 302 and r.location=="/foo" )
示例6: test_request_post_counts_update
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def test_request_post_counts_update(self):
environ = {'wsgi.input': StringIO('')}
req=Request(environ)
req.method = 'POST'
req.body='dblistform_d:0:name=a&dblistform_d:0:id=1&dblistform_d:1:name=b&dblistform_d:1:id=2'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
assert(self.DbTestCls1.query.count() == 2)
r = self.widget().request(req)
assert(self.DbTestCls1.query.count() == 2)
示例7: __call__
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def __call__(self, environ, start_response):
# Before we go any further, gzip is hard to parse, don't ask for it
del environ['HTTP_ACCEPT_ENCODING']
request = Request(environ)
if request.method == "POST":
valid = 'isHuman' in request.POST
if not valid:
params = urllib.urlencode(request.POST)
if request.referrer is None:
# huh....
raise ValueError
from_page = request.referrer.split("?")[0] + "?" + params
response = Response(status=302, location=from_page)
return response(environ, start_response)
else:
post = request.POST.copy()
del post['isHuman']
request.body = urllib.urlencode(post)
response = request.get_response(self.app)
# We don't want to deal with images and the like
if response.content_type == 'text/html':
try:
parsed = html.fromstring(response.body)
except (XMLSyntaxError, TypeError):
return response(environ, start_response)
forms = parsed.xpath("//form")
index = 0
for form in forms:
if form.method.upper() == "GET":
continue
try:
tags = [child for child in form.iterdescendants() if child.tag=='input']
submit = tags[-1] # maybe?
except IndexError:
# Empty forms are weird.
continue
box_id = "captcha%d" % index
index += 1
checkbox = Element("input", type="checkbox", name="isHuman", value="1", id=box_id)
label = Element("label", attrib={'for':box_id})
label.text = "I am a human"
submit.addprevious(checkbox)
submit.addprevious(label)
response.body = html.tostring(parsed)
return response(environ, start_response)
示例8: test_request_post_valid
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def test_request_post_valid(self):
environ = {'wsgi.input': StringIO(''),
}
req=Request(environ)
req.method = 'POST'
req.body='mytestwidget:field1=a&mytestwidget:field2=b&mytestwidget:field3=c'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
r = self.widget().request(req)
assert (
r.body == """Form posted successfully {'field2': 'b', 'field3': 'c', 'field1': 'a'}""" or
r.body == """Form posted successfully {'field2': u'b', 'field3': u'c', 'field1': u'a'}"""
), r.body
示例9: _test_request_post_content_update
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def _test_request_post_content_update(self):
environ = {'wsgi.input': StringIO('')}
req=Request(environ)
req.method = 'POST'
req.body='dblistform_d:0:name=b&dblistform_d:0:id=1'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
original = self.DbTestCls1.query.filter(self.DbTestCls1.id==1).one()
assert(original.name == 'foo1')
r = self.widget().request(req)
updated = self.DbTestCls1.query.filter(self.DbTestCls1.id=='1')
assert(updated.count() == 1)
updated = updated.one()
assert(updated.name == 'b')
示例10: test_no_query_property
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def test_no_query_property(self):
old_prop = self.widget.entity.query
self.widget.entity.query = None
environ = {'wsgi.input': StringIO('')}
req=Request(environ)
req.method = 'POST'
req.body='dbformpage_d:name=a'
req.environ['CONTENT_LENGTH'] = str(len(req.body))
req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
self.mw.config.debug = True
try:
r = self.widget().request(req)
assert False
except AttributeError, e:
print e
assert(str(e) == 'entity has no query_property()')
示例11: _reboot
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def _reboot(self, req, request_data, *parts):
"""
Handle the machine reboot request
"""
data = {}
force = request_data.get('force', False)
if isinstance(force, str):
force = 'HARD' if force.lower() == 'true' else 'SOFT'
else:
force = 'HARD' if force else 'SOFT'
data['reboot'] = {'type': force}
env = self._fresh_env(req)
env['PATH_INFO'] = concat(self.os_path, '/', parts[0], '/action')
env['CONTENT_TYPE'] = 'application/json'
new_req = Request(env)
new_req.body = json.dumps(data)
res = new_req.get_response(self.app)
return res
示例12: app
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def app(environ, start_response):
try:
request = Request(environ)
response = Response()
if len(request.body) == 0:
try:
request.body = sys.argv[1]
except:
response.status = 400 # Bad Request
response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
response.body = str(NoApplicableCode('No query string found.'))
return response(environ, start_response)
wps = pywps.Pywps(request.method)
if wps.parseRequest(request.body):
# pywps.debug(wps.inputs)
response_msg = wps.performRequest()
# request performed, write the response back
if response_msg:
response.status = 200 # OK
response.headerlist = [('Content-Type', wps.request.contentType),]
response.body = response_msg
# pywps.response.response(wps.response,
# sys.stdout, wps.parser.soapVersion, wps.parser.isSoap,
# wps.parser.isSoapExecute, wps.request.contentType)
except WPSException as e:
traceback.print_exc(file=pywps.logFile)
response.status = 400 # Bad Request
response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
response.body = str(e)
# pywps.response.response(e, sys.stdout, wps.parser.soapVersion,
# wps.parser.isSoap,
# wps.parser.isSoapExecute)
except Exception as e:
traceback.print_exc(file=pywps.logFile)
response.status = 500 # Internal Server Error
response.headerlist = [('Content-Type', 'application/xml; charset=UTF-8'),]
response.body = str(NoApplicableCode(e.message))
return response(environ, start_response)
示例13: PUT
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def PUT(self, env, start_response):
"""
Handle Container update and create request
"""
# First check if the resource exists and if it is a directory
path = '/' + concat_parts('v1', self.account_name, self.container_name,
self.parent_name, self.object_name)
exists, headers, body = check_resource(env, 'GET', path, self.logger,
False, None)
if exists:
content_type = headers.get('content-type', '')
content_type = content_type.lower() if content_type else ''
if content_type.find('application/directory') >= 0:
return get_err_response('Conflict')
else:
path = '/' + concat_parts('v1', self.account_name,
self.container_name)
query_string = 'delimiter=/&prefix=' + \
concat_parts(self.parent_name, self.object_name) + '/'
parent_exists, dummy, body = check_resource(env, 'GET', path,
self.logger, True,
query_string)
if parent_exists:
try:
children = json.loads(body)
if len(children) > 0:
# No children under, no resource exist
return get_err_response('Conflict')
except ValueError:
return get_err_response('InconsistantState')
else:
return get_err_response('NoParentContainer')
# Check if the parent is OK. it should be either a real directory or
# a virtual directory
res = self._check_parent(env, start_response)
if res:
return res
# Create a new WebOb Request object according to the current request
#if we found X-Object-UploadID in the header, we need know that
#the request is uploading a piece of a large object, the piece
#will need to go to the segments folder
try:
self._handle_part(env)
except Exception as ex:
return get_err_response(ex.message)
req = Request(env)
metadata = {}
if req.body:
try:
body = self._handle_body(env, True)
except Exception:
return get_err_response('InvalidBody')
# headling copy object
if body.get('copy'):
# add the copy-from header to indicate a copy operation
# for swift
req.headers['X-Copy-From'] = body.get('copy')
req.body = ''
else:
if body.get('metadata'):
metadata = body['metadata']
for key in metadata:
if metadata[key] == '':
req.headers[Consts.META_OBJECT_ID + key] = ''
else:
req.headers[Consts.META_OBJECT_ID + key] = \
key + ":" + str(metadata[key])
else:
metadata = {}
try:
req.body = str(body.get('value', ''))
req.headers['content-type'] = body.get('mimetype',
'text/plain').lower()
encoding = body.get('valuetransferencoding', 'utf-8')
req.headers[Consts.VALUE_ENCODING] = encoding
# if the value is encoded using base64, then
# we need to decode it and save as binary
if encoding == Consts.ENCODING_BASE64:
req.body = base64.decodestring(req.body)
except KeyError:
return get_err_response('InvalidContent')
else:
req.headers['content-length'] = '0'
res = req.get_response(self.app)
# Deal with the response now.
# Build the response message body according to CDMI specification
# If the response status is 201, then we know we have successfully
# created the object. According to CDMI spec, only send response body
# when creating new object.
if res.status_int == 201:
body = {}
#.........这里部分代码省略.........
示例14: pprint
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
# {'METHOD': 'GET'}
req_environ=req.environ
#pprint(req.environ)
# 'GET'
req_method=req.method
#pprint(req.method)
#
req_dir=dir(req)
# req
# <Request at 0x27cd9e8 (invalid WSGI environ)>
req=Request.blank('/article?id=1&id=2')
pprint(req.environ)
# demo for request body
req.body='This is a request body'
req.path_info_peek()
req.path_info_pop()
req.script_name
# Headers
req.headers['Content-Type'] = 'application/x-www-urlencoded'
req.headers.items()
req.environ['CONTENT_TYPE']
# Query & POST
req = Request.blank('/test?check=a&check=b&name=Bob')
req.GET
req.GET['check']
req.GET.getall('check')
示例15: PUT
# 需要导入模块: from webob import Request [as 别名]
# 或者: from webob.Request import body [as 别名]
def PUT(self, env, start_response):
""" Handle non-CDMI Object update and create request. """
# First check if the resource exists and if it is a directory
path = '/' + concat_parts('v1', self.account_name, self.container_name,
self.parent_name, self.object_name)
exists, headers, body = check_resource(env, 'GET', path, self.logger,
False, None)
if exists:
content_type = headers.get('content-type', '')
content_type = content_type.lower() if content_type else ''
if content_type.find('application/directory') >= 0:
return get_err_response('Conflict')
else:
path = '/' + concat_parts('v1', self.account_name,
self.container_name)
query_string = 'delimiter=/&prefix=' + \
concat_parts(self.parent_name, self.object_name) + '/'
parent_exists, dummy, body = check_resource(env, 'GET', path,
self.logger, True,
query_string)
if parent_exists:
try:
children = json.loads(body)
if len(children) > 0:
#No children under, no resource exist
return get_err_response('Conflict')
except ValueError:
return get_err_response('InconsistantState')
else:
return get_err_response('NoParentContainer')
# Check if the parent is OK. it should be either a real directory
# or a virtual directory
res = self._check_parent(env, start_response)
if res:
return res
try:
self._handle_part(env)
except Exception as ex:
return get_err_response(ex.message)
try:
body = self._handle_body(env, False)
except Exception as ex:
return get_err_response('InvalidBody')
else:
env['CONTENT_TYPE'] = body.get('mimetype', 'text/plain')
req = Request(env)
req.body = body.get('value', '')
req.headers['content-length'] = len(req.body)
res = req.get_response(self.app)
if (res.status_int in [201, 204] and
env.get('HTTP_X_USE_EXTRA_REQUEST')):
extra_res = self._put_manifest(env)
res.status_int = extra_res.status
return res