Python sanic.Blueprint() Examples
The following are 30
code examples of sanic.Blueprint().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sanic
, or try the search function
.
Example #1
Source File: test_swagger.py From sanic-openapi with MIT License | 6 votes |
def test_blueprint_class_based_view(app): bp = Blueprint("test") bp.add_route(SimpleView.as_view(), "/") app.blueprint(bp) _, response = app.test_client.get("/swagger/swagger.json") assert response.status == 200 assert response.content_type == "application/json" swagger_json = response.json methods = METHODS.copy() methods.remove("options") assert sorted(set(methods)) == sorted(set(swagger_json["paths"]["/"].keys())) assert {"name": "test"} in swagger_json["tags"]
Example #2
Source File: test_initialize.py From sanic-jwt with MIT License | 6 votes |
def test_initialize_app_and_bp(): app = Sanic("sanic-jwt-test") bp = Blueprint("bp", url_prefix="/bpapi") Initialize(instance=bp, app=app, authenticate=lambda: True) app.blueprint(bp) # print("app", app.router.routes_all.keys()) # print("bp", [x.uri for x in bp.routes]) # Result: # assert False
Example #3
Source File: initialization.py From sanic-jwt with MIT License | 6 votes |
def __add_endpoints(self): """ Initialize the Sanic JWT Blueprint and add to the instance initialized """ for mapping in endpoint_mappings: if all(map(self.config.get, mapping.keys)): self.__add_single_endpoint( mapping.cls, mapping.endpoint, mapping.is_protected, mapping.protected_kwargs, ) self.bp.exception(exceptions.SanicJWTException)( self.responses.exception_response ) if not self.instance_is_blueprint: url_prefix = self._get_url_prefix() self.instance.blueprint(self.bp, url_prefix=url_prefix)
Example #4
Source File: initialization.py From sanic-jwt with MIT License | 6 votes |
def __add_class_views(self): """ Include any custom class views on the Sanic JWT Blueprint """ config = self.config if "class_views" in self.kwargs: class_views = self.kwargs.pop("class_views") for route, view in class_views: if issubclass(view, endpoints.BaseEndpoint) and isinstance( route, str ): self.bp.add_route( view.as_view( self.responses, config=self.config, instance=self.instance, ), route, strict_slashes=config.strict_slashes(), ) else: raise exceptions.InvalidClassViewsFormat()
Example #5
Source File: callback.py From rasa-for-botfront with Apache License 2.0 | 6 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]] ) -> Blueprint: callback_webhook = Blueprint("callback_webhook", __name__) @callback_webhook.route("/", methods=["GET"]) async def health(_: Request): return response.json({"status": "ok"}) @callback_webhook.route("/webhook", methods=["POST"]) async def webhook(request: Request) -> HTTPResponse: 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") return callback_webhook
Example #6
Source File: conftest.py From sanic-jwt with MIT License | 6 votes |
def app_with_bp_setup_without_init(username_table, authenticate): sanic_app = Sanic("sanic-jwt-test") @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) sanic_bp = Blueprint("bp", url_prefix="/bp") @sanic_bp.route("/") async def bp_helloworld(request): return json({"hello": "world"}) @sanic_bp.route("/protected") @protected() async def bp_protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_bp)
Example #7
Source File: test_extension.py From sanic-limiter with MIT License | 6 votes |
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)
Example #8
Source File: swagger.py From sanic-transmute with MIT License | 6 votes |
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the sanic app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_ROOT, swagger_json_route ).encode("utf-8") async def swagger_ui(request): return HTTPResponse(body_bytes=swagger_body, content_type="text/html") bp = Blueprint('swagger') bp.static(STATIC_ROOT, static_root) app.add_route(swagger_ui, target_route, methods=["GET"]) app.blueprint(bp)
Example #9
Source File: framework.py From sanicpluginsframework with MIT License | 6 votes |
def _register_route_helper(r, _spf, plugin, context, _p_name, _url_prefix): # Prepend the plugin URI prefix if available uri = _url_prefix + r.uri if _url_prefix else r.uri uri = uri[1:] if uri.startswith('//') else uri # attach the plugin name to the handler so that it can be # prefixed properly in the router _app = _spf._app if isinstance(_app, Blueprint): # blueprint always handles adding __blueprintname__ # So we identify ourselves here a different way. handler_name = r.handler.__name__ r.handler.__name__ = "{}.{}".format(_p_name, handler_name) _spf._plugin_register_bp_route( r.handler, plugin, context, uri, *r.args, **r.kwargs) else: # app is not a blueprint, but we use the __blueprintname__ # property to store the plugin name r.handler.__blueprintname__ = _p_name _spf._plugin_register_app_route( r.handler, plugin, context, uri, *r.args, **r.kwargs)
Example #10
Source File: framework.py From sanicpluginsframework with MIT License | 6 votes |
def _register_websocket_route_helper(w, _spf, plugin, context, _p_name, _url_prefix): # Prepend the plugin URI prefix if available uri = _url_prefix + w.uri if _url_prefix else w.uri uri = uri[1:] if uri.startswith('//') else uri # attach the plugin name to the handler so that it can be # prefixed properly in the router _app = _spf._app if isinstance(_app, Blueprint): # blueprint always handles adding __blueprintname__ # So we identify ourselves here a different way. handler_name = w.handler.__name__ w.handler.__name__ = "{}.{}".format(_p_name, handler_name) _spf._plugin_register_bp_websocket_route( w.handler, plugin, context, uri, *w.args, **w.kwargs) else: # app is not a blueprint, but we use the __blueprintname__ # property to store the plugin name w.handler.__blueprintname__ = _p_name _spf._plugin_register_app_websocket_route( w.handler, plugin, context, uri, *w.args, **w.kwargs)
Example #11
Source File: framework.py From sanicpluginsframework with MIT License | 6 votes |
def _on_server_start(self, app, loop): if not isinstance(self._app, Blueprint): assert self._app == app,\ "Sanic Plugins Framework is not assigned to the correct " \ "Sanic App!" if self._running: # during testing, this will be called _many_ times. return # Ignore if this is already called. self._loop = loop self._running = True # sort and freeze these self._pre_request_middleware = \ tuple(sorted(self._pre_request_middleware)) self._post_request_middleware = \ tuple(sorted(self._post_request_middleware)) self._pre_response_middleware = \ tuple(sorted(self._pre_response_middleware)) self._post_response_middleware = \ tuple(sorted(self._post_response_middleware)) self._cleanup_middleware = \ tuple(sorted(self._cleanup_middleware))
Example #12
Source File: channel.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): custom_webhook = Blueprint( 'custom_webhook_{}'.format(type(self).__name__), inspect.getmodule(self).__name__) # noinspection PyUnusedLocal @custom_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @custom_webhook.route("/webhook", methods=['POST']) async def receive(request): sender_id = await self._extract_sender(request) text = self._extract_message(request) should_use_stream = utils.bool_arg(request, "stream", default=False) if should_use_stream: return response.stream( self.stream_response(on_new_message, text, sender_id), content_type='text/event-stream') else: collector = CollectingOutputChannel() # noinspection PyBroadException try: await on_new_message(UserMessage(text, collector, sender_id, input_channel=self.name())) except CancelledError: logger.error("Message handling timed out for " "user message '{}'.".format(text)) except Exception: logger.exception("An exception occured while handling " "user message '{}'.".format(text)) return response.json(collector.messages) return custom_webhook
Example #13
Source File: channel.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]] ) -> Blueprint: """Defines a Sanic blueprint. The blueprint will be attached to a running sanic server and handle incoming routes it registered for.""" raise NotImplementedError("Component listener needs to provide blueprint.")
Example #14
Source File: slack.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): slack_webhook = Blueprint('slack_webhook', __name__) @slack_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @slack_webhook.route("/webhook", methods=['GET', 'POST']) async def webhook(request: Request): if request.form: output = dict(request.form) if self._is_button_reply(output): sender_id = json.loads(output['payload'])['user']['id'] return await self.process_message( request, on_new_message, text=self._get_button_reply(output), sender_id=sender_id) elif request.json: output = request.json if "challenge" in output: return response.json(output.get("challenge")) elif self._is_user_message(output): return await self.process_message( request, on_new_message, text=self._sanitize_user_message( output['event']['text'], output['authed_users']), sender_id=output.get('event').get('user')) return response.text("") return slack_webhook
Example #15
Source File: twilio.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): twilio_webhook = Blueprint('twilio_webhook', __name__) @twilio_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @twilio_webhook.route("/webhook", methods=['POST']) async def message(request): sender = request.values.get('From', None) text = request.values.get('Body', None) out_channel = TwilioOutput(self.account_sid, self.auth_token, self.twilio_number) if sender is not None and message is not None: try: # @ signs get corrupted in SMSes by some carriers text = text.replace('ยก', '@') await on_new_message(UserMessage(text, out_channel, sender, input_channel=self.name())) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.debug(e, exc_info=True) if self.debug_mode: raise pass else: logger.debug("Invalid message") return response.text("success") return twilio_webhook
Example #16
Source File: webexteams.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]] ) -> Blueprint: webexteams_webhook = Blueprint("webexteams_webhook", __name__) @webexteams_webhook.route("/", methods=["GET"]) async def health(_: Request) -> HTTPResponse: return response.json({"status": "ok"}) @webexteams_webhook.route("/webhook", methods=["POST"]) async def webhook(request: Request) -> HTTPResponse: """Respond to inbound webhook HTTP POST from Webex Teams.""" logger.debug("Received webex webhook call") # Get the POST data sent from Webex Teams json_data = request.json # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the message details message = self.api.messages.get(webhook_obj.data.id) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the # messages that the bot posts and thereby create a loop me = self.api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return response.text("OK") else: metadata = self.get_metadata(request) await self.process_message( on_new_message, message.text, message.personId, metadata ) return response.text("") return webexteams_webhook
Example #17
Source File: botframework.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): botframework_webhook = Blueprint('botframework_webhook', __name__) @botframework_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @botframework_webhook.route("/webhook", methods=['POST']) async def webhook(request: Request): postdata = request.json try: if postdata["type"] == "message": out_channel = BotFramework(self.app_id, self.app_password, postdata["conversation"], postdata["recipient"], postdata["serviceUrl"]) user_msg = UserMessage(postdata["text"], out_channel, postdata["from"]["id"], input_channel=self.name()) await on_new_message(user_msg) else: logger.info("Not received message type") except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.debug(e, exc_info=True) pass return response.text("success") return botframework_webhook
Example #18
Source File: rocketchat.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]] ) -> Blueprint: rocketchat_webhook = Blueprint("rocketchat_webhook", __name__) @rocketchat_webhook.route("/", methods=["GET"]) async def health(_: Request) -> HTTPResponse: return response.json({"status": "ok"}) @rocketchat_webhook.route("/webhook", methods=["GET", "POST"]) async def webhook(request: Request) -> HTTPResponse: output = request.json metadata = self.get_metadata(request) if output: if "visitor" not in output: sender_name = output.get("user_name", None) text = output.get("text", None) recipient_id = output.get("channel_id", None) else: messages_list = output.get("messages", None) text = messages_list[0].get("msg", None) sender_name = messages_list[0].get("username", None) recipient_id = output.get("_id") await self.send_message( text, sender_name, recipient_id, on_new_message, metadata ) return response.text("") return rocketchat_webhook
Example #19
Source File: mattermost.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[None]] ) -> Blueprint: mattermost_webhook = Blueprint("mattermost_webhook", __name__) @mattermost_webhook.route("/", methods=["GET"]) async def health(_: Request) -> HTTPResponse: return response.json({"status": "ok"}) @mattermost_webhook.route("/webhook", methods=["POST"]) async def webhook(request: Request) -> HTTPResponse: output = request.json if not output: return response.text("") metadata = self.get_metadata(request) # handle normal message with trigger_word if "trigger_word" in output: await self.message_with_trigger_word(on_new_message, output, metadata) # handle context actions from buttons elif "context" in output: await self.action_from_button(on_new_message, output, metadata) return response.text("success") return mattermost_webhook
Example #20
Source File: facebook.py From rasa-for-botfront with Apache License 2.0 | 5 votes |
def blueprint( self, on_new_message: Callable[[UserMessage], Awaitable[Any]] ) -> Blueprint: fb_webhook = Blueprint("fb_webhook", __name__) # noinspection PyUnusedLocal @fb_webhook.route("/", methods=["GET"]) async def health(request: Request) -> HTTPResponse: return response.json({"status": "ok"}) @fb_webhook.route("/webhook", methods=["GET"]) async def token_verification(request: Request) -> HTTPResponse: if request.args.get("hub.verify_token") == self.fb_verify: return response.text(request.args.get("hub.challenge")) else: logger.warning( "Invalid fb verify token! Make sure this matches " "your webhook settings on the facebook app." ) return response.text("failure, invalid token") @fb_webhook.route("/webhook", methods=["POST"]) async def webhook(request: Request) -> HTTPResponse: signature = request.headers.get("X-Hub-Signature") or "" if not self.validate_hub_signature(self.fb_secret, request.body, signature): logger.warning( "Wrong fb secret! Make sure this matches the " "secret in your facebook app settings" ) return response.text("not validated") messenger = Messenger(self.fb_access_token, on_new_message) metadata = self.get_metadata(request) await messenger.handle(request.json, metadata) return response.text("success") return fb_webhook
Example #21
Source File: facebook.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): fb_webhook = Blueprint('fb_webhook', __name__) @fb_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @fb_webhook.route("/webhook", methods=['GET']) async def token_verification(request): if request.raw_args.get("hub.verify_token") == self.fb_verify: return request.raw_args.get("hub.challenge") else: logger.warning( "Invalid fb verify token! Make sure this matches " "your webhook settings on the facebook app.") return response.text("failure, invalid token") @fb_webhook.route("/webhook", methods=['POST']) async def webhook(request): signature = request.headers.get("X-Hub-Signature") or '' if not self.validate_hub_signature(self.fb_secret, request.data, signature): logger.warning("Wrong fb secret! Make sure this matches the " "secret in your facebook app settings") return response.text("not validated") messenger = Messenger(self.fb_access_token, on_new_message) await messenger.handle(request.json) return response.text("success") return fb_webhook
Example #22
Source File: test_extension.py From sanic-limiter with MIT License | 5 votes |
def test_bp_limit(self): app, limiter = self.build_app(config={}, global_limits=['1/day']) bp = Blueprint('/bp') limiter.limit('2 per hour')(bp) @bp.route("/bp1") 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)
Example #23
Source File: sanic.py From idom with MIT License | 5 votes |
def _setup_application(self, app: Sanic, config: Config) -> None: cors_config = config["cors"] if cors_config: cors_params = cors_config if isinstance(cors_config, dict) else {} CORS(app, **cors_params) bp = Blueprint(f"idom_renderer_{id(self)}", url_prefix=config["url_prefix"]) self._setup_blueprint_routes(bp, config) app.blueprint(bp)
Example #24
Source File: framework.py From sanicpluginsframework with MIT License | 5 votes |
def url_for(self, view_name, *args, reg=None, **kwargs): if reg is not None: (spf, name, url_prefix) = reg view_name = "{}.{}".format(name, view_name) app = self._app if app is None: return None if isinstance(app, Blueprint): view_name = "{}.{}".format(app.name, view_name) return app.url_for(view_name, *args, **kwargs)
Example #25
Source File: plugin.py From sanicpluginsframework with MIT License | 5 votes |
def __new__(cls, *args, **kwargs): # making a bold assumption here. # Assuming that if a sanic plugin is initialized using # `MyPlugin(app)`, then the user is attempting to do a legacy plugin # instantiation, aka Flask-Style plugin instantiation. if args and len(args) > 0 and \ (isinstance(args[0], Sanic) or isinstance(args[0], Blueprint)): app = args[0] try: mod_name = cls.__module__ mod = importlib.import_module(mod_name) assert mod except (ImportError, AssertionError): raise RuntimeError( "Failed attempting a legacy plugin instantiation. " "Cannot find the module this plugin belongs to.") # Get the spf singleton from this app from spf.framework import SanicPluginsFramework spf = SanicPluginsFramework(app) # catch cases like when the module is "__main__" or # "__call__" or "__init__" if mod_name.startswith("__"): # In this case, we cannot use the module to register the # plugin. Try to use the class method. assoc = spf.register_plugin(cls, *args, **kwargs) else: assoc = spf.register_plugin(mod, *args, **kwargs) return assoc self = super(SanicPlugin, cls).__new__(cls) try: self._initialized # initialized may be True or Unknown except AttributeError: self._initialized = False return self
Example #26
Source File: mattermost.py From rasa_core with Apache License 2.0 | 5 votes |
def blueprint(self, on_new_message): mattermost_webhook = Blueprint('mattermost_webhook', __name__) @mattermost_webhook.route("/", methods=['GET']) async def health(request): return response.json({"status": "ok"}) @mattermost_webhook.route("/webhook", methods=['POST']) async def webhook(request): output = request.json if output: # splitting to get rid of the @botmention # trigger we are using for this text = output['text'].split(" ", 1) text = text[1] sender_id = output['user_id'] self.bot_channel = output['channel_id'] try: out_channel = MattermostBot(self.url, self.team, self.user, self.pw, self.bot_channel) user_msg = UserMessage(text, out_channel, sender_id, input_channel=self.name()) await on_new_message(user_msg) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.debug(e, exc_info=True) pass return response.text("") return mattermost_webhook
Example #27
Source File: test_requests.py From sanic with MIT License | 5 votes |
def test_endpoint_blueprint_asgi(): bp = Blueprint("my_blueprint", url_prefix="/bp") @bp.route("/") async def bp_root(request): return text("Hello") app = Sanic("named") app.blueprint(bp) request, response = await app.asgi_client.get("/bp") assert request.endpoint == "named.my_blueprint.bp_root"
Example #28
Source File: test_multiprocessing.py From sanic with MIT License | 5 votes |
def test_multiprocessing_with_blueprint(app): # Selects a number at random so we can spot check num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1)) process_list = set() def stop_on_alarm(*args): for process in multiprocessing.active_children(): process_list.add(process.pid) process.terminate() signal.signal(signal.SIGALRM, stop_on_alarm) signal.alarm(3) bp = Blueprint("test_text") app.blueprint(bp) app.run(HOST, PORT, workers=num_workers) assert len(process_list) == num_workers # this function must be outside a test function so that it can be # able to be pickled (local functions cannot be pickled).
Example #29
Source File: test_multiprocessing.py From sanic with MIT License | 5 votes |
def test_pickle_app_with_bp(app, protocol): bp = Blueprint("test_text") bp.route("/")(handler) app.blueprint(bp) p_app = pickle.dumps(app, protocol=protocol) del app up_p_app = pickle.loads(p_app) assert up_p_app request, response = up_p_app.test_client.get("/") assert up_p_app.is_request_stream is False assert response.text == "Hello"
Example #30
Source File: test_swagger.py From sanic-openapi with MIT License | 5 votes |
def test_document_blueprint_route(app, method): bp = Blueprint("test") @bp.route("/", methods=[method]) def test(request): return text("test") app.blueprint(bp) _, response = app.test_client.get("/swagger/swagger.json") assert response.status == 200 assert response.content_type == "application/json" swagger_json = response.json assert {"name": "test"} in swagger_json["tags"] assert swagger_json["paths"] == { "/": { method: { "operationId": "test.test", "consumes": ["application/json"], "produces": ["application/json"], "tags": ["test"], "parameters": [], "responses": {"200": {}}, } } }