本文整理汇总了Python中werkzeug.wrappers.Request.encoding_errors方法的典型用法代码示例。如果您正苦于以下问题:Python Request.encoding_errors方法的具体用法?Python Request.encoding_errors怎么用?Python Request.encoding_errors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.wrappers.Request
的用法示例。
在下文中一共展示了Request.encoding_errors方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "get"
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
result = dict()
for task_type in self._task_types:
result[task_type.__name__] = \
list(p.describe() for p in task_type.ACCEPTED_PARAMETERS)
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response
示例2: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
route = self.router.bind_to_environ(environ)
try:
endpoint, args = route.match()
except HTTPException as exc:
return exc(environ, start_response)
if endpoint == "events":
return self.event_handler(environ, start_response)
elif endpoint == "logo":
return self.logo_handler(environ, start_response)
elif endpoint == "root":
return self.root_handler(environ, start_response)
else:
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
if endpoint == "sublist":
SubListHandler(request, response, args["user_id"])
elif endpoint == "scores":
ScoreHandler(request, response)
elif endpoint == "history":
HistoryHandler(request, response)
return response(environ, start_response)
示例3: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
route = self.router.bind_to_environ(environ)
try:
endpoint, args = route.match()
except HTTPException as exc:
return exc(environ, start_response)
assert endpoint == "sublist"
request = Request(environ)
request.encoding_errors = "strict"
if request.accept_mimetypes.quality("application/json") <= 0:
raise NotAcceptable()
result = list()
for task_id in self.task_store._store.keys():
result.extend(
self.scoring_store.get_submissions(
args["user_id"], task_id
).values()
)
result.sort(key=lambda x: (x.task, x.time))
result = list(a.__dict__ for a in result)
response = Response()
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps(result)
return response(environ, start_response)
示例4: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "rpc"
response = Response()
if self._auth is not None and not self._auth(environ):
response.status_code = 403
response.mimetype = "plain/text"
response.data = "Request not allowed."
return response
request = Request(environ)
request.encoding_errors = "strict"
remote_service = ServiceCoord(args['service'], args['shard'])
if remote_service not in self._service.remote_services:
return NotFound()
# TODO Check content_encoding and content_md5.
if request.mimetype != "application/json":
return UnsupportedMediaType()
if request.accept_mimetypes.quality("application/json") <= 0:
return NotAcceptable()
try:
data = json.load(request.stream, encoding='utf-8')
except ValueError:
return BadRequest()
if not self._service.remote_services[remote_service].connected:
return ServiceUnavailable()
result = self._service.remote_services[remote_service].execute_rpc(
args['method'], data)
# XXX We could set a timeout on the .wait().
result.wait()
response.status_code = 200
response.mimetype = "application/json"
response.data = json.dumps({
"data": result.value,
"error": None if result.successful() else "%s" % result.exception})
return response
示例5: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
urls = self._url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
except HTTPException as exc:
return exc
assert endpoint == "rpc"
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
remote_service = ServiceCoord(args['service'], args['shard'])
if remote_service not in self._service.remote_services:
return NotFound()
# TODO Check content_encoding and content_md5.
if request.mimetype != "application/json":
return UnsupportedMediaType()
if request.accept_mimetypes.quality("application/json") <= 0:
return NotAcceptable()
try:
data = json.load(request.stream, encoding='utf-8')
except ValueError:
return BadRequest()
if not self._service.remote_services[remote_service].connected:
return ServiceUnavailable()
value = AsyncResult()
@rpc_callback
def callback(service, data, plus=None, error=None):
value.set({'data': data, 'error': error})
self._service.remote_services[remote_service].execute_rpc(
args['method'], data, callback)
response.status_code = 200
response.mimetype = "application/json"
# XXX We could set a timeout on the .get().
response.data = json.dumps(value.get())
return response
示例6: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
original_response = Response.from_app(self.wrapped_app, environ)
# We send relative locations to play nice with reverse proxies
# but Werkzeug by default turns them into absolute ones.
original_response.autocorrect_location_header = False
if self.DIGEST_HEADER not in original_response.headers:
return original_response
digest = original_response.headers.pop(self.DIGEST_HEADER)
filename = original_response.headers.pop(self.FILENAME_HEADER, None)
mimetype = original_response.mimetype
try:
fobj = self.file_cacher.get_file(digest)
size = self.file_cacher.get_size(digest)
except KeyError:
return NotFound()
except TombstoneError:
return ServiceUnavailable()
request = Request(environ)
request.encoding_errors = "strict"
response = Response()
response.status_code = 200
response.mimetype = mimetype
if filename is not None:
response.headers.add(
"Content-Disposition", "attachment", filename=filename)
response.set_etag(digest)
response.cache_control.max_age = SECONDS_IN_A_YEAR
response.cache_control.private = True
response.response = \
wrap_file(environ, fobj, buffer_size=FileCacher.CHUNK_SIZE)
response.direct_passthrough = True
try:
# This takes care of conditional and partial requests.
response.make_conditional(
request, accept_ranges=True, complete_length=size)
except HTTPException as exc:
return exc
return response
示例7: wsgi_app
# 需要导入模块: from werkzeug.wrappers import Request [as 别名]
# 或者: from werkzeug.wrappers.Request import encoding_errors [as 别名]
def wsgi_app(self, environ, start_response):
"""Execute this instance as a WSGI application.
See the PEP for the meaning of parameters. The separation of
__call__ and wsgi_app eases the insertion of middlewares.
"""
request = Request(environ)
request.encoding_errors = "strict"
# The problem here is that we'd like to send an infinite stream
# of events, but WSGI has been designed to handle only finite
# responses. Hence, to do this we will have to "abuse" the API
# a little. This works well with gevent's pywsgi implementation
# but it may not with others (still PEP-compliant). Therefore,
# just to be extra-safe, we will terminate the response anyway,
# after a long timeout, to make it finite.
# The first such "hack" is the mechanism to trigger the chunked
# transfer-encoding. The PEP states just that "the server *may*
# use chunked encoding" to send each piece of data we give it,
# if we don't specify a Content-Length header and if both the
# client and the server support it. Accoring to the HTTP spec.
# all (and only) HTTP/1.1 compliant clients have to support it.
# We'll assume that the server software supports it too, and
# actually uses it (gevent does!) even if we have no way to
# check it. We cannot try to force such behavior as the PEP
# doesn't even allow us to set the Transfer-Encoding header.
# The second abuse is the use of the write() callable, returned
# by start_response, even if the PEP strongly discourages its
# use in new applications. We do it because we need a way to
# detect when the client disconnects, and we hope to achieve
# this by seeing when a call to write() fails, i.e. raises an
# exception. This behavior isn't documented by the PEP, but it
# seems reasonable and it's present in gevent (which raises a
# socket.error).
# The third non-standard behavior that we expect (related to
# the previous one) is that no one in the application-to-client
# chain does response buffering: neither any middleware nor the
# server (gevent doesn't!). This should also hold outside the
# server realm (i.e. no proxy buffering) but that's definetly
# not our responsibility.
# The fourth "hack" is to avoid an error to be printed on the
# logs. If the client terminates the connection, we catch and
# silently ignore the exception and return gracefully making
# the server try to write the last zero-sized chunk (used to
# mark the end of the stream). This will fail and produce an
# error. To avoid this we detect if we're running on a gevent
# server and make it "forget" this was a chunked response.
# Check if the client will understand what we will produce.
if request.accept_mimetypes.quality(b"text/event-stream") <= 0:
return NotAcceptable()(environ, start_response)
# Initialize the response and get the write() callback. The
# Cache-Control header is useless for conforming clients, as
# the spec. already imposes that behavior on them, but we set
# it explictly to avoid unwanted caching by unaware proxies and
# middlewares.
write = start_response(
b"200 OK",
[(b"Content-Type", b"text/event-stream; charset=utf-8"),
(b"Cache-Control", b"no-cache")])
# This is a part of the fourth hack (see above).
if hasattr(start_response, "__self__") and \
isinstance(start_response.__self__, WSGIHandler):
handler = start_response.__self__
else:
handler = None
# One-shot means that we will terminate the request after the
# first batch of sent events. We do this when we believe the
# client doesn't support chunked transfer. As this encoding has
# been introduced in HTTP/1.1 (as mandatory!) we restrict to
# requests in that HTTP version. Also, if it comes from an
# XMLHttpRequest it has been probably sent from a polyfill (not
# from the native browser implementation) which will be able to
# read the response body only when it has been fully received.
if environ[b"SERVER_PROTOCOL"] != b"HTTP/1.1" or request.is_xhr:
one_shot = True
else:
one_shot = False
# As for the Server-Sent Events [1] spec., this is the way for
# the client to tell us the ID of the last event it received
# and to ask us to send it the ones that happened since then.
# [1] http://www.w3.org/TR/eventsource/
# The spec. requires implementations to retry the connection
# when it fails, adding the "Last-Event-ID" HTTP header. But in
# case of an error they stop, and we have to (manually) delete
# the EventSource and create a new one. To obtain that behavior
# again we give the "last_event_id" as a URL query parameter
# (with lower priority, to have the header override it).
last_event_id = request.headers.get(b"Last-Event-ID",
type=lambda x: x.decode('utf-8'))
if last_event_id is None:
#.........这里部分代码省略.........