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_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"] == 4 assert MIDDLEWARE_INVOKE_COUNTER["request"] == 4
def test_with_bp_with_url_prefix(app): bp = Blueprint("test_text", url_prefix="/test1") class DummyView(HTTPMethodView): def get(self, request): return text("I am get method") bp.add_route(DummyView.as_view(), "/") app.blueprint(bp) request, response = app.test_client.get("/test1/") assert response.text == "I am get method"
def test_bp_static(app): current_file = inspect.getfile(inspect.currentframe()) with open(current_file, "rb") as file: current_file_contents = file.read() blueprint = Blueprint("test_static") blueprint.static("/testing.file", current_file) app.blueprint(blueprint) request, response = app.test_client.get("/testing.file") assert response.status == 200 assert response.body == current_file_contents
def test_with_bp_with_url_prefix(): app = Sanic('test_with_bp_with_url_prefix') bp = Blueprint('test_text', url_prefix='/test1') class DummyView(HTTPMethodView): def get(self, request): return text('I am get method') bp.add_route(DummyView.as_view(), '/') app.blueprint(bp) request, response = sanic_endpoint_test(app, uri='/test1/') assert response.text == 'I am get method'
def test_bp_static(): current_file = inspect.getfile(inspect.currentframe()) with open(current_file, 'rb') as file: current_file_contents = file.read() app = Sanic('test_static') blueprint = Blueprint('test_static') blueprint.static('/testing.file', current_file) app.blueprint(blueprint) request, response = sanic_endpoint_test(app, uri='/testing.file') assert response.status == 200 assert response.body == current_file_contents
def test_with_bp(app): bp = Blueprint("test_text") class DummyView(HTTPMethodView): def get(self, request): assert request.stream is None return text("I am get method") bp.add_route(DummyView.as_view(), "/") app.blueprint(bp) request, response = app.test_client.get("/") assert app.is_request_stream is False assert response.text == "I am get method"
def test_bp_group_list_operations(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_2", url_prefix="/bp3") @blueprint_3.route("/second") def blueprint_3_second_route(request): return text("BP3_OK") assert len(blueprint_group_1) == 2 blueprint_group_1.append(blueprint_3) assert len(blueprint_group_1) == 3 del blueprint_group_1[2] assert len(blueprint_group_1) == 2 blueprint_group_1[1] = blueprint_3 assert len(blueprint_group_1) == 2 assert blueprint_group_1.url_prefix == "/bp"
def test_with_bp(): app = Sanic('test_with_bp') bp = Blueprint('test_text') class DummyView(HTTPMethodView): def get(self, request): assert request.stream is None return text('I am get method') bp.add_route(DummyView.as_view(), '/') app.blueprint(bp) request, response = app.test_client.get('/') assert app.is_request_stream is False assert response.text == 'I am get method'
def test_bp_group_with_default_url_prefix(app): from sanic.response import json bp_resources = Blueprint("bp_resources") @bp_resources.get("/") def list_resources_handler(request): resource = {} return json([resource]) bp_resource = Blueprint("bp_resource", url_prefix="/<resource_id>") @bp_resource.get("/") def get_resource_hander(request, resource_id): resource = {"resource_id": resource_id} return json(resource) bp_resources_group = Blueprint.group( bp_resources, bp_resource, url_prefix="/resources" ) bp_api_v1 = Blueprint("bp_api_v1") @bp_api_v1.get("/info") def api_v1_info(request): return text("api_version: v1") bp_api_v1_group = Blueprint.group( bp_api_v1, bp_resources_group, url_prefix="/v1" ) bp_api_group = Blueprint.group(bp_api_v1_group, url_prefix="/api") app.blueprint(bp_api_group) request, response = app.test_client.get("/api/v1/info") assert response.text == "api_version: v1" request, response = app.test_client.get("/api/v1/resources") assert response.json == [{}] from uuid import uuid4 resource_id = str(uuid4()) request, response = app.test_client.get( "/api/v1/resources/{0}".format(resource_id) ) assert response.json == {"resource_id": resource_id}
def test_bp_group_indexing(app: Sanic): blueprint_1 = Blueprint("blueprint_1", url_prefix="/bp1") blueprint_2 = Blueprint("blueprint_2", url_prefix="/bp2") group = Blueprint.group(blueprint_1, blueprint_2) assert group[0] == blueprint_1 with raises(expected_exception=IndexError) as e: _ = group[3]
def test_bp_static_content_type(app, file_name): # This is done here, since no other test loads a file here current_file = inspect.getfile(inspect.currentframe()) current_directory = os.path.dirname(os.path.abspath(current_file)) static_directory = os.path.join(current_directory, "static") blueprint = Blueprint("test_static") blueprint.static( "/testing.file", get_file_path(static_directory, file_name), content_type="text/html; charset=utf-8", ) app.blueprint(blueprint) request, response = app.test_client.get("/testing.file") assert response.status == 200 assert response.body == get_file_content(static_directory, file_name) assert response.headers["Content-Type"] == "text/html; charset=utf-8"
def test_bp_group(app): deep_0 = Blueprint("deep_0", url_prefix="/deep") deep_1 = Blueprint("deep_1", url_prefix="/deep1") @deep_0.route("/") def handler(request): return text("D0_OK") @deep_1.route("/bottom") def bottom_handler(request): return text("D1B_OK") mid_0 = Blueprint.group(deep_0, deep_1, url_prefix="/mid") mid_1 = Blueprint("mid_tier", url_prefix="/mid1") @mid_1.route("/") def handler1(request): return text("M1_OK") top = Blueprint.group(mid_0, mid_1) app.blueprint(top) @app.route("/") def handler2(request): return text("TOP_OK") request, response = app.test_client.get("/") assert response.text == "TOP_OK" request, response = app.test_client.get("/mid1") assert response.text == "M1_OK" request, response = app.test_client.get("/mid/deep") assert response.text == "D0_OK" request, response = app.test_client.get("/mid/deep1/bottom") assert response.text == "D1B_OK"
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_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_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
from sanic.blueprints import Blueprint from sanic.response import json from sanic_openapi import doc from models import Driver, Status blueprint = Blueprint('Driver', '/driver') @blueprint.get("/") @doc.summary("Fetches all drivers") @doc.produces([Driver]) def driver_list(request): return json([{"driver": None}]) @blueprint.get("/<driver_id:int>") @doc.summary("Fetches a driver") @doc.produces(Driver) def driver_get(request, driver_id): return json({"driver": None}) @blueprint.put("/<driver_id:int>") @doc.summary("Updates a driver") @doc.consumes(Driver) @doc.produces(Driver) def driver_put(request, driver_id): return json({"driver": None})
from sanic.blueprints import Blueprint from sanic.response import json from sanic_openapi import doc from models import Driver, Status blueprint = Blueprint('Manufacturer', '/manufacturer') @blueprint.get("/") @doc.summary("Fetches all manufacturers") @doc.produces([Driver]) def manufacturer_list(request): return json([{"manufacturer": None}]) @blueprint.get("/<manufacturer_id:int>") @doc.summary("Fetches a manufacturer") @doc.produces(Driver) def manufacturer_get(request, manufacturer_id): return json({"manufacturer": None}) @blueprint.put("/<manufacturer_id:int>") @doc.summary("Updates a manufacturer") @doc.consumes(Driver) @doc.produces(Driver) def manufacturer_put(request, manufacturer_id): return json({"manufacturer": None})
from sanic.response import text from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host="example.com") async def hello(request): return text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return text("42") @bp.route("/question") async def hello(request): return text("What is the meaning of life?") @bp.route("/answer") async def hello(request):
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("DELETE_{}".format(param)) elif request.method == "PATCH": return text("PATCH_{}".format(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.get("/v2/api/bp1/request_path") assert response.status == 401
def test_request_stream(): '''test for complex application''' bp = Blueprint('test_blueprint_request_stream') app = Sanic('test_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, asyncio.Queue) result = '' while True: body = await request.stream.get() if body is None: break result += body.decode('utf-8') request.stream.task_done() return text(result) @app.post('/stream', stream=True) async def handler(request): assert isinstance(request.stream, asyncio.Queue) async def streaming(response): while True: body = await request.stream.get() if body is None: break response.write(body.decode('utf-8')) request.stream.task_done() return stream(streaming) @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, asyncio.Queue) result = '' while True: body = await request.stream.get() if body is None: break result += body.decode('utf-8') request.stream.task_done() 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, asyncio.Queue) result = '' while True: body = await request.stream.get() if body is None: break result += body.decode('utf-8') request.stream.task_done() 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_bp_shorthand(app): blueprint = Blueprint("test_shorhand_routes") ev = asyncio.Event() @blueprint.get("/get") def handler(request): return text("OK") @blueprint.put("/put") def put_handler(request): return text("OK") @blueprint.post("/post") def post_handler(request): return text("OK") @blueprint.head("/head") def head_handler(request): return text("OK") @blueprint.options("/options") def options_handler(request): return text("OK") @blueprint.patch("/patch") def patch_handler(request): return text("OK") @blueprint.delete("/delete") def delete_handler(request): return text("OK") @blueprint.websocket("/ws/", strict_slashes=True) async def websocket_handler(request, ws): ev.set() app.blueprint(blueprint) request, response = app.test_client.get("/get") assert response.body == b"OK" request, response = app.test_client.post("/get") assert response.status == 405 request, response = app.test_client.put("/put") assert response.body == b"OK" request, response = app.test_client.get("/post") assert response.status == 405 request, response = app.test_client.post("/post") assert response.body == b"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.body == b"OK" request, response = app.test_client.get("/options") assert response.status == 405 request, response = app.test_client.patch("/patch") assert response.body == b"OK" request, response = app.test_client.get("/patch") assert response.status == 405 request, response = app.test_client.delete("/delete") assert response.body == b"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()
import logging import re from itertools import repeat from sanic.blueprints import Blueprint from sanic.response import json from sanic.views import CompositionView from sanicms.doc import route_specs, RouteSpec, serialize_schema, definitions logger = logging.getLogger('sanic') 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): config = app.config.get('SWAGGER') _spec['swagger'] = '2.0' _spec['info'] = remove_nulls({ "version":
import random as rand import ujson from sanic.blueprints import Blueprint from sanic.exceptions import ServerError from sanic.response import json rng = rand.Random() rng.seed() random = Blueprint('Random', '/api/random') @random.get("/") async def get_random_quote(request): async with request.app.postgresql.acquire() as conn: quote_count = await request.app.redis.get('quotecount') if quote_count is None: quote_count = await conn.fetchval( '''SELECT max(quote_id) FROM otakuquotes.quotes''') await request.app.redis.set('quotecount', quote_count) # Grab rows from postgresql # Update Redis quote_count random_id = rng.randint(1, int(quote_count) - 1) quote = await request.app.redis.get(f'quote_id:{random_id}') if quote is None: prepstatement = await conn.prepare(''' SELECT quotes.quote_id, quotes.quote_text, quotes.date_added, quotes.episode, quotes.time_stamp, quotes.submitter_name,
from sanic.blueprints import Blueprint app = Blueprint( # pylint: disable=invalid-name 'v1', version=1, strict_slashes=True)
# coding:utf-8 from __future__ import absolute_import, unicode_literals from sanic.blueprints import Blueprint from . import spider, other __author__ = "golden" __date__ = '2018/6/25' bp = Blueprint(__name__, '/api/') bp.add_route(spider.SpidersApi.as_view(), '<project:[A-z]+>/spiders/') bp.add_route(spider.ProjectsApi.as_view(), 'projects/') bp.add_route(other.MenusApi.as_view(), 'menus/')
import json from sanic.blueprints import Blueprint from sanic.response import json from data import test_garage, test_success from models import Car, Garage, Status from sanic_openapi import doc blueprint = Blueprint('Garage', '/garage') @blueprint.get("/", strict_slashes=True) @doc.summary("Fetches the garage") @doc.produces(Garage) async def get_garage(request): return json(test_garage) @blueprint.get("/cars", strict_slashes=True) @doc.summary("Fetches the cars in the garage") @doc.consumes({"doors": int}) @doc.produces({"cars": [Car]}) async def get_cars(request): return json(test_garage.get('cars')) @blueprint.put("/car", strict_slashes=True) @doc.summary("Adds a car to the garage") @doc.consumes(Car) @doc.produces(Status)
import re from itertools import repeat import os 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('swagger', url_prefix='swagger') dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.abspath(dir_path + '/ui') blueprint.static('/', dir_path + '/index.html') blueprint.static('/', dir_path) _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 }
from data import test_car, test_success from models import Car, Status from sanic.blueprints import Blueprint from sanic.response import json from sanic_openapi import doc blueprint = Blueprint('Car', '/car') @blueprint.get("/", strict_slashes=True) @doc.summary("Fetches all cars") @doc.description( "Really gets the job done fetching these cars. I mean, really, wow.") @doc.produces([Car]) def car_list(request): return json([test_car]) @blueprint.get("/<car_id:int>", strict_slashes=True) @doc.summary("Fetches a car") @doc.produces(Car) def car_get(request, car_id): return json(test_car) @blueprint.put("/<car_id:int>", strict_slashes=True) @doc.summary("Updates a car") @doc.consumes(Car, location='body') @doc.consumes({'AUTHORIZATION': str}, location='header') @doc.produces(Car)
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from sanic.blueprints import Blueprint from heliotrope.rest.api.hitomi.galleryinfo import hitomi_galleryinfo from heliotrope.rest.api.hitomi.image import hitomi_image from heliotrope.rest.api.hitomi.info import hitomi_info from heliotrope.rest.api.hitomi.list import hitomi_list from heliotrope.rest.api.hitomi.random import hitomi_random from heliotrope.rest.api.hitomi.search import hitomi_search hitomi_endpoint = Blueprint.group( hitomi_search, hitomi_galleryinfo, hitomi_info, hitomi_list, hitomi_random, hitomi_image, url_prefix="/hitomi", )
import logging from sanic import response from sanic.blueprints import Blueprint from omega.jobs import syncjobs bp = Blueprint("jobs", url_prefix="/jobs/") logger = logging.getLogger(__name__) @bp.route("sync_calendar", methods=["POST"]) async def sync_calendar_handler(request): try: await syncjobs.sync_calendar() return response.json(body=None, status=200) except Exception as e: logger.exception(e) return response.json(e, status=500) @bp.route("sync_security_list", methods=["POST"]) async def sync_seurity_list_handler(request): try: await syncjobs.sync_security_list() return response.json(body=None, status=200) except Exception as e: logger.exception(e) return response.json(body=e, status=500)
from sanic.blueprints import Blueprint from os import path blueprint = Blueprint('redoc') dir_path = path.dirname(path.realpath(__file__)) dir_path = path.abspath(dir_path + '/public') blueprint.static('/docs', dir_path) blueprint.static('/docs', dir_path + '/index.html')
def __init__(self, name='API', url_prefix=''): if url_prefix.endswith('/'): warnings.warn('You used "url_prefix" with trailing slash') self.blueprint = Blueprint(name, url_prefix=url_prefix)
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') @blueprint.get("/somewhere", strict_slashes=True) @protected(blueprint) def protected_hello_world(request): return json({'message': 'hello world'}) @blueprint.get("/user/<id>", strict_slashes=True) @protected(blueprint) def protected_user(request, id): return json({'user': id}) async def authenticate(request, *args, **kwargs): return {'user_id': 1} app = Sanic() sanicjwt = Initialize( blueprint, app=app,
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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) @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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) @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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) async def post_add_route(request): assert isinstance(request.stream, StreamBuffer) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) 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
from sanic.blueprints import Blueprint from sanic.response import json from sanic_openapi import doc health = Blueprint("health", url_prefix="/health") @health.route("/status") @doc.summary("Health Status API") @doc.produces({"status": str}) async def health_status_swagger(request): return json({"status": "OK"})
def test_request_stream_blueprint(): '''for self.is_request_stream = True''' app = Sanic('test_request_stream_blueprint') 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, asyncio.Queue) async def streaming(response): while True: body = await request.stream.get() if body is None: break response.write(body.decode('utf-8')) request.stream.task_done() return stream(streaming) @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, asyncio.Queue) async def streaming(response): while True: body = await request.stream.get() if body is None: break response.write(body.decode('utf-8')) request.stream.task_done() return stream(streaming) @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, asyncio.Queue) async def streaming(response): while True: body = await request.stream.get() if body is None: break response.write(body.decode('utf-8')) request.stream.task_done() return stream(streaming) 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
from sanic import response from sanic.blueprints import Blueprint from sanic.request import Request from views.account import account_blueprint from views.apply import apply_blueprint from views.meal import meal_blueprint from views.notice import notice_blueprint from views.report import report_blueprint blueprint_group = Blueprint.group( account_blueprint, apply_blueprint, meal_blueprint, notice_blueprint, report_blueprint, ) async def ping(request: Request): return response.text('pong!')
MIT License Copyright (c) 2021 SaidBySolo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from sanic.blueprints import Blueprint from heliotrope.rest.api.hitomi import hitomi_endpoint from heliotrope.rest.api.proxy import heliotrope_image_proxy api_endpoint = Blueprint.group(hitomi_endpoint, heliotrope_image_proxy, url_prefix="/api")
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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) @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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) @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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) async def post_add_route(request): assert isinstance(request.stream, StreamBuffer) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) 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
from sanic.blueprints import Blueprint from sanic.response import json from sanic import request import platform import sys api_info = Blueprint('v1.api_info') # API Information /v1/index @api_info.route('/index') async def ApiV1root(request): os_version = platform.system() + " " + str(platform.version()) return json({ "msg": "Hello", "API_info": [{ "PROJECT_VERSION": "1.0", "python_version": sys.version, "OS": os_version }] })
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) async def streaming(response): while True: body = await request.stream.read() if body is None: break await response.write(body.decode("utf-8")) return stream(streaming) @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
from ManjiApi.sanic import ManjiApiRequest from sanic.views import HTTPMethodView from sanic.blueprints import Blueprint from sanic.response import HTTPResponse, json yoshigall_search = Blueprint("yoshigall_search", url_prefix="/search") class YoshiGallSearchView(HTTPMethodView): async def get(self, request: ManjiApiRequest) -> HTTPResponse: if keyword := request.args.get("keyword"): if search_result := await request.app.ctx.yoshigall_request.get_search( keyword, request.args.get("search_mode"), request.args.get("page"), ): return json({"status": 200, **search_result}) return request.app.ctx.response.not_found return json({"status": 400, "message": "no keyword"}, 400) yoshigall_search.add_route(YoshiGallSearchView.as_view(), "")
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 from sanic_jwt.decorators import scoped blueprint = Blueprint("Test") @blueprint.get("/", strict_slashes=True) @protected(blueprint) def protected_hello_world(request): return json({"message": "hello world"}) @blueprint.get("/user/<id>", strict_slashes=True) @protected(blueprint) def protected_user(request, id): return json({"user": id}) @blueprint.route("/scoped_empty") @scoped("something", initialized_on=blueprint) async def scoped(request): return json({"scoped": True}) async def authenticate(request, *args, **kwargs): return {"user_id": 1}
def test_bp_shorthand(): app = Sanic('test_shorhand_routes') blueprint = Blueprint('test_shorhand_routes') ev = asyncio.Event() @blueprint.get('/get') def handler(request): return text('OK') @blueprint.put('/put') def handler(request): return text('OK') @blueprint.post('/post') def handler(request): return text('OK') @blueprint.head('/head') def handler(request): return text('OK') @blueprint.options('/options') def handler(request): return text('OK') @blueprint.patch('/patch') def handler(request): return text('OK') @blueprint.delete('/delete') def handler(request): return text('OK') @blueprint.websocket('/ws') async def handler(request, ws): ev.set() app.blueprint(blueprint) 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()
from sanic.blueprints import Blueprint from sanic.response import json health = Blueprint('health', url_prefix='/health') health_swagger = Blueprint('health', url_prefix='/health') @health.route("/status") async def health_status(request): return json({ 'status': 'OK' })
def test_request_stream_blueprint(app): bp = Blueprint("test_blueprint_request_stream_blueprint") @app.get("/get") async def get(request): return text("GET") @bp.head("/head") async def head(request): return text("HEAD") @bp.delete("/delete") async def delete(request): return text("DELETE") @bp.options("/options") async def options(request): return text("OPTIONS") @bp.post("/_post/<id>") async def _post(request, id): return text("_POST") @bp.post("/post/<id>", stream=True) async def post(request, id): 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): return text("_PUT") @bp.put("/put", stream=True) async def put(request): 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): return text("_PATCH") @bp.patch("/patch", stream=True) async def patch(request): 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): 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) 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 re import shortuuid import itertools import pathlib from sanic.blueprints import Blueprint from sanic.views import HTTPMethodView as View from sanic import response from utils.base import json_dumps from utils.decorators import check_permission from utils.paginator import Paginator from utils.base import carry_key_hash_md5, hmac_sha256 from utils.access_key import generate_access_key_id, generate_access_key_secret from . import forms admin = Blueprint('admin', url_prefix='admin') class UserAdmin(View): """用户列表""" @check_permission() async def get(self, request, **kwargs): q = request.raw_args.get('q') page = int(request.raw_args.get('page', 1)) per_page = int(request.raw_args.get('per_page', 10)) _start = (page - 1) * per_page if q: count_res = await request.app.db.get( "select count(id) as count from user where concat(`username`, ',', `nickname`, ',', `phone`, ',', `email`) like %s and delete_flag = 0;", ('%%%s%%' % q)) count = count_res['count']