本文整理汇总了Python中pyramid.response.Response方法的典型用法代码示例。如果您正苦于以下问题:Python response.Response方法的具体用法?Python response.Response怎么用?Python response.Response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response
的用法示例。
在下文中一共展示了response.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: openapi_validation_error
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def openapi_validation_error(
context: t.Union[RequestValidationError, ResponseValidationError], request: Request
) -> Response:
"""Render any validation errors as JSON."""
if isinstance(context, RequestValidationError):
logger.warning(context)
if isinstance(context, ResponseValidationError):
logger.error(context)
extract_errors = request.registry.settings["pyramid_openapi3_extract_errors"]
errors = list(extract_errors(request, context.errors))
# If validation failed for request, it is user's fault (-> 400), but if
# validation failed for response, it is our fault (-> 500)
if isinstance(context, RequestValidationError):
status_code = 400
for error in context.errors:
if isinstance(error, InvalidSecurity):
status_code = 401
if isinstance(context, ResponseValidationError):
status_code = 500
return exception_response(status_code, json_body=errors)
示例2: test_has_context
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_has_context(route, get_client, sentry_init, capture_events):
sentry_init(integrations=[PyramidIntegration()])
events = capture_events()
@route("/message/{msg}")
def hi2(request):
capture_message(request.matchdict["msg"])
return Response("hi")
client = get_client()
client.get("/message/yoo")
(event,) = events
assert event["message"] == "yoo"
assert event["request"] == {
"env": {"SERVER_NAME": "localhost", "SERVER_PORT": "80"},
"headers": {"Host": "localhost"},
"method": "GET",
"query_string": "",
"url": "http://localhost/message/yoo",
}
assert event["transaction"] == "hi2"
示例3: test_large_json_request
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_large_json_request(sentry_init, capture_events, route, get_client):
sentry_init(integrations=[PyramidIntegration()])
data = {"foo": {"bar": "a" * 2000}}
@route("/")
def index(request):
assert request.json == data
assert request.text == json.dumps(data)
assert not request.POST
capture_message("hi")
return Response("ok")
events = capture_events()
client = get_client()
client.post("/", content_type="application/json", data=json.dumps(data))
(event,) = events
assert event["_meta"]["request"]["data"]["foo"]["bar"] == {
"": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
}
assert len(event["request"]["data"]["foo"]["bar"]) == 512
示例4: test_flask_empty_json_request
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_flask_empty_json_request(sentry_init, capture_events, route, get_client, data):
sentry_init(integrations=[PyramidIntegration()])
@route("/")
def index(request):
assert request.json == data
assert request.text == json.dumps(data)
assert not request.POST
capture_message("hi")
return Response("ok")
events = capture_events()
client = get_client()
response = client.post("/", content_type="application/json", data=json.dumps(data))
assert response[1] == "200 OK"
(event,) = events
assert event["request"]["data"] == data
示例5: test_files_and_form
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_files_and_form(sentry_init, capture_events, route, get_client):
sentry_init(integrations=[PyramidIntegration()], request_bodies="always")
data = {"foo": "a" * 2000, "file": (BytesIO(b"hello"), "hello.txt")}
@route("/")
def index(request):
capture_message("hi")
return Response("ok")
events = capture_events()
client = get_client()
client.post("/", data=data)
(event,) = events
assert event["_meta"]["request"]["data"]["foo"] == {
"": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
}
assert len(event["request"]["data"]["foo"]) == 512
assert event["_meta"]["request"]["data"]["file"] == {
"": {"len": 0, "rem": [["!raw", "x", 0, 0]]}
}
assert not event["request"]["data"]["file"]
示例6: test_errorhandler_ok
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_errorhandler_ok(
sentry_init, pyramid_config, capture_exceptions, route, get_client
):
sentry_init(integrations=[PyramidIntegration()])
errors = capture_exceptions()
@route("/")
def index(request):
raise Exception()
def errorhandler(exc, request):
return Response("bad request")
pyramid_config.add_view(errorhandler, context=Exception)
client = get_client()
client.get("/")
assert not errors
示例7: test_errorhandler_500
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_errorhandler_500(
sentry_init, pyramid_config, capture_exceptions, route, get_client
):
sentry_init(integrations=[PyramidIntegration()])
errors = capture_exceptions()
@route("/")
def index(request):
1 / 0
def errorhandler(exc, request):
return Response("bad request", status=500)
pyramid_config.add_view(errorhandler, context=Exception)
client = get_client()
app_iter, status, headers = client.get("/")
assert b"".join(app_iter) == b"bad request"
assert status.lower() == "500 internal server error"
(error,) = errors
assert isinstance(error, ZeroDivisionError)
示例8: get_post_response
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def get_post_response(dom, request):
id_text = dom.find('Body/GetPost/id').text
post = MemoryDb.get_post(id_text, get_ip(request))
if not post:
raise exception_response(404)
resp_xml = """<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetPostResponse xmlns="http://tempuri.org/">
<GetPostResult>
<Id>{}</Id>
<Title>{}</Title>
<Published>{}</Published>
<Content>{}</Content>
<ViewCount>{}</ViewCount>
</GetPostResult>
</GetPostResponse>
</soap:Body>
</soap:Envelope>""".format(post.id, post.title, post.published, post.content, post.view_count) # noqa
return Response(body=resp_xml, content_type='text/xml')
示例9: delete_post_response
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def delete_post_response(dom, request):
id_text = dom.find('Body/DeletePost/id').text
post = MemoryDb.get_post(id_text, get_ip(request))
if not post:
raise exception_response(404)
if MemoryDb.is_post_read_only(post.id):
raise exception_response(403)
MemoryDb.delete_post(post, get_ip(request))
resp_xml = """<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<DeletePostResponse xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>""" # noqa
return Response(body=resp_xml, content_type='text/xml')
示例10: blog_post
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def blog_post(request):
print("Processing {} request from {} for the HTTP service: {}, ua: {}".format(
request.method, get_ip(request), request.url, request.user_agent
))
data = build_dict(request)
post_id = data.get('post_id')
post = MemoryDb.get_post(post_id, get_ip(request))
if not post:
return Response('{"error":"Post with ID not found: ' + post_id + '"}', status=404)
return post
################################################################################
# POST /api/blog
# { blog post data... }
#
示例11: login
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def login(self, request, auth_api):
post_data = request.POST
try:
user_id = post_data.getone('user_id')
org_id = post_data.getone('org_id')
password = post_data.getone('password')
except KeyError as e:
LOGGER.debug('User has not filled all credential fields for authentication. %s.',
e.message)
raise HTTPForbidden
if user_id and org_id and password:
try:
auth_api.authenticate_with_password(org_id, user_id, password)
except INVALID_CREDENTIALS:
LOGGER.warning('User tried to authenticate with invalid credentials. '
'User id: %r, organization id: %r.', user_id, org_id)
raise HTTPForbidden
credentials = self._join_org_id_user_id(org_id, user_id)
headers = remember(request, credentials)
self._add_content_type_header(headers)
return Response(headerlist=headers)
示例12: test_response
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def test_response(self,
res_limits,
full_access,
is_authenticated,
is_cert_available,
expected_response):
mocked_request = self._get_mocked_request(res_limits,
full_access,
is_authenticated,
is_cert_available)
view_inst = self._get_view_instance(mocked_request)
resp = view_inst.make_response()
self.assertIsInstance(resp, Response)
resp_body = json.loads(resp.body)
self.assertDictEqual(resp_body, expected_response)
self.assertEqual(resp.content_type, self.expected_content_type)
self.assertEqual(resp.status_int, 200)
示例13: post_sentinel_op
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def post_sentinel_op(request):
params = get_params_from_request(request, op_schema)
janus_server = request.registry.janus_server
janus_watcher = request.registry.janus_watcher
if params['op'] == 'start_maintenance':
janus_server.start_maintenance()
elif params['op'] == 'stop_maintenance':
janus_server.stop_maintenance()
elif params['op'] == 'restart_process':
if janus_watcher is None:
raise JanusCloudError('janus_watcher not enable',
JANUS_ERROR_NOT_IMPLEMENTED)
janus_watcher.stop()
janus_watcher.start()
else:
raise JanusCloudError('Not implement for op {}'.format(params['op']),
JANUS_ERROR_NOT_IMPLEMENTED)
return Response(status=200)
示例14: delete_videoroom_room
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def delete_videoroom_room(request):
plugin = request.registry.videoroom_plugin
room_mgr = plugin.room_mgr
room_id = int(request.matchdict['room_id'])
room_base_info = get_params_from_request(request, room_base_schema)
room_mgr.destroy(room_id=room_id,
secret=room_base_info['secret'],
permanent=room_base_info['permanent'])
return Response(status=200)
#@get_view(route_name='videoroom_tokens')
#def get_videoroom_tokens(request):
# plugin = request.registry.videoroom_plugin
# room_mgr = plugin.room_mgr
# room_id = int(request.matchdict['room_id'])
# room = room_mgr.get(room_id)
# tokens_info = list(room.allowed)
# return tokens_info
示例15: get_autoscaler_count
# 需要导入模块: from pyramid import response [as 别名]
# 或者: from pyramid.response import Response [as 别名]
def get_autoscaler_count(request):
service = request.swagger_data.get("service")
instance = request.swagger_data.get("instance")
cluster = settings.cluster
soa_dir = settings.soa_dir
instance_config = get_instance_config(service, instance, cluster, soa_dir)
if not isinstance(
instance_config, (KubernetesDeploymentConfig, MarathonServiceConfig)
):
error_message = (
f"Autoscaling is not supported for {service}.{instance} because instance type is not "
f"marathon or kubernetes."
)
raise ApiFailure(error_message, 501)
response_body = {
"desired_instances": instance_config.get_instances(),
"calculated_instances": instance_config.get_instances(with_limit=False),
}
return Response(json_body=response_body, status_code=200)