How to use the sanic.Blueprint function in sanic

To help you get started, we’ve selected a few sanic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bohea / sanic-limiter / test / test_extension.py View on Github external
def test_bp_combined_limit(self):
        app, limiter = self.build_app(config={}, global_limits=['1/day'])
        bp = Blueprint('/bp')
        limiter.limit('1 per hour')(bp)

        @bp.route("/bp1")
        @limiter.limit('2 per hour')
        async def bp_t1(request):
            return text("bp_t1")

        app.blueprint(bp)

        cli = app.test_client
        self.assertEqual(200, cli.get("/bp1")[1].status)
        self.assertEqual(200, cli.get("/bp1")[1].status)
        self.assertEqual(429, cli.get("/bp1")[1].status)
github bohea / sanic-limiter / test / test_demo.py View on Github external
# demo start
from sanic import Sanic, Blueprint
from sanic.response import text

from sanic_limiter import Limiter, get_remote_address

app = Sanic(__name__)
limiter = Limiter(app, global_limits=['1 per hour', '10 per day'], key_func=get_remote_address)
bp = Blueprint('some_bp')
limiter.limit("2 per hour")(bp)


@bp.route("/bp1")
async def bp_t1(request):
    return text("bp_t1")


@app.route("/t1")
@limiter.limit("100 per hour;10/minute")
async def t1(request):
    return text("t1")


@app.route("/t2")
async def t2(request):
github vapor-ware / synse-server / synse_server / api / http.py View on Github external
"""Synse Server HTTP API."""

import ujson
from sanic import Blueprint
from sanic.request import Request
from sanic.response import HTTPResponse, StreamingHTTPResponse, stream
from structlog import get_logger

from synse_server import cmd, errors, plugin, utils

logger = get_logger()

# Blueprint for the Synse core (version-less) routes.
core = Blueprint('core-http')

# Blueprint for the Synse v3 HTTP API.
v3 = Blueprint('v3-http', version='v3')


@core.route('/test')
async def test(request: Request) -> HTTPResponse:
    """A dependency and side-effect free check to see whether Synse Server
    is reachable and responsive.

    This endpoint does not have any internal data dependencies. A failure
    may indicate that Synse Server is not serving (e.g. still starting up
    or experiencing a failure), or that it is not reachable on the network.

    Args:
        request: The Sanic request object.
github HackerDom / ructfe-2016 / services / atlablog / entries / blueprint.py View on Github external
from sanic import Blueprint

from .models import make_models
from .service import _has_entry_service, EntryService, \
    _set_default_entry_service, _register_entry_service

bp = Blueprint('entries')


@bp.record
def module_registered(state):
    app = state.app
    db = state.options.get('db')
    db_name = state.options.get('db_name')
    loop = state.options.get('loop')

    if not db_name:
        raise RuntimeError(
            "This blueprint expects you to provide database access! "
            "Use: app.blueprint(bp, db_name=...)")
    if _has_entry_service(db_name):
        raise RuntimeError(
            "This blueprint already registered with this db_name! "
github teamhide / pythondi / examples / sanic_example.py View on Github external
    @abc.abstractmethod
    def get(self):
        pass


class SQLRepo(Repo):
    """Impl class"""
    def __init__(self):
        pass

    def get(self):
        print('SQLRepo')


bp = Blueprint('home', url_prefix='/')


@bp.route('/')
async def home(request):
    usecase = Usecase()
    usecase.repo.get()
    return json({'hello': 'world'})


class Usecase:
    @inject()
    def __init__(self, repo: Repo):
        self.repo = repo


def create_app():
github baojiweicn / susnote / app / views / notebook_view.py View on Github external
#!/usr/bin/env python
# encoding: utf-8

import logging
from sanic import  Blueprint, response
from sanic.response import json, text, html, redirect
import ujson
import datetime

logger = logging.getLogger('notebook')
notebook_bp = Blueprint('notebook', url_prefix='notebook')

@notebook_bp.route('/get',methods=['GET'])
async def notebooks(request):
    args = request.args
    limit = args.get('limit',10)
    start = args.get('start',0)
    order = args.get('order','desc')
    notebook_id = args.get('id',-1)

    notebooks = []

    author_id = request['session']['author_id'] if request['session']['author_id'] else -1

    if author_id <0 :
        return json({'error':'illegal information'}, status=400)
github autogestion / pubgate / pubgate / api / inbox.py View on Github external
import asyncio
from sanic import response, Blueprint
from sanic.log import logger
from sanic_openapi import doc

from pubgate.db import Inbox, Outbox
from pubgate.db.cached import timeline_cached
from pubgate.utils import check_origin
from pubgate.utils.networking import deliver, verify_request
from pubgate.utils.checks import user_check, token_check
from pubgate.utils.cached import ensure_inbox
from pubgate.activity import Activity
from pubgate.utils.cached import cached_mode, clear_cache

inbox_v1 = Blueprint('inbox_v1')


# @inbox_v1.middleware('response')
# async def update_headers(request, response):
#     response.headers["Access-Control-Allow-Origin"] = "*"


@inbox_v1.route('/@/inbox', methods=['POST'])
@doc.summary("Post to user inbox")
@doc.consumes(Inbox, location="body")
@user_check
async def inbox_post(request, user):
    # TODO implement shared inbox
    # TODO https://www.w3.org/TR/activitypub/#inbox-forwarding
    activity = request.json.copy()
    # TODO The receiver must verify the notification by fetching its source from the origin server.
github botfront / rasa-for-botfront / rasa / core / channels / callback.py View on Github external
def blueprint(self, on_new_message):
        callback_webhook = Blueprint("callback_webhook", __name__)

        @callback_webhook.route("/", methods=["GET"])
        async def health(request: Request):
            return response.json({"status": "ok"})

        @callback_webhook.route("/webhook", methods=["POST"])
        async def webhook(request: Request):
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)

            collector = self.get_output_channel()
            await on_new_message(
                UserMessage(text, collector, sender_id, input_channel=self.name())
            )
            return response.text("success")
github sourcepirate / devmap / app / roadmap / blueprints / mapblueprint.py View on Github external
"""blueprint for roadmap"""

from uuid import uuid4
from sanic import Blueprint
from sanic import response
from roadmap.base import RoadMap


endpoints = Blueprint("MapEndpoints")


@endpoints.get("/api/<_id>")
def get_root_map(request, _id):
    """getting road map root node"""
    dct = RoadMap.get_map(_id)
    if not dct:
        return response.json({"Error": "Not Found"}, status=404)
    return response.json(dct.to_dict(), status=200)

@endpoints.post("/api/new")
def create_root_map(request):
    """creating root map"""
    key = str(uuid4())
    name = request.json.get("name")
    start = request.json.get("start_node")
github rmorshea / idom / src / py / idom / server / base.py View on Github external
def __init__(self):
        self.app = Sanic()
        self._blueprints: List[Blueprint] = []