本文整理汇总了Python中sanic.response.text函数的典型用法代码示例。如果您正苦于以下问题:Python text函数的具体用法?Python text怎么用?Python text使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: response
def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Request
:param exception: Exception to handle
:return: Response object
"""
handler = self.lookup(exception)
response = None
try:
if handler:
response = handler(request=request, exception=exception)
if response is None:
response = self.default(request=request, exception=exception)
except Exception:
self.log(format_exc())
if self.debug:
url = getattr(request, 'url', 'unknown')
response_message = (
'Exception raised in exception handler "{}" '
'for uri: "{}"\n{}').format(
handler.__name__, url, format_exc())
log.error(response_message)
return text(response_message, 500)
else:
return text('An error occurred while handling an error', 500)
return response
开发者ID:penelopeia,项目名称:sanic,代码行数:28,代码来源:handlers.py
示例2: authenticate_request
def authenticate_request(request: Request):
global AUTH
auth = request.headers.get("authorization")
if auth:
# Dummy auth check. We can have anything here and it's fine.
if AUTH not in auth:
return text("Unauthorized", status=401)
else:
return text("Unauthorized", status=401)
开发者ID:channelcat,项目名称:sanic,代码行数:9,代码来源:test_blueprint_group.py
示例3: handle_request
async def handle_request(request):
urls = request.args.getlist('url')
callback = request.args.get('callback')
if urls:
if len(urls) > 10:
return response.json([{
'ok': False,
'error': 'Max 10 URLs allowed'
}], status=400)
async with aiohttp.ClientSession() as session:
head_infos = await asyncio.gather(*[
head(session, url) for url in urls
])
if callback and is_valid_callback(callback):
return response.text(
'{}({})'.format(callback, json.dumps(head_infos, indent=2)),
content_type='application/javascript',
headers={'Access-Control-Allow-Origin': '*'},
)
else:
return response.json(
head_infos,
headers={'Access-Control-Allow-Origin': '*'},
)
else:
return response.html(INDEX)
开发者ID:simonw,项目名称:json-head,代码行数:26,代码来源:json_head.py
示例4: test_composition_view_runs_methods_as_expected
def test_composition_view_runs_methods_as_expected(app, method):
view = CompositionView()
def first(request):
assert request.stream is None
return text("first method")
view.add(["GET", "POST", "PUT"], first)
view.add(["DELETE", "PATCH"], lambda x: text("second method"))
app.add_route(view, "/")
assert app.is_request_stream is False
if method in ["GET", "POST", "PUT"]:
request, response = getattr(app.test_client, method.lower())("/")
assert response.text == "first method"
response = view(request)
assert response.body.decode() == "first method"
if method in ["DELETE", "PATCH"]:
request, response = getattr(app.test_client, method.lower())("/")
assert response.text == "second method"
response = view(request)
assert response.body.decode() == "second method"
开发者ID:channelcat,项目名称:sanic,代码行数:26,代码来源:test_views.py
示例5: write_response
def write_response(self, response):
if isinstance(response, str):
response = text(response)
self.transport.write(
response.output(self.request.version)
)
self.transport.close()
开发者ID:penelopeia,项目名称:sanic,代码行数:7,代码来源:test_custom_protocol.py
示例6: error_handler
async def error_handler(request, exception):
if request.method in ["HEAD", "PATCH", "PUT", "DELETE"]:
return text(
"", exception.status_code, headers=exception.headers
)
else:
return self.app.error_handler.default(request, exception)
开发者ID:channelcat,项目名称:sanic,代码行数:7,代码来源:testing.py
示例7: post_handler
async def post_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
开发者ID:channelcat,项目名称:sanic,代码行数:8,代码来源:server.py
示例8: handler
def handler(request):
response = text("OK")
response.cookies["test"] = "at you"
response.cookies["test"]["httponly"] = True
response.cookies["test"]["expires"] = datetime.now() + timedelta(
seconds=10
)
return response
开发者ID:channelcat,项目名称:sanic,代码行数:8,代码来源:test_cookies.py
示例9: delete_account
async def delete_account(req, clientid, token, jwt):
async with shared.postgres.transaction():
stmt = await shared.postgres.prepare("DELETE FROM tb_users WHERE userid = $1")
stmt.fetchv(clientid)
await shared.redis.sadd("removed-id", clientid)
return text("ok")
开发者ID:Julien00859,项目名称:Bomberman,代码行数:8,代码来源:auth.py
示例10: post_handler
async def post_handler(request):
assert isinstance(request.stream, StreamBuffer)
result = ""
while True:
body = await request.stream.read()
if body is None:
break
result += body.decode("utf-8")
return text(result)
开发者ID:channelcat,项目名称:sanic,代码行数:9,代码来源:test_request_stream.py
示例11: post_handler
async def post_handler(request):
assert isinstance(request.stream, asyncio.Queue)
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
开发者ID:penelopeia,项目名称:sanic,代码行数:9,代码来源:test_request_stream.py
示例12: health
async def health(request):
""" returns the current health state of the system """
duration = time.time() - LAST_CALL_ROUTE_SERVICES
if duration > settings.args.hangup_detection:
msg = "system hang-up detected, it's been {} seconds since start of "\
"route_services".format(int(duration))
raise sanic.exceptions.ServerError(msg)
return text("OK")
开发者ID:flypenguin,项目名称:python-rancon,代码行数:9,代码来源:__init__.py
示例13: save
async def save(request):
app = request.app
artwork = request.files.getlist("artwork", [])
artwork = [Artwork(f.name, f.type, f.body, None) for f in artwork]
app.processor.cache_art(artwork)
data = json.loads(request.form.get("data"))
app.processor.save_all(data["tracks"], data["options"])
return response.text("")
开发者ID:EvanPurkhiser,项目名称:tunes,代码行数:10,代码来源:importer.py
示例14: update_my_account
async def update_my_account(req, jwt):
allowed_fields = {"nickname", "email"}
fields = allowed_fields & req.json.keys()
if not fields:
logging.warning(f"Unknown fields: {req.json.keys()}")
raise InvalidUsage(f"Autorized fields are {allowed_fields}")
async with shared.postgres.transaction():
sets = ", ".join([f"{field} = ${idx+2}" for idx, field in enumerate(fields)])
stmt = await shared.postgres.prepare(f"UPDATE tb_users SET {sets} WHERE userid = $1")
await stmt.fetch(jwt["id"], *map(lambda field: req.json[field], fields))
return text("ok")
开发者ID:Julien00859,项目名称:Bomberman,代码行数:13,代码来源:auth.py
示例15: update_account
async def update_account(req, clientid, token, jwt):
allowed_fields = {"nickname", "email", "password", "is_verfied", "is_admin"}
fields = allowed_fields & req.json.keys()
if not fields:
logging.warning(f"Unknown fields: {req.json.keys()}")
raise InvalidUsage(f"Autorized fields are {allowed_fields}")
async with shared.postgres.transaction():
sets = " ".join([f"SET {field} = ${idx+2}" for idx, field in enumerate(fields)])
stmt = await shared.postgres.prepare(f"UPDATE FROM tb_users {sets} WHERE userid = $1")
await stmt.fetch(clientid, *map(lambda field: req.json[field], fields))
return text("ok")
开发者ID:Julien00859,项目名称:Bomberman,代码行数:13,代码来源:auth.py
示例16: test_composition_view_rejects_invalid_methods
def test_composition_view_rejects_invalid_methods(app, method):
view = CompositionView()
view.add(["GET", "POST", "PUT"], lambda x: text("first method"))
app.add_route(view, "/")
if method in ["GET", "POST", "PUT"]:
request, response = getattr(app.test_client, method.lower())("/")
assert response.status == 200
assert response.text == "first method"
if method in ["DELETE", "PATCH"]:
request, response = getattr(app.test_client, method.lower())("/")
assert response.status == 405
开发者ID:channelcat,项目名称:sanic,代码行数:14,代码来源:test_views.py
示例17: response
def response(self, request, exception):
"""Fetches and executes an exception handler and returns a response
object
:param request: Instance of :class:`sanic.request.Request`
:param exception: Exception to handle
:type request: :class:`sanic.request.Request`
:type exception: :class:`sanic.exceptions.SanicException` or
:class:`Exception`
:return: Wrap the return value obtained from :func:`default`
or registered handler for that type of exception.
"""
handler = self.lookup(exception)
response = None
try:
if handler:
response = handler(request, exception)
if response is None:
response = self.default(request, exception)
except Exception:
self.log(format_exc())
try:
url = repr(request.url)
except AttributeError:
url = "unknown"
response_message = (
"Exception raised in exception handler " '"%s" for uri: %s'
)
logger.exception(response_message, handler.__name__, url)
if self.debug:
return text(response_message % (handler.__name__, url), 500)
else:
return text("An error occurred while handling an error", 500)
return response
开发者ID:channelcat,项目名称:sanic,代码行数:37,代码来源:handlers.py
示例18: validate
async def validate(req, clientid, token):
if not (await shared.redis.exists(f"users:{clientid}:validation_token")):
logger.log(45, f"No validation token available for user {clientid} (IP: {req.ip})")
raise Forbidden("No validation token available for this account")
validation_token = await (shared.redis.get(f"users:{clientid}:validation_token"))
if not compare_digest(token.encode(), validation_token):
logger.log(45, f"Wrong validation token for user {clientid} (IP: {req.ip})")
raise Forbidden("Wrong validation token")
async with shared.postgres.transaction():
stmt = await shared.postgres.prepare("SELECT set_user_verified($1);")
await stmt.fetch(clientid)
return text("ok")
开发者ID:Julien00859,项目名称:Bomberman,代码行数:15,代码来源:auth.py
示例19: reset
async def reset(req, clientid):
if not (await shared.redis.exists(f"users:{clientid}:reset_token")):
logger.log(45, f"No reset token available for user {clientid} (IP: {req.ip})")
raise Forbidden("No reset token available for this account")
reset_token = await (shared.redis.get(f"users:{clientid}:reset_token"))
if not compare_digest(req.json["token"].encode(), reset_token):
logger.log(45, f"Wrong reset token for user {clientid} (IP: {req.ip})")
raise Forbidden("Wrong reset token")
async with shared.postgres.transaction():
stmt = await shared.postgres.prepare("UPDATE tb_users SET password = $1 WHERE userid = $2")
await stmt.fetch(bcrypt.hashpw(req.json["password"].encode(), bcrypt.gensalt()), clientid)
return text("ok")
开发者ID:Julien00859,项目名称:Bomberman,代码行数:15,代码来源:auth.py
示例20: test_composition_view_rejects_invalid_methods
def test_composition_view_rejects_invalid_methods(method):
app = Sanic('test_composition_view')
view = CompositionView()
view.add(['GET', 'POST', 'PUT'], lambda x: text('first method'))
app.add_route(view, '/')
if method in ['GET', 'POST', 'PUT']:
request, response = getattr(app.test_client, method.lower())('/')
assert response.status == 200
assert response.text == 'first method'
if method in ['DELETE', 'PATCH']:
request, response = getattr(app.test_client, method.lower())('/')
assert response.status == 405
开发者ID:penelopeia,项目名称:sanic,代码行数:16,代码来源:test_views.py
注:本文中的sanic.response.text函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论