本文整理汇总了Python中sanic.response.text函数的典型用法代码示例。如果您正苦于以下问题:Python text函数的具体用法?Python text怎么用?Python text使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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)
示例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"
示例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()
示例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)
示例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)
示例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
示例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")
示例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)
示例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)
示例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")
示例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("")
示例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")
示例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")