本文整理汇总了Python中sanic.response.raw方法的典型用法代码示例。如果您正苦于以下问题:Python response.raw方法的具体用法?Python response.raw怎么用?Python response.raw使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sanic.response
的用法示例。
在下文中一共展示了response.raw方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_all_callbacks
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def get_all_callbacks(request, user):
if user['auth'] not in ['access_token', 'apitoken']:
abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
if user['current_operation'] != "":
query = await db_model.operation_query()
operation = await db_objects.get(query, name=user['current_operation'])
query = await db_model.callback_query()
callbacks = await db_objects.execute(query.where(Callback.operation == operation))
return json([c.to_json() for c in callbacks])
else:
return json([])
# format of cached_keys:
# {
# "UUID": raw key
# }
示例2: get_agent_message
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def get_agent_message(request):
# get the raw data first
if request.body != b'':
data = request.body
#print("Body: " + str(data))
elif len(request.cookies) != 0:
keys = request.cookies.items()
data = request.cookies[keys[0]]
#print("Cookies: " + str(data))
elif len(request.query_args) != 0:
data = urllib.parse.unquote(request.query_args[0][1])
#print("Query: " + str(data))
else:
logger.exception("Failed to find data for an agent message")
return raw(b'', 404)
return text(await parse_agent_message(data, request), 200)
示例3: get_mbtiles
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def get_mbtiles(request, z, x, y):
# Flip Y coordinate because MBTiles store tiles in TMS.
coords = (x, (1 << z) - 1 - y, z)
cursor = Config.db_sqlite.execute("""
SELECT tile_data
FROM tiles
WHERE tile_column=? and tile_row=? and zoom_level=?
LIMIT 1 """, coords)
tile = cursor.fetchone()
if tile:
return response.raw(
tile[0],
headers={"Content-Type": "application/x-protobuf",
"Content-Encoding": "gzip"})
else:
return response.raw(b'',
headers={"Content-Type": "application/x-protobuf"})
示例4: expose_endpoint
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def expose_endpoint(self):
"""
Expose /metrics endpoint on the same Sanic server.
This may be useful if Sanic is launched from a container
and you do not want to expose more than one port for some
reason.
"""
@self._app.route(self._metrics_path, methods=['GET'])
async def expose_metrics(request):
return raw(self._get_metrics_data(),
content_type=CONTENT_TYPE_LATEST)
示例5: _version_view
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def _version_view(self, request):
"""
View that returns the contents of version.json or a 404.
"""
version_json = self._version_callback(self.version_path)
if isawaitable(version_json):
version_json = await version_json
if version_json is None:
return response.raw(b"version.json not found", 404)
else:
return response.json(version_json)
示例6: _lbheartbeat_view
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def _lbheartbeat_view(self, request):
"""
Lets the load balancer know the application is running and available.
Must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return response.raw(b"", 200)
示例7: version_callback
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def version_callback(self, func):
"""
A decorator to optionally register a new Dockerflow version callback
and use that instead of the default of
:func:`dockerflow.version.get_version`.
The callback will be passed the value of the
``version_path`` parameter to the Dockerflow extension object,
which defaults to the parent directory of the Sanic app's root path.
The callback should return a dictionary with the
version information as defined in the Dockerflow spec,
or None if no version information could be loaded.
E.g.::
import aiofiles
app = Sanic(__name__)
dockerflow = Dockerflow(app)
@dockerflow.version_callback
async def my_version(root):
path = os.path.join(root, 'acme_version.json')
async with aiofiles.open(path, mode='r') as f:
raw = await f.read()
return json.loads(raw)
"""
self._version_callback = func
示例8: app
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def app():
app = Sanic("dockerflow")
@app.route("/")
async def root(request):
if request.body:
raise ValueError(request.body.decode())
return response.raw(b"")
return app
示例9: download_zipped_files
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def download_zipped_files(request, user):
if user['auth'] not in ['access_token', 'apitoken']:
abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
try:
data = request.json
if 'files' not in data:
return abort(404, "missing 'files' value")
# need to make aa temporary directory, copy all the files there, zip it, return that and clean up temp dir
temp_id = str(uuid.uuid4())
query = await db_model.operation_query()
operation = await db_objects.get(query, name=user['current_operation'])
working_dir = "./app/payloads/operations/{}/{}/".format(operation.name, str(uuid.uuid4()))
os.makedirs(working_dir, exist_ok=True)
query = await db_model.filemeta_query()
for file_id in data['files']:
try:
cur_file = await db_objects.get(query, agent_file_id=file_id, operation=operation)
shutil.copy(cur_file.path, working_dir + os.path.basename(cur_file.path))
except Exception as e:
print(str(e))
shutil.make_archive("./app/payloads/operations/{}/{}".format(operation.name, temp_id), 'zip', working_dir)
zip_data = open("./app/payloads/operations/{}/{}.zip".format(operation.name, temp_id), 'rb').read()
os.remove("./app/payloads/operations/{}/{}.zip".format(operation.name, temp_id))
shutil.rmtree(working_dir)
return raw(base64.b64encode(zip_data))
except Exception as e:
print(str(e))
return json({'status': 'error', 'error': 'failed to process request'})
示例10: get_tile_tm2
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def get_tile_tm2(request, x, y, z):
"""
"""
scale_denominator = zoom_to_scale_denom(z)
# compute mercator bounds
bounds = mercantile.xy_bounds(x, y, z)
bbox = f"st_makebox2d(st_point({bounds.left}, {bounds.bottom}), st_point({bounds.right},{bounds.top}))"
sql = Config.tm2query.format(
bbox=bbox,
scale_denominator=scale_denominator,
pixel_width=256,
pixel_height=256,
)
logger.debug(sql)
async with Config.db_pg.acquire() as conn:
# join tiles into one bytes string except null tiles
rows = await conn.fetch(sql)
pbf = b''.join([row[0] for row in rows if row[0]])
return response.raw(
pbf,
headers={"Content-Type": "application/x-protobuf"}
)
示例11: get_tile_postgis
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def get_tile_postgis(request, x, y, z, layer):
"""
Direct access to a postgis layer
"""
if ' ' in layer:
return response.text('bad layer name: {}'.format(layer), status=404)
# get fields given in parameters
fields = ',' + request.raw_args['fields'] if 'fields' in request.raw_args else ''
# get geometry column name from query args else geom is used
geom = request.raw_args.get('geom', 'geom')
# compute mercator bounds
bounds = mercantile.xy_bounds(x, y, z)
# make bbox for filtering
bbox = f"st_setsrid(st_makebox2d(st_point({bounds.left}, {bounds.bottom}), st_point({bounds.right},{bounds.top})), {OUTPUT_SRID})"
# compute pixel resolution
scale = resolution(z)
sql = single_layer.format(**locals(), OUTPUT_SRID=OUTPUT_SRID)
logger.debug(sql)
async with Config.db_pg.acquire() as conn:
rows = await conn.fetch(sql)
pbf = b''.join([row[0] for row in rows if row[0]])
return response.raw(
pbf,
headers={"Content-Type": "application/x-protobuf"}
)
示例12: register
# 需要导入模块: from sanic import response [as 别名]
# 或者: from sanic.response import raw [as 别名]
def register(self) -> None:
"""Register the metrics monitor with the Sanic application.
This adds the metrics endpoint as well as setting up various metrics
collectors.
"""
@self.app.middleware('request')
async def before_request(request: Request) -> None:
request[self._req_start_time] = time.time()
@self.app.middleware('response')
async def before_response(request: Request, response: HTTPResponse) -> None:
latency = time.time() - request[self._req_start_time]
# WebSocket handler ignores response logic, so default
# to a 200 response in such case.
code = response.status if response else 200
labels = (request.method, request.uri_template, request.path, code, request.ip)
if request.path != '/metrics':
self.http_req_latency.labels(*labels).observe(latency)
self.http_req_count.labels(*labels).inc()
# We cannot use Content-Length header since that has not yet been
# calculated and added to the response headers.
#
# Streaming responses do not have a 'body' attribute, so we cannot
# collect this data in those cases.
if hasattr(response, 'body') and response.body is not None:
self.http_resp_bytes.labels(*labels).inc(len(response.body))
@self.app.route('/metrics', methods=['GET'])
async def metrics(_) -> HTTPResponse:
return raw(
generate_latest(core.REGISTRY),
content_type=CONTENT_TYPE_LATEST,
)