def test_websocket_route(app: Sanic): event = asyncio.Event() async def websocket_handler(request, ws): assert ws.subprotocol is None event.set() bp = Blueprint(name="handler", url_prefix="/ws") bp.add_websocket_route(websocket_handler, "/test", name="test") app.blueprint(bp) _, response = app.test_client.get("/ws/test", headers={ 'Upgrade': 'websocket', 'Connection': 'upgrade', 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Version': '13' }) assert response.status == 101 assert event.is_set()
def test_versioned_routes_get(method): app = Sanic('test_shorhand_routes_get') bp = Blueprint('test_text') method = method.lower() func = getattr(bp, method) if callable(func): @func('/{}'.format(method), version=1) def handler(request): return text('OK') else: print(func) raise app.blueprint(bp) client_method = getattr(app.test_client, method) request, response = client_method('/v1/{}'.format(method)) assert response.status == 200
def test_shorthand_named_routes_get(app): bp = Blueprint("test_bp", url_prefix="/bp") @app.get("/get", name="route_get") def handler(request): return text("OK") @bp.get("/get", name="route_bp") def handler2(request): return text("Blueprint") app.blueprint(bp) assert app.router.routes_all["/get"].name == "route_get" assert app.url_for("route_get") == "/get" with pytest.raises(URLBuildError): app.url_for("handler") assert app.router.routes_all["/bp/get"].name == "test_bp.route_bp" assert app.url_for("test_bp.route_bp") == "/bp/get" with pytest.raises(URLBuildError): app.url_for("test_bp.handler2")
def test_static_blueprint_name(app: Sanic, static_file_directory, file_name): current_file = inspect.getfile(inspect.currentframe()) with open(current_file, 'rb') as file: current_file_contents = file.read() bp = Blueprint(name="static", url_prefix="/static", strict_slashes=False) bp.static("/test.file/", get_file_path(static_file_directory, file_name), name="static.testing", strict_slashes=True) app.blueprint(bp) uri = app.url_for('static', name='static.testing') assert uri == "/static/test.file" _, response = app.test_client.get("/static/test.file") assert response.status == 404 _, response = app.test_client.get("/static/test.file/") assert response.status == 200
def test_shorthand_named_routes_get(app): bp = Blueprint('test_bp', url_prefix='/bp') @app.get('/get', name='route_get') def handler(request): return text('OK') @bp.get('/get', name='route_bp') def handler2(request): return text('Blueprint') app.blueprint(bp) assert app.router.routes_all['/get'].name == 'route_get' assert app.url_for('route_get') == '/get' with pytest.raises(URLBuildError): app.url_for('handler') assert app.router.routes_all['/bp/get'].name == 'test_bp.route_bp' assert app.url_for('test_bp.route_bp') == '/bp/get' with pytest.raises(URLBuildError): app.url_for('test_bp.handler2')
def test_versioned_routes_get(app, method): bp = Blueprint("test_text") method = method.lower() func = getattr(bp, method) if callable(func): @func(f"/{method}", version=1) def handler(request): return text("OK") else: print(func) raise Exception(f"{func} is not callable") app.blueprint(bp) client_method = getattr(app.test_client, method) request, response = client_method(f"/v1/{method}") assert response.status == 200
def sanic_app(elasticapm_client): app = Sanic(name="elastic-apm") apm = ElasticAPM(app=app, client=elasticapm_client) TestManager(app=app) bp = Blueprint(name="test", url_prefix="/apm", version="v1") @app.exception(Exception) def handler(request, exception): return json({"response": str(exception)}, 500) @bp.post("/unhandled-exception") async def raise_something(request): raise CustomException("Unhandled") @app.route("/", methods=["GET", "POST"]) def default_route(request: Request): with async_capture_span("test"): pass return json({"response": "ok"}) @app.get("/greet/<name:str>") async def greet_person(request: Request, name: str): return json({"response": f"Hello {name}"}) @app.get("/capture-exception") async def capture_exception(request): try: 1 / 0 except ZeroDivisionError: await apm.capture_exception() return json({"response": "invalid"}, 500) app.blueprint(blueprint=bp) try: yield app finally: elasticapm.uninstrument()
def test_bp_middleware_order(app): blueprint = Blueprint("test_bp_middleware_order") order = list() @blueprint.middleware("request") def mw_1(request): order.append(1) @blueprint.middleware("request") def mw_2(request): order.append(2) @blueprint.middleware("request") def mw_3(request): order.append(3) @blueprint.middleware("response") def mw_4(request, response): order.append(6) @blueprint.middleware("response") def mw_5(request, response): order.append(5) @blueprint.middleware("response") def mw_6(request, response): order.append(4) @blueprint.route("/") def process_response(request): return text("OK") app.blueprint(blueprint) order.clear() request, response = app.test_client.get("/") assert response.status == 200 assert order == [1, 2, 3, 4, 5, 6]
def test_versioned_named_routes_get(app, method): bp = Blueprint('test_bp', url_prefix='/bp') method = method.lower() route_name = 'route_{}'.format(method) route_name2 = 'route2_{}'.format(method) func = getattr(app, method) if callable(func): @func('/{}'.format(method), version=1, name=route_name) def handler(request): return text('OK') else: print(func) raise func = getattr(bp, method) if callable(func): @func('/{}'.format(method), version=1, name=route_name2) def handler2(request): return text('OK') else: print(func) raise app.blueprint(bp) assert app.router.routes_all['/v1/{}'.format(method)].name == route_name route = app.router.routes_all['/v1/bp/{}'.format(method)] assert route.name == 'test_bp.{}'.format(route_name2) assert app.url_for(route_name) == '/v1/{}'.format(method) url = app.url_for('test_bp.{}'.format(route_name2)) assert url == '/v1/bp/{}'.format(method) with pytest.raises(URLBuildError): app.url_for('handler')
def test_route_handler_add(app: Sanic): view = CompositionView() async def get_handler(request): return json({"response": "OK"}) view.add(["GET"], get_handler, stream=False) async def default_handler(request): return text("OK") bp = Blueprint(name="handler", url_prefix="/handler") bp.add_route(default_handler, uri="/default/", strict_slashes=True) bp.add_route(view, uri="/view", name="test") app.blueprint(bp) _, response = app.test_client.get("/handler/default/") assert response.text == "OK" _, response = app.test_client.get("/handler/view") assert response.json["response"] == "OK"
def test_bp_with_host(): app = Sanic('test_bp_host') bp = Blueprint('test_bp_host', url_prefix='/test1', host="example.com") @bp.route('/') def handler(request): return text('Hello') @bp.route('/', host="sub.example.com") def handler(request): return text('Hello subdomain!') app.blueprint(bp) headers = {"Host": "example.com"} request, response = sanic_endpoint_test(app, uri='/test1/', headers=headers) assert response.text == 'Hello' headers = {"Host": "sub.example.com"} request, response = sanic_endpoint_test(app, uri='/test1/', headers=headers) assert response.text == 'Hello subdomain!'
def test_static_head_request(file_name, static_file_directory): app = Sanic('test_static') app.static('/testing.file', get_file_path(static_file_directory, file_name), use_content_range=True) bp = Blueprint('test_bp_static', url_prefix='/bp') bp.static('/testing.file', get_file_path(static_file_directory, file_name), use_content_range=True) app.blueprint(bp) uri = app.url_for('static') assert uri == '/testing.file' assert uri == app.url_for('static', name='static') assert uri == app.url_for('static', name='static', filename='any') request, response = app.test_client.head(uri) assert response.status == 200 assert 'Accept-Ranges' in response.headers assert 'Content-Length' in response.headers assert int(response.headers['Content-Length']) == len( get_file_content(static_file_directory, file_name)) # blueprint uri = app.url_for('static', name='test_bp_static.static') assert uri == '/bp/testing.file' assert uri == app.url_for('static', name='test_bp_static.static', filename='any') request, response = app.test_client.head(uri) assert response.status == 200 assert 'Accept-Ranges' in response.headers assert 'Content-Length' in response.headers assert int(response.headers['Content-Length']) == len( get_file_content(static_file_directory, file_name))
def create_app(): app = Sanic(DEFAULT_SERVICE_NAME) api_prefix = f'/{DEFAULT_SERVICE_NAME}' api = Blueprint('warehouse', url_prefix=api_prefix) api.add_route(SmokeResource.as_view(), "/smoke") api.add_route(ClientAllResource().as_view(), "/client") api.add_route(ClientResource().as_view(), "/client/<client_id>") api.add_route(ParcelTypeAllResource().as_view(), "/parceltype") api.add_route(ParcelTypeResource().as_view(), "/parceltype/<type_id>") api.add_route(StorageAllResource().as_view(), "/storage") api.add_route(StorageResource().as_view(), "/storage/<storage_id>") api.add_route(ParcelAllResource().as_view(), "/parcel") api.add_route(ParcelResource().as_view(), "/parcel/<parcel_id>") api.add_route(ParcelQueryResource().as_view(), "/parcel/<parcel_type>/<storage_id>") api.add_route(ParcelReportResource().as_view(), "/parcel/report") api.add_route(SupplyAllResource().as_view(), "/supply") api.add_route(SupplyResource().as_view(), "/supply/<supply_id>") app.blueprint(api) return app
def test_bp_with_host(app): bp = Blueprint('test_bp_host', url_prefix='/test1', host="example.com") @bp.route('/') def handler(request): return text('Hello') @bp.route('/', host="sub.example.com") def handler(request): return text('Hello subdomain!') app.blueprint(bp) headers = {"Host": "example.com"} request, response = app.test_client.get( '/test1/', headers=headers) assert response.text == 'Hello' headers = {"Host": "sub.example.com"} request, response = app.test_client.get( '/test1/', headers=headers) assert response.text == 'Hello subdomain!'
def test_request_stream(app): """test for complex application""" bp = Blueprint("test_blueprint_request_stream") class SimpleView(HTTPMethodView): def get(self, request): assert request.stream is None return text("OK") @stream_decorator async def post(self, 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) @app.post("/stream", stream=True) async def 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) @app.get("/get") async def get(request): assert request.stream is None return text("OK") @bp.post("/bp_stream", stream=True) async def bp_stream(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) @bp.get("/bp_get") async def bp_get(request): assert request.stream is None return text("OK") def get_handler(request): assert request.stream is None return text("OK") 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) app.add_route(SimpleView.as_view(), "/method_view") view = CompositionView() view.add(["GET"], get_handler) view.add(["POST"], post_handler, stream=True) app.blueprint(bp) app.add_route(view, "/composition_view") assert app.is_request_stream is True request, response = app.test_client.get("/method_view") assert response.status == 200 assert response.text == "OK" request, response = app.test_client.post("/method_view", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.get("/composition_view") assert response.status == 200 assert response.text == "OK" request, response = app.test_client.post("/composition_view", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.get("/get") assert response.status == 200 assert response.text == "OK" request, response = app.test_client.post("/stream", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.get("/bp_get") assert response.status == 200 assert response.text == "OK" request, response = app.test_client.post("/bp_stream", data=data) assert response.status == 200 assert response.text == data
def test_request_stream_blueprint(app): """for self.is_request_stream = True""" bp = Blueprint("test_blueprint_request_stream_blueprint") @app.get("/get") async def get(request): assert request.stream is None return text("GET") @bp.head("/head") async def head(request): assert request.stream is None return text("HEAD") @bp.delete("/delete") async def delete(request): assert request.stream is None return text("DELETE") @bp.options("/options") async def options(request): assert request.stream is None return text("OPTIONS") @bp.post("/_post/<id>") async def _post(request, id): assert request.stream is None return text("_POST") @bp.post("/post/<id>", stream=True) async def post(request, id): 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) @bp.put("/_put") async def _put(request): assert request.stream is None return text("_PUT") @bp.put("/put", stream=True) async def put(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) @bp.patch("/_patch") async def _patch(request): assert request.stream is None return text("_PATCH") @bp.patch("/patch", stream=True) async def patch(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) async def post_add_route(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) bp.add_route(post_add_route, "/post/add_route", methods=["POST"], stream=True) app.blueprint(bp) assert app.is_request_stream is True request, response = app.test_client.get("/get") assert response.status == 200 assert response.text == "GET" request, response = app.test_client.head("/head") assert response.status == 200 assert response.text == "" request, response = app.test_client.delete("/delete") assert response.status == 200 assert response.text == "DELETE" request, response = app.test_client.options("/options") assert response.status == 200 assert response.text == "OPTIONS" request, response = app.test_client.post("/_post/1", data=data) assert response.status == 200 assert response.text == "_POST" request, response = app.test_client.post("/post/1", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.put("/_put", data=data) assert response.status == 200 assert response.text == "_PUT" request, response = app.test_client.put("/put", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.patch("/_patch", data=data) assert response.status == 200 assert response.text == "_PATCH" request, response = app.test_client.patch("/patch", data=data) assert response.status == 200 assert response.text == data request, response = app.test_client.post("/post/add_route", data=data) assert response.status == 200 assert response.text == data
import os import re from itertools import repeat from sanic.blueprints import Blueprint from sanic.response import json, redirect from sanic.views import CompositionView from .doc import RouteSpec, definitions from .doc import route as doc_route from .doc import route_specs, serialize_schema swagger_blueprint = Blueprint("swagger", url_prefix="/swagger") dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.abspath(dir_path + "/ui") # Redirect "/swagger" to "/swagger/" @swagger_blueprint.route("", strict_slashes=True) def index(request): return redirect("{}/".format(swagger_blueprint.url_prefix)) swagger_blueprint.static("/", dir_path + "/index.html", strict_slashes=True) swagger_blueprint.static("/", dir_path) _spec = {} # Removes all null values from a dictionary
import re from itertools import repeat from sanic.blueprints import Blueprint from sanic.response import json from sanic.views import CompositionView from .doc import route_specs, RouteSpec, serialize_schema, definitions blueprint = Blueprint('openapi', url_prefix='openapi') _spec = {} # Removes all null values from a dictionary def remove_nulls(dictionary, deep=True): return { k: remove_nulls(v, deep) if deep and type(v) is dict else v for k, v in dictionary.items() if v is not None } @blueprint.listener('before_server_start') def build_spec(app, loop): _spec['swagger'] = '2.0' _spec['info'] = { "version": getattr(app.config, 'API_VERSION', '1.0.0'), "title": getattr(app.config, 'API_TITLE', 'API'), "description": getattr(app.config, 'API_DESCRIPTION', ''), "termsOfService": getattr(app.config, 'API_TERMS_OF_SERVICE', None), "contact": {
from sanic_restful import Api from sanic.blueprints import Blueprint from . import healthcheck health_bp = Blueprint(__name__, url_prefix='/health') health_api = Api(health_bp) health_api.add_resource(healthcheck.HealthStatusResource, '/status')
from sanic import Sanic from sanic.blueprints import Blueprint from sanic.response import json from sanic_jwt import Initialize async def authenticate(request, *args, **kwargs): return {"user_id": 1} blueprint = Blueprint("Test") app = Sanic() sanicjwt = Initialize(blueprint, app=app, authenticate=authenticate) @blueprint.get("/", strict_slashes=True) @sanicjwt.protected() def protected_hello_world(request): return json({"message": "hello world"}) @blueprint.get("/user/<id>", strict_slashes=True) @sanicjwt.protected(authorization_header="foobar") def protected_user(request, id): return json({"user": id}) @blueprint.route("/scoped_empty") @sanicjwt.scoped("something") async def scoped(request):
def test_bp_shorthand(): app = Sanic('test_shorhand_routes') blueprint = Blueprint('test_shorhand_routes') ev = asyncio.Event() @blueprint.get('/get') def handler(request): assert request.stream is None return text('OK') @blueprint.put('/put') def handler(request): assert request.stream is None return text('OK') @blueprint.post('/post') def handler(request): assert request.stream is None return text('OK') @blueprint.head('/head') def handler(request): assert request.stream is None return text('OK') @blueprint.options('/options') def handler(request): assert request.stream is None return text('OK') @blueprint.patch('/patch') def handler(request): assert request.stream is None return text('OK') @blueprint.delete('/delete') def handler(request): assert request.stream is None return text('OK') @blueprint.websocket('/ws') async def handler(request, ws): assert request.stream is None ev.set() app.blueprint(blueprint) assert app.is_request_stream is False request, response = app.test_client.get('/get') assert response.text == 'OK' request, response = app.test_client.post('/get') assert response.status == 405 request, response = app.test_client.put('/put') assert response.text == 'OK' request, response = app.test_client.get('/post') assert response.status == 405 request, response = app.test_client.post('/post') assert response.text == 'OK' request, response = app.test_client.get('/post') assert response.status == 405 request, response = app.test_client.head('/head') assert response.status == 200 request, response = app.test_client.get('/head') assert response.status == 405 request, response = app.test_client.options('/options') assert response.text == 'OK' request, response = app.test_client.get('/options') assert response.status == 405 request, response = app.test_client.patch('/patch') assert response.text == 'OK' request, response = app.test_client.get('/patch') assert response.status == 405 request, response = app.test_client.delete('/delete') assert response.text == 'OK' request, response = app.test_client.get('/delete') assert response.status == 405 request, response = app.test_client.get('/ws', headers={ 'Upgrade': 'websocket', 'Connection': 'upgrade', 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', 'Sec-WebSocket-Version': '13'}) assert response.status == 101 assert ev.is_set()
def test_bp_group(app: Sanic): blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1") blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2") @blueprint_1.route("/") def blueprint_1_default_route(request): return text("BP1_OK") @blueprint_2.route("/") def blueprint_2_default_route(request): return text("BP2_OK") blueprint_group_1 = Blueprint.group( blueprint_1, blueprint_2, url_prefix="/bp" ) blueprint_3 = Blueprint("blueprint_3", url_prefix="/bp3") @blueprint_group_1.middleware("request") def blueprint_group_1_middleware(request): global MIDDLEWARE_INVOKE_COUNTER MIDDLEWARE_INVOKE_COUNTER["request"] += 1 @blueprint_group_1.middleware def blueprint_group_1_middleware_not_called(request): global MIDDLEWARE_INVOKE_COUNTER MIDDLEWARE_INVOKE_COUNTER["request"] += 1 @blueprint_3.route("/") def blueprint_3_default_route(request): return text("BP3_OK") blueprint_group_2 = Blueprint.group( blueprint_group_1, blueprint_3, url_prefix="/api" ) @blueprint_group_2.middleware("response") def blueprint_group_2_middleware(request, response): global MIDDLEWARE_INVOKE_COUNTER MIDDLEWARE_INVOKE_COUNTER["response"] += 1 app.blueprint(blueprint_group_2) @app.route("/") def app_default_route(request): return text("APP_OK") _, response = app.test_client.get("/") assert response.text == "APP_OK" _, response = app.test_client.get("/api/bp/bp1") assert response.text == "BP1_OK" _, response = app.test_client.get("/api/bp/bp2") assert response.text == "BP2_OK" _, response = app.test_client.get("/api/bp3") assert response.text == "BP3_OK" assert MIDDLEWARE_INVOKE_COUNTER["response"] == 3 assert MIDDLEWARE_INVOKE_COUNTER["request"] == 4
def test_bp_group_with_additional_route_params(app: Sanic): blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1") blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2") @blueprint_1.route( "/request_path", methods=frozenset({"PUT", "POST"}), version=2 ) def blueprint_1_v2_method_with_put_and_post(request: Request): if request.method == "PUT": return text("PUT_OK") elif request.method == "POST": return text("POST_OK") @blueprint_2.route( "/route/<param>", methods=frozenset({"DELETE", "PATCH"}), name="test" ) def blueprint_2_named_method(request: Request, param): if request.method == "DELETE": return text(f"DELETE_{param}") elif request.method == "PATCH": return text(f"PATCH_{param}") blueprint_group = Blueprint.group( blueprint_1, blueprint_2, url_prefix="/api" ) @blueprint_group.middleware("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) @blueprint_group.middleware("response") def enhance_response_middleware(request: Request, response: HTTPResponse): response.headers.add("x-test-middleware", "value") app.blueprint(blueprint_group) header = {"authorization": " ".join(["Basic", AUTH])} _, response = app.test_client.put( "/v2/api/bp1/request_path", headers=header ) assert response.text == "PUT_OK" assert response.headers.get("x-test-middleware") == "value" _, response = app.test_client.post( "/v2/api/bp1/request_path", headers=header ) assert response.text == "POST_OK" _, response = app.test_client.delete("/api/bp2/route/bp2", headers=header) assert response.text == "DELETE_bp2" _, response = app.test_client.patch("/api/bp2/route/bp2", headers=header) assert response.text == "PATCH_bp2" _, response = app.test_client.put("/v2/api/bp1/request_path") assert response.status == 401
from sanic import Sanic from sanic.views import CompositionView from sanic.views import HTTPMethodView from sanic.views import stream as stream_decorator from sanic.blueprints import Blueprint from sanic.response import stream, text bp = Blueprint('blueprint_request_stream') app = Sanic('request_stream') ''' Sanic允许通过流获得请求数据,如下所示。 当请求结束时,request.stream.get()返回None。只有post、put和补丁修饰器才有流参数。 ''' class SimpleView(HTTPMethodView): @stream_decorator async def post(self, request): result = '' while True: body = await request.stream.get() if body is None: break result += body.decode('utf-8') return text(result) @app.post('/stream', stream=True) async def handler(request): async def streaming(response): while True:
def test_bp_shorthand(app): blueprint = Blueprint("test_shorhand_routes") ev = asyncio.Event() @blueprint.get("/get") def handler(request): assert request.stream is None return text("OK") @blueprint.put("/put") def put_handler(request): assert request.stream is None return text("OK") @blueprint.post("/post") def post_handler(request): assert request.stream is None return text("OK") @blueprint.head("/head") def head_handler(request): assert request.stream is None return text("OK") @blueprint.options("/options") def options_handler(request): assert request.stream is None return text("OK") @blueprint.patch("/patch") def patch_handler(request): assert request.stream is None return text("OK") @blueprint.delete("/delete") def delete_handler(request): assert request.stream is None return text("OK") @blueprint.websocket("/ws/", strict_slashes=True) async def websocket_handler(request, ws): assert request.stream is None ev.set() app.blueprint(blueprint) assert app.is_request_stream is False request, response = app.test_client.get("/get") assert response.text == "OK" request, response = app.test_client.post("/get") assert response.status == 405 request, response = app.test_client.put("/put") assert response.text == "OK" request, response = app.test_client.get("/post") assert response.status == 405 request, response = app.test_client.post("/post") assert response.text == "OK" request, response = app.test_client.get("/post") assert response.status == 405 request, response = app.test_client.head("/head") assert response.status == 200 request, response = app.test_client.get("/head") assert response.status == 405 request, response = app.test_client.options("/options") assert response.text == "OK" request, response = app.test_client.get("/options") assert response.status == 405 request, response = app.test_client.patch("/patch") assert response.text == "OK" request, response = app.test_client.get("/patch") assert response.status == 405 request, response = app.test_client.delete("/delete") assert response.text == "OK" request, response = app.test_client.get("/delete") assert response.status == 405 request, response = app.test_client.websocket("/ws/") assert response.opened is True assert ev.is_set()
from sanic.views import HTTPMethodView from ManjiApi.sanic import ManjiApiRequest from sanic.blueprints import Blueprint from sanic.response import HTTPResponse, json skill_skill = Blueprint("skill_skill", url_prefix="/skill") class SkillSkillView(HTTPMethodView): async def get(self, request: ManjiApiRequest, num: int) -> HTTPResponse: if skill_info := await request.app.ctx.framedata_request.get_skill_by_num( num): return json({"status": 200, **skill_info}) return request.app.ctx.response.not_found skill_skill.add_route(SkillSkillView.as_view(), "/<num:int>")
def test_decorators_override_configuration_defaults(): blueprint = Blueprint("Test") app = Sanic() sanicjwt = Initialize( blueprint, app=app, authenticate=authenticate, scopes_enabled=True, retrieve_user=authenticate, add_scopes_to_payload=my_scope_extender, ) @blueprint.get("/protected") @protected(blueprint, verify_exp=False) def protected_hello_world(request): return json({"message": "hello world"}) @blueprint.route("/scoped") @sanicjwt.scoped("user", authorization_header="foobar") async def scoped_endpoint(request): return json({"scoped": True}) app.blueprint(blueprint, url_prefix="/test") _, response = app.test_client.post("/test/auth", json={ "username": "******", "password": "******" }) access_token = response.json.get(sanicjwt.config.access_token_name(), None) payload = jwt.decode(access_token, sanicjwt.config.secret()) exp = payload.get("exp", None) assert "exp" in payload exp = datetime.utcfromtimestamp(exp) with freeze_time(datetime.utcnow() + timedelta(seconds=(60 * 35))): assert isinstance(exp, datetime) assert datetime.utcnow() > exp _, response = app.test_client.get( "/test/protected", headers={"Authorization": "Bearer {}".format(access_token)}, ) assert response.status == 200 _, response = app.test_client.get( "/test/scoped", headers={"FudgeBar": "Bearer {}".format(access_token)}) assert response.status == 401 assert "Authorization header not present." in response.json.get("reasons") assert response.json.get("exception") == "Unauthorized" _, response = app.test_client.get( "/test/scoped", headers={"Foobar": "Bear {}".format(access_token)}) assert response.status == 401 assert "Authorization header is invalid." in response.json.get("reasons") assert response.json.get("exception") == "Unauthorized" _, response = app.test_client.get( "/test/scoped", headers={"Foobar": "Bearer {}".format(access_token)}) assert response.status == 403 assert "Invalid scope." in response.json.get("reasons") assert response.json.get("exception") == "Unauthorized"
from sanic import Sanic from sanic.blueprints import Blueprint from sanic.response import json from sanic_jwt import Initialize from sanic_jwt.decorators import protected blueprint = Blueprint('Test', '/test') @blueprint.get("/", strict_slashes=True) @protected() def protected_hello_world(request): return json({'message': 'hello world'}) async def authenticate(request, *args, **kwargs): return {'user_id': 1} app = Sanic() app.blueprint(blueprint) sanicjwt = Initialize( app, authenticate=authenticate, ) def test_protected_blueprint(): _, response = app.test_client.get('/test/')
from sanic.blueprints import Blueprint from sanic.response import json from sanic.views import HTTPMethodView from sanic_openapi import doc blueprint = Blueprint('Class-based View', url_prefix='/class-based-view') class MyView(HTTPMethodView): @doc.summary("Get my view") def get(self, request): return json({"method": "GET"}) @doc.summary("Post my view") @doc.consumes({"view": {"name": str}}, location="body") def post(self, request): return json({"method": "POST"}) blueprint.add_route(MyView.as_view(), '/view', strict_slashes=True)
def test_bp_group_as_list(): blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1") blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2") blueprint_group_1 = Blueprint.group([blueprint_1, blueprint_2]) assert len(blueprint_group_1) == 2