예제 #1
0
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'
예제 #2
0
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"
예제 #3
0
파일: test_views.py 프로젝트: imuxin/iSanic
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"
예제 #4
0
def test_with_bp():
    app = Sanic('test_with_bp')
    bp = Blueprint('test_text')

    class DummyView(HTTPMethodView):
        def get(self, request):
            return text('I am get method')

    bp.add_route(DummyView(), '/')

    app.blueprint(bp)
    request, response = sanic_endpoint_test(app)

    assert response.text == 'I am get method'
예제 #5
0
파일: test_views.py 프로젝트: rim99/sanic
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'
예제 #6
0
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'
예제 #7
0
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'
예제 #8
0
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"
예제 #9
0
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'
예제 #10
0
def test_class_based_routing(app):
    class SimpleView(HTTPMethodView):
        @doc.summary('Simple endpoint')
        def get(self, request):
            return text('worked')

    blueprint_with_route = Blueprint('withroute', url_prefix='withroute')
    blueprint_with_route.add_route(SimpleView.as_view(), '/')
    blueprint_with_no_routes = Blueprint('routeless', url_prefix='routeless')

    app.blueprint(blueprint_with_route)
    app.blueprint(blueprint_with_no_routes)

    _, response = app.test_client.get('/withroute/')
    assert response.status == 200
    _, response = app.test_client.get('/routeless/')
    assert response.status == 404
예제 #11
0
class Api:
    """
    Object for incapsulating interactions with resource. This object
    stores bluprint, that actually responsible for routing and stuff.
    """
    def __init__(self, name='API', url_prefix='', logger=None):
        if url_prefix.endswith('/'):
            warnings.warn('You used "url_prefix" with trailing slash')

        self.name = name
        self.blueprint = Blueprint(name, url_prefix=url_prefix)

        if logger is None:
            self.logger = self._make_logger()

    def _make_logger(self):
        stream = logging.StreamHandler()
        stream.setLevel(logging.INFO)
        stream.setFormatter(
            logging.Formatter('%(asctime)s [ %(levelname)s ] %(message)s'))

        logger = logging.getLogger(self.name)
        logger.setLevel(logging.INFO)
        logger.addHandler(stream)

        return logger

    def init_app(self, app):
        app.blueprint(self.blueprint)

    def add_resource(self,
                     res,
                     new_uri=None,
                     inject_logger=True,
                     *args,
                     **kwargs):
        if new_uri:
            uri = new_uri
        else:
            uri = res.uri

        if inject_logger:
            res.logger = self.logger

        self.blueprint.add_route(res.as_view(), uri, *args, **kwargs)
예제 #12
0
def create_app():
    app = Sanic(DEFAULT_SERVICE_NAME)
    api_prefix = f'/{DEFAULT_SERVICE_NAME}'
    api = Blueprint('whreports', url_prefix=api_prefix)

    api.add_route(SmokeResource.as_view(), "/smoke")
    api.add_route(GenerateReportResource.as_view(), "/report")
    api.add_route(StatusReportResource.as_view(), "/report/status/<task_id>")
    api.add_route(DownloadReportResource.as_view(),
                  "/report/download/<task_id>")
    app.blueprint(api)
    import os
    return app
예제 #13
0
class Api:
    """
    Object for incapsulating interactions with resource. This object
    stores bluprint, that actually responsible for routing and stuff.
    """
    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)

    def init_app(self, app):
        app.blueprint(self.blueprint)

    def add_resource(self, res, new_uri=None, *args, **kwargs):
        if new_uri:
            uri = new_uri
        else:
            uri = res.uri

        self.blueprint.add_route(res.as_view(), uri, *args, **kwargs)
예제 #14
0
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"
예제 #15
0
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"
예제 #16
0
from sanic_ext.extensions.openapi import openapi  # type: ignore

from heliotrope.domain import Info
from heliotrope.sanic import HeliotropeRequest

hitomi_info = Blueprint("hitomi_info", url_prefix="/info")


class HitomiInfoView(HTTPMethodView):
    @openapi.tag("hitomi")  # type: ignore
    @openapi.summary("Get hitomi info")  # type: ignore
    @openapi.parameter(name="id", location="path", schema=int)  # type: ignore
    async def get(self, request: HeliotropeRequest, id: int) -> HTTPResponse:
        info = await request.app.ctx.odm.get_info(id)

        if not info:
            if galleryinfo := await request.app.ctx.hitomi_request.get_galleryinfo(id):
                info = Info.from_galleryinfo(galleryinfo)
            else:
                raise NotFound

        return json(
            {
                "status": 200,
                **await request.app.ctx.common_js.convert_thumbnail(info),
            }
        )


hitomi_info.add_route(HitomiInfoView.as_view(), "/<id:int>")
예제 #17
0
hitomi_list = Blueprint("hitomi_list", url_prefix="/list")


class HitomiListView(HTTPMethodView):
    @openapi.tag("hitomi")  # type: ignore
    @openapi.summary("Get latest hitomi info list")  # type: ignore
    @openapi.parameter(name="index", location="path", schema=int)  # type: ignore
    async def get(self, request: HeliotropeRequest, index: int) -> HTTPResponse:
        total = len(await request.app.ctx.orm.get_all_index())

        start_at_zero = index - 1

        if start_at_zero < 0 or total < start_at_zero:
            raise InvalidUsage

        info_list = await request.app.ctx.odm.get_info_list(start_at_zero)

        return json(
            {
                "status": 200,
                "list": [
                    await request.app.ctx.common_js.convert_thumbnail(info)
                    for info in info_list
                ],
                "total": total,
            }
        )


hitomi_list.add_route(HitomiListView.as_view(), "/<index:int>")
예제 #18
0
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
예제 #19
0
from sanic.response import HTTPResponse, json
from ManjiApi.sanic import ManjiApiRequest
from sanic.blueprints import Blueprint
from sanic.views import HTTPMethodView

yoshigall_todaytip = Blueprint("yoshigall_todaytip", url_prefix="/todaytip")


class YoshiGallTodayTipView(HTTPMethodView):
    async def get(self, request: ManjiApiRequest, page: int) -> HTTPResponse:
        if todaytip := await request.app.ctx.yoshigall_request.get_todaytip(
                page):
            return json({"status": 200, **todaytip})
        return request.app.ctx.response.not_found


yoshigall_todaytip.add_route(YoshiGallTodayTipView.as_view(), "/<page:int>")
예제 #20
0
from account import api, service
###############################
# api
###############################
from libs.jwt import jwt_wrapper

account_api_blueprint = Blueprint('account_api', version='1')

api_urls = [('/account', api.CreateAccountApi.as_view(), ['POST']),
            ('/account/send_code', api.SendCodeApi.as_view(), ['POST']),
            ('/login', api.LoginApi.as_view(), ['POST']),
            ('/account/<user_id>/role',
             jwt_wrapper(api.GetRoleIdApi.as_view(), required=True), ['GET'])]
for url, view, methods in api_urls:
    account_api_blueprint.add_route(view, url, methods=methods)

##########################
# 内部服务使用的 api
##########################
service_urls = [
    ('/account', service.CreateAccountService.as_view(), ['POST']),
    ('/account/send_code', service.SendCodeService.as_view(), ['POST']),
    ('/login', service.LoginService.as_view(), ['POST']),
    ('/account/<user_id>/role', service.GetRoleIdService.as_view(), ['GET']),
]
account_service_blueprint = Blueprint('account_service',
                                      url_prefix='/service/v1')
for url, view, methods in service_urls:
    account_service_blueprint.add_route(view, url, methods=methods)
예제 #21
0
api_urls = [('/product',
             jwt_wrapper(api.CreateProductApi.as_view(),
                         role_ids=(app.config.ROLE_MANAGER, )), ['POST']),
            ('/products', api.ListProductsApi.as_view(), ['GET']),
            ('/product/manager/<manager_id>',
             jwt_wrapper(api.ListProductByManagerIdApi.as_view(),
                         role_ids=(app.config.ROLE_MANAGER, )), ['GET']),
            ('/product/<product_id>',
             jwt_wrapper(api.UpdateProductByIdApi.as_view(),
                         role_ids=(app.config.ROLE_MANAGER, )), ['PUT']),
            ('/product/<product_id>',
             jwt_wrapper(api.DeleteProductByIdApi.as_view(),
                         role_ids=(app.config.ROLE_MANAGER, )), ['DELETE'])]
for url, view, methods in api_urls:
    product_api_blueprint.add_route(view, url, methods=methods)

##########################
# 内部服务使用的 api
##########################
service_urls = [('/product', service.CreateProductService.as_view(), ['POST']),
                ('/products', service.ListProductsService.as_view(), ['GET']),
                ('/product/manager/<manager_id>',
                 service.ListProductByManagerService.as_view(), ['GET']),
                ('/product/<product_id>',
                 service.UpdateProductByIdService.as_view(), ['PUT']),
                ('/product/<product_id>',
                 service.DeleteProductByIdService.as_view(), ['DELETE'])]
product_service_blueprint = Blueprint('product_service',
                                      url_prefix='/service/v1')
for url, view, methods in service_urls:
예제 #22
0
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 sanic.response import HTTPResponse, json
from sanic.views import HTTPMethodView
from sanic_ext.extensions.openapi import openapi  # type: ignore

from heliotrope.sanic import HeliotropeRequest

hitomi_random = Blueprint("hitomi_random", url_prefix="/random")


class HitomiRandomView(HTTPMethodView):
    @openapi.summary("Get random result in hitomi")  # type: ignore
    @openapi.tag("hitomi")  # type: ignore
    async def get(self, request: HeliotropeRequest) -> HTTPResponse:
        info = await request.app.ctx.odm.get_random_info()

        return json({
            "status": 200,
            **await request.app.ctx.common_js.convert_thumbnail(info)
        })


hitomi_random.add_route(HitomiRandomView.as_view(), "/")
예제 #23
0
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
예제 #24
0
hitomi_image = Blueprint("hitomi_image", url_prefix="/image")


class HitomiImageView(HTTPMethodView):
    @openapi.tag("hitomi")  # type: ignore
    @openapi.summary("Get hitomi image url list")  # type: ignore
    @openapi.parameter(name="id", location="path", schema=int)  # type: ignore
    async def get(self, request: HeliotropeRequest, id: int) -> HTTPResponse:
        # BUG: Very slow response
        galleryinfo = await request.app.ctx.orm.get_galleryinfo(id)
        if not galleryinfo:
            galleryinfo = await request.app.ctx.hitomi_request.get_galleryinfo(id)

        if not galleryinfo:
            raise NotFound

        files = await request.app.ctx.common_js.image_urls(
            id, list(map(lambda f: f.to_dict(), galleryinfo.files)), False
        )

        return json(
            {
                "status": 200,
                "files": list(files),
            }
        )


hitomi_image.add_route(HitomiImageView.as_view(), "/<id:int>")
예제 #25
0
internal_bp = Blueprint('internal_v1', url_prefix='/api/internal/v1')
external_bp = Blueprint('external_v1', url_prefix='/api/external/v1')


@internal_bp.exception(ServerError)
def internal_bp_exception_handler(request, exception):
    return get_err_response(None, exception.message)


@external_bp.exception(ServerError)
def external_bp_exception_handler(request, exception):
    return get_err_response(None, exception.message)


internal_bp.add_route(get_agent_info, '/agent')
internal_bp.add_route(bind_to_free_slot,
                      '/agent/bind_to_free_slot',
                      methods=('POST', ))
internal_bp.add_route(agent_heartbeat, '/agent/agent_heartbeat')
internal_bp.add_route(remove_agent,
                      '/agent/remove_agent',
                      methods=('DELETE', ))

internal_bp.add_route(add_browser_agent_map,
                      '/browser_agent_map/add_browser_agent_map')
internal_bp.add_route(delete_browser_agent_map,
                      '/browser_agent_map/delete_browser_agent_map',
                      methods=('DELETE', ))

internal_bp.add_route(add_busy_event,
예제 #26
0
            raise InvalidUsage

        headers = request.app.ctx.hitomi_request.headers

        # Pixiv request header
        # 픽시브일경우 리퍼러 헤더 변경
        if "pximg" in unquote_image_url:
            headers.update({"referer": "https://pixiv.net"})

        async with request.app.ctx.request.session.get(
                unquote_image_url, headers=headers) as request_response:

            if request_response.status != 200:
                raise NotFound

            response: HTTPResponse = await request.respond(
                content_type=request_response.content_type)

            # Use chunk
            # 청크를 사용
            # If read is used, oof may occur if many images are requested.
            # 만약 .read를 사용할경우 메모리를 많이 먹기때문에 많은 요청 들어오면 out of memory로 터질수도있음
            async for data, _ in request_response.content.iter_chunks():
                await response.send(data)
            return await response.eof()  # type: ignore


heliotrope_image_proxy.add_route(HeliotropeImageProxyView.as_view(),
                                 "/<image_url:path>",
                                 unquote=True)
예제 #27
0
from sanic.blueprints import Blueprint

apply_blueprint = Blueprint(
    name='apply_blueprint',
    url_prefix='/apply',
)

from views.apply.extension import ExtensionApplyView, ExtensionMapView
apply_blueprint.add_route(ExtensionApplyView.as_view(),
                          '/extension/<time:int>')
apply_blueprint.add_route(ExtensionMapView.as_view(),
                          '/extension/map/<time:int>/<class_:int>')

from views.apply.goingout import GoingoutApplyView
apply_blueprint.add_route(GoingoutApplyView.as_view(), '/goingout')

from views.apply.music import MusicApplyView
apply_blueprint.add_route(MusicApplyView.as_view(), '/music/<weekday:int>')

from views.apply.stay import StayApplyView
apply_blueprint.add_route(StayApplyView.as_view(), '/stay')
예제 #28
0
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>")
예제 #29
0
# 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/')
예제 #30
0
"""
路由 http 请求
"""
from sanic.blueprints import Blueprint

from views import views, admin, k8s

###############################
# api
###############################
api_blueprint = Blueprint('example', version='1')

api_blueprint.add_route(
    views.ExampleView.as_view(), '/example', methods=['POST'])

###############################
# Admin 接口
###############################
admin_blueprint = Blueprint('admin')

admin_blueprint.add_route(
    admin.ListExampleView.as_view(), '/admin/example', methods=['GET'])

###############################
# k8s 检查
###############################
k8s_blueprint = Blueprint('k8s')

k8s_blueprint.add_route(k8s.healthz, '/healthz', methods=['GET'])
k8s_blueprint.add_route(k8s.rediness, '/readiness', methods=['GET'])
예제 #31
0
            await page.goto('data:text/html,{}'.format(html),
                            options={'timeout': 20000})
            # await page.screenshot({'path': 'example.png'})
            result = await page.evaluate(script)
        except Exception as e:
            logger.exception(e)
            return json({"result": "", "code": 0})
        finally:
            if page:
                await page.close()
        return json({"result": result, "code": 1})


api_blueprint = Blueprint("api")

api_blueprint.add_route(RenderJs.as_view(), uri="/render/js", methods=["POST"])


def listeners(app):
    @app.listener('before_server_start')
    async def open_browser(app, loop):
        app.browser = await launch()

    @app.listener('before_server_stop')
    async def server_stop(app, loop):
        await app.browser.close()


def create_app():
    app = Sanic("render")
    app.blueprint(api_blueprint)
예제 #32
0
            break
        result += body.decode('utf-8').replace('1', 'A')
    return text(result)


# You can also use `bp.add_route()` with stream argument
async def bp_post_handler(request):
    result = ''
    while True:
        body = await request.stream.read()
        if body is None:
            break
        result += body.decode('utf-8').replace('1', 'A')
    return text(result)

bp.add_route(bp_post_handler, '/bp_stream', methods=['POST'], stream=True)


async def post_handler(request):
    result = ''
    while True:
        body = await request.stream.read()
        if body is None:
            break
        result += body.decode('utf-8')
    return text(result)

app.blueprint(bp)
app.add_route(SimpleView.as_view(), '/method_view')
view = CompositionView()
view.add(['POST'], post_handler, stream=True)
예제 #33
0
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
예제 #34
0
from sanic.views import HTTPMethodView
from ManjiApi.sanic import ManjiApiRequest
from sanic.blueprints import Blueprint
from sanic.response import HTTPResponse, json


yoshigall_post = Blueprint("yoshigall_post", url_prefix="/post")


class YoshiGallPostView(HTTPMethodView):
    async def get(self, request: ManjiApiRequest, post_id: int) -> HTTPResponse:
        if post_info := await request.app.ctx.yoshigall_request.get_post(post_id):
            return json({"status": 200, **post_info})
        return request.app.ctx.response.not_found


yoshigall_post.add_route(YoshiGallPostView.as_view(), "/<post_id:int>")
예제 #35
0
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)
예제 #36
0
from sanic.views import HTTPMethodView
from sanic.blueprints import Blueprint
from sanic.response import json
from sanic_openapi import doc

blueprint = Blueprint('Repair', '/repair')
from models import Station
from data import test_station


class RepairStation(HTTPMethodView):
    @doc.summary("Fetches all repair stations")
    @doc.produces([Station])
    def get(self, request):
        return json([test_station])

    @doc.summary("make an appointment")
    @doc.description("submit necessary information for appointment")
    def post(self, request):
        return json(request.json)


blueprint.add_route(RepairStation.as_view(), "/station", strict_slashes=True)