def test_methods(method): app = Sanic('test_methods') class DummyView(HTTPMethodView): async def get(self, request): assert request.stream is None return text('', headers={'method': 'GET'}) def post(self, request): return text('', headers={'method': 'POST'}) async def put(self, request): return text('', headers={'method': 'PUT'}) def head(self, request): return text('', headers={'method': 'HEAD'}) def options(self, request): return text('', headers={'method': 'OPTIONS'}) async def patch(self, request): return text('', headers={'method': 'PATCH'}) def delete(self, request): return text('', headers={'method': 'DELETE'}) app.add_route(DummyView.as_view(), '/') assert app.is_request_stream is False request, response = getattr(app.test_client, method.lower())('/') assert response.headers['method'] == method
def test_remove_static_route(): app = Sanic('test_remove_static_route') async def handler1(request): return text('OK1') async def handler2(request): return text('OK2') app.add_route(handler1, '/test') app.add_route(handler2, '/test2') request, response = app.test_client.get('/test') assert response.status == 200 request, response = app.test_client.get('/test2') assert response.status == 200 app.remove_route('/test') app.remove_route('/test2') request, response = app.test_client.get('/test') assert response.status == 404 request, response = app.test_client.get('/test2') assert response.status == 404
def test_remove_route_without_clean_cache(): app = Sanic('test_remove_static_route') async def handler(request): return text('OK') app.add_route(handler, '/test') request, response = app.test_client.get('/test') assert response.status == 200 app.remove_route('/test', clean_cache=True) request, response = app.test_client.get('/test') assert response.status == 404 app.add_route(handler, '/test') request, response = app.test_client.get('/test') assert response.status == 200 app.remove_route('/test', clean_cache=False) request, response = app.test_client.get('/test') assert response.status == 200
def test_url_attributes_with_ssl(path, query, expected_url): app = Sanic('test_url_attrs_with_ssl') current_dir = os.path.dirname(os.path.realpath(__file__)) context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) context.load_cert_chain( os.path.join(current_dir, 'certs/selfsigned.cert'), keyfile=os.path.join(current_dir, 'certs/selfsigned.key')) async def handler(request): return text('OK') app.add_route(handler, path) request, response = app.test_client.get( 'https://{}:{}'.format(HOST, PORT) + path + '?{}'.format(query), server_kwargs={'ssl': context}) assert request.url == expected_url.format(HOST, PORT) parsed = urlparse(request.url) assert parsed.scheme == request.scheme assert parsed.path == request.path assert parsed.query == request.query_string assert parsed.netloc == request.host
def test_request_stream_method_view(): '''for self.is_request_stream = True''' app = Sanic('test_request_stream_method_view') 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') return text(result) app.add_route(SimpleView.as_view(), '/method_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
def test_request_stream_composition_view(): '''for self.is_request_stream = True''' app = Sanic('test_request_stream__composition_view') 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') return text(result) view = CompositionView() view.add(['GET'], get_handler) view.add(['POST'], post_handler, stream=True) app.add_route(view, '/composition_view') assert app.is_request_stream is True 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
def test_methods(method): app = Sanic('test_methods') class DummyView(HTTPMethodView): def get(self, request): return text('', headers={'method': 'GET'}) def post(self, request): return text('', headers={'method': 'POST'}) def put(self, request): return text('', headers={'method': 'PUT'}) def head(self, request): return text('', headers={'method': 'HEAD'}) def options(self, request): return text('', headers={'method': 'OPTIONS'}) def patch(self, request): return text('', headers={'method': 'PATCH'}) def delete(self, request): return text('', headers={'method': 'DELETE'}) app.add_route(DummyView.as_view(), '/') request, response = sanic_endpoint_test(app, method=method) assert response.headers['method'] == method
def test_remove_unhashable_route(): app = Sanic('test_remove_unhashable_route') async def handler(request, unhashable): return text('OK') app.add_route(handler, '/folder/<unhashable:[A-Za-z0-9/]+>/end/') request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 200 request, response = app.test_client.get('/folder/test///////end/') assert response.status == 200 request, response = app.test_client.get('/folder/test/end/') assert response.status == 200 app.remove_route('/folder/<unhashable:[A-Za-z0-9/]+>/end/') request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 404 request, response = app.test_client.get('/folder/test///////end/') assert response.status == 404 request, response = app.test_client.get('/folder/test/end/') assert response.status == 404
def test_with_middleware_response(): app = Sanic('test_with_middleware_response') results = [] @app.middleware('request') async def process_response(request): results.append(request) @app.middleware('response') async def process_response(request, response): results.append(request) results.append(response) class DummyView(HTTPMethodView): def get(self, request): return text('I am get method') app.add_route(DummyView.as_view(), '/') request, response = sanic_endpoint_test(app) assert response.text == 'I am get method' assert type(results[0]) is Request assert type(results[1]) is Request assert isinstance(results[2], HTTPResponse)
def test_remove_static_route(): app = Sanic('test_remove_static_route') async def handler1(request): return text('OK1') async def handler2(request): return text('OK2') app.add_route(handler1, '/test') app.add_route(handler2, '/test2') request, response = sanic_endpoint_test(app, uri='/test') assert response.status == 200 request, response = sanic_endpoint_test(app, uri='/test2') assert response.status == 200 app.remove_route('/test') app.remove_route('/test2') request, response = sanic_endpoint_test(app, uri='/test') assert response.status == 404 request, response = sanic_endpoint_test(app, uri='/test2') assert response.status == 404
def test_add_route_method_not_allowed(): app = Sanic('test_add_route_method_not_allowed') async def handler(request): return text('OK') app.add_route(handler, '/test', methods=['GET']) request, response = app.test_client.get('/test') assert response.status == 200 request, response = app.test_client.post('/test') assert response.status == 405
def test_add_route_method_not_allowed(): app = Sanic('test_add_route_method_not_allowed') async def handler(request): return text('OK') app.add_route(handler, '/test', methods=['GET']) request, response = sanic_endpoint_test(app, uri='/test') assert response.status == 200 request, response = sanic_endpoint_test(app, method='post', uri='/test') assert response.status == 405
def test_argument_methods(): app = Sanic('test_argument_methods') class DummyView(HTTPMethodView): def get(self, request, my_param_here): return text('I am get method with %s' % my_param_here) app.add_route(DummyView.as_view(), '/<my_param_here>') request, response = sanic_endpoint_test(app, uri='/test123') assert response.text == 'I am get method with test123'
def test_unexisting_methods(): app = Sanic('test_unexisting_methods') class DummyView(HTTPMethodView): def get(self, request): return text('I am get method') app.add_route(DummyView.as_view(), '/') request, response = sanic_endpoint_test(app, method="get") assert response.text == 'I am get method' request, response = sanic_endpoint_test(app, method="post") assert response.text == 'Error: Method POST not allowed for URL /'
def test_dynamic_add_route(): app = Sanic('test_dynamic_add_route') results = [] async def handler(request, name): results.append(name) return text('OK') app.add_route(handler, '/folder/<name>') request, response = app.test_client.get('/folder/test123') assert response.text == 'OK' assert results[0] == 'test123'
def test_remove_dynamic_route(): app = Sanic('test_remove_dynamic_route') async def handler(request, name): return text('OK') app.add_route(handler, '/folder/<name>') request, response = app.test_client.get('/folder/test123') assert response.status == 200 app.remove_route('/folder/<name>') request, response = app.test_client.get('/folder/test123') assert response.status == 404
def dev(ctx, gateway, folder, port, secret): """ Test a factory instance locally """ if gateway is None: gateway = get_default_gateway(ctx) cwd = os.getcwd() log_config = { "version": 1, "disable_existing_loggers": False, "loggers": { "sanic.root": { "level": "FATAL", "propagate": True }, "sanic.error": { "level": "FATAL", "propagate": True }, }, } app = Sanic("Lager-Factory", log_config=log_config) app.config['CONTEXT'] = ctx app.config['GATEWAY_ID'] = gateway app.config['CWD'] = cwd app.config['FOLDER'] = folder app.config['PORT'] = port app.config['SECRETS'] = secret app.add_route(home, '/') app.add_route(start, '/factory/start', methods=['POST']) app.add_route(stop, '/factory/stop', methods=['POST']) app.add_route(runner, '/factory/run-station/new-runner/<session_id:uuid>', methods=['POST']) app.add_route(image, '/factory/run-station/img') app.add_websocket_route(websocket_handler, '/ws/job/<session_id:uuid>') app.static('/static', ASSET_PATH) app.signal('server.init.after')(after_start) env = Environment(loader=FileSystemLoader(ASSET_PATH), autoescape=select_autoescape()) app.ctx.jinja = env dev_mode = 'LAGER_SANIC_DEV' in os.environ app.run(port=port, motd=False, verbosity=0, dev=dev_mode, access_log=False)
def test_context_vars(): """ Test if ContextVar works as expected in sanic request handlers """ cv = contextvars.ContextVar('cv') async def handle_get(request: sanic.request, path: str) -> sanic.response: print(f"Start get {path}") cv.set(path) await asyncio.sleep(0.5) print(f"End get {path}, cv={cv.get()}") return sanic.response.text(f"{path} {cv.get()}") async def quit(request: sanic.request) -> sanic.response: print("Received /stop") app.stop() return sanic.response.text("ok") app = Sanic(__name__) app.config.LOGO = None app.add_route(quit, '/stop', methods=['GET']) app.add_route(handle_get, '/test/<path:.*>', methods=['GET']) def do_get(ret, wait=0, path="/", timeout=10): time.sleep(wait) req = urllib.request.urlopen("http://127.0.0.1:22334" + path, timeout=timeout) body = req.read() ret['status'] = req.status ret['body'] = body get_a_ret = {} get_a_thread = threading.Thread(target=do_get, args=(get_a_ret, 0.1, "/test/a")) get_a_thread.start() get_b_ret = {} get_b_thread = threading.Thread(target=do_get, args=(get_b_ret, 0.1, "/test/b")) get_b_thread.start() stop_thread = threading.Thread(target=do_get, args=({}, 1, "/stop", 0.1)) stop_thread.start() app.run(host="127.0.0.1", port=22334) get_a_thread.join() get_b_thread.join() stop_thread.join() asyncio.set_event_loop(asyncio.new_event_loop()) # leave with an non-stopped loop assert get_a_ret == {'status': 200, 'body': b'a a'} assert get_b_ret == {'status': 200, 'body': b'b b'}
def set_up_routes(app: Sanic): api = Blueprint('api', url_prefix='/api/v1') api.add_route(note.add, '/add', methods=('POST',)) api.add_route(note.edit, '/edit/<id:int>', methods=('POST',)) api.add_route(note.del_by_id, '/delete/<id:int>', methods=('DELETE',)) api.add_route(note.set_done, '/done/<id:int>', methods=('POST',)) api.add_route(note.set_undone, '/undone/<id:int>', methods=('POST',)) api.add_route(note.set_in_progress, '/in_progress/<id:int>', methods=('POST',)) api.add_route(note.set_off_progress, '/off_progress/<id:int>', methods=('POST',)) app.blueprint(api) app.blueprint(swagger_blueprint) app.add_route(ping.ping, '/ping', methods=('GET',)) return app
def test_dynamic_add_named_route_unhashable(): app = Sanic('test_dynamic_add_route_unhashable') async def handler(request, unhashable): return text('OK') app.add_route(handler, '/folder/<unhashable:[A-Za-z0-9/]+>/end/', name='route_unhashable') route = app.router.routes_all['/folder/<unhashable:[A-Za-z0-9/]+>/end/'] assert route.name == 'route_unhashable' url = app.url_for('route_unhashable', unhashable='folder1') assert url == '/folder/folder1/end' with pytest.raises(URLBuildError): app.url_for('handler')
class Server(object): def __init__(self): self.app = Sanic() # 一种Python web框架 self.flag = 1 self.app.add_route(self.tt, '/tt', methods=['GET']) #self.app.add_route(self.test, '/test', methods=['POST']) # async def func1(self): # while True: # print(self.flag) # await asyncio.sleep(1) async def tt(self, requests): #self.flag=self.flag+1 return json(JSON.dumps({"result": 'self.flag'}))
def create_app(env=None): app = Sanic(__name__, log_config=logger.get_sanic_log_config()) app.config.from_object(get_config(env)) db.init_engine(env) setup_middleware(app) app.blueprint(user_bp) app.blueprint(admin_bp) app.blueprint(email_bp) app.add_route(Account_Endpoints.as_view(), "/account") app.add_route(Admin_Endpoints.as_view(), "/accounts/<id>") Log.info("created app") return app
def createApp(cls, appName): app = Sanic(appName) #判断session if config('SESSION_ENABLE') == 'true': # 启用session Session(app, interface=InMemorySessionInterface( expiry=int(config('SESSION_EXPIRE')))) #加载路由 for uri, action in router.routers.items(): app.add_route(action.as_view(), uri) #设置静态目录 app.static('/static', './static') return app
def configure_app(config: ApplicationConfig, context: Context): init_db_postgres(config, context) app = Sanic(__name__) for handler in get_routes(config, context): app.add_route( handler=handler, uri=handler.uri, methods=handler.methods, strict_slashes=True, ) return app
def build_app(): from config import config sentry_sdk.init(dsn=config.SENTRY_DSN, integrations=[SanicIntegration()], release=VERSION, environment=os.environ.get( 'INFOENERGIA_MODULE_SETTINGS').split('.')[-1]) app = Sanic('infoenergia-api') try: app.config.from_object(config) InitializeJWT(app, authenticate=authenticate, retrieve_user=retrieve_user, class_views=extra_views) app.blueprint(bp_contracts) app.blueprint(bp_f1_measures) app.blueprint(bp_modcontracts) app.blueprint(bp_cch_measures) app.blueprint(bp_reports) app.blueprint(bp_tariff) app.add_route(InvitationUrlToken.as_view(), '/auth/invitationtoken', host='localhost:9000') app.thread_pool = futures.ThreadPoolExecutor(app.config.MAX_THREADS) app.erp_client = Client(transport=PoolTransport( secure=app.config.TRANSPORT_POOL_CONF['secure']), **app.config.ERP_CONF) db.bind(provider='sqlite', filename=os.path.join( app.config.DATA_DIR, '{}.sqlite3'.format(app.config.DB_CONF['database'])), create_db=True) db.generate_mapping(create_tables=True) app.db = db except Exception as e: msg = "An error ocurred building Infoenergia API: %s" logger.exception(msg, str(e)) raise e else: logger.info("Build api finished") return app
def test_composition_view_rejects_invalid_methods(method): app = Sanic('test_composition_view') view = CompositionView() view.add(['GET', 'POST', 'PUT'], lambda x: text('first method')) app.add_route(view, '/') if method in ['GET', 'POST', 'PUT']: request, response = getattr(app.test_client, method.lower())('/') assert response.status == 200 assert response.text == 'first method' if method in ['DELETE', 'PATCH']: request, response = getattr(app.test_client, method.lower())('/') assert response.status == 405
def test_with_custom_class_methods(): app = Sanic('test_with_custom_class_methods') class DummyView(HTTPMethodView): global_var = 0 def _iternal_method(self): self.global_var += 10 def get(self, request): self._iternal_method() return text('I am get method and global var is {}'.format(self.global_var)) app.add_route(DummyView.as_view(), '/') request, response = sanic_endpoint_test(app, method="get") assert response.text == 'I am get method and global var is 10'
def main(debug: Optional[bool]=False): """ Runs the api server. """ app = Sanic(__name__) # add routes app.add_route(CheckView.as_view(), CheckView.base_path) # /check app.add_route(CheckIDView.as_view(), CheckIDView.base_path) # /check/<id> # call init function init_text_comparison() # run server port = get_env('PORT') app.run('0.0.0.0', port=port, debug=debug)
class MyAPIClass(object): def __init__(self, address='192.168.211.14', port=5000): self.address = address self.port = port self.app = Sanic(__name__) self.app.add_route(self.create, "/sarcopenia", methods=['POST']) def create(self, request): root = request.form.get('root') home = request.form.get('home') print(request.json) size = int(request.form.get('size', 0)) print('CREATE {} -> {} -> {} -> {}'.format(id, root, home, size)) def start(self): self.app.run(host=self.address, port=self.port)
def test_composition_view_runs_methods_as_expected(method): app = Sanic('test_composition_view') view = CompositionView() view.add(['GET', 'POST', 'PUT'], lambda x: text('first method')) view.add(['DELETE', 'PATCH'], lambda x: text('second method')) app.add_route(view, '/') if method in ['GET', 'POST', 'PUT']: request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'first method' if method in ['DELETE', 'PATCH']: request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'second method'
class QRest(QRemoteConnection): def __init__( self, analyzer, category="", white_lister=None, host="0.0.0.0", port=5000, workers=multiprocessing.cpu_count(), config_path=["conf", "config.json"], ): self.host = host self.port = port self.workers = workers super().__init__(analyzer, category, white_lister) self.app = Sanic(__name__) # Add routes # This works, but it is better to make these after instantiating the class # that way you don't need partial application... see README unary_post_root = partial(post_root, self) unary_get_root = partial(get_root, self) self.app.add_route(unary_post_root, "/", methods=["POST"]) self.app.add_route(unary_get_root, "/", methods=["GET"]) def get_future(self): """ Return a Future (Promise in JS land) that can be put on an event loop """ return self.app.create_server(host=self.host, port=self.port) def connect(self): """ Doesn't return, makes a blocking connection Only use if you are ONLY using REST This is a more robust REST server than get_future makes see: https://sanic.readthedocs.io/en/latest/sanic/deploying.html#asynchronous-support """ if self.workers > 1: print(f"grpc, and hence AutoML, only support 1 worker, " + f"but you are using {self.workers}") return self.app.run(host=self.host, port=self.port, workers=self.workers)
def init_app(app: Sanic) -> Tuple[PublisherClient, SQLiteAckQueue]: """Initialize Sanic app with url rules.""" # Initialize PubSub client timeout = app.config.get("PUBLISH_TIMEOUT_SECONDS", None) client = PublisherClient() client.api.publish = partial( client.api.publish, retry=Retry(TRANSIENT_ERRORS, deadline=timeout), timeout=timeout, ) client._batch_class = AsyncioBatch # Use a SQLiteAckQueue because: # * we use acks to ensure messages only removed on success # * persist-queue's SQLite*Queue is faster than its Queue # * SQLite provides thread-safe and process-safe access queue_config = { key[6:].lower(): value for key, value in app.config.items() if key.startswith("QUEUE_") } q = SQLiteAckQueue(**queue_config) # get metadata_headers config metadata_headers = app.config["METADATA_HEADERS"] # validate attribute keys for attribute in metadata_headers.values(): if len(attribute.encode("utf8")) > 256: # https://cloud.google.com/pubsub/quotas#resource_limits raise ValueError( "Metadata attribute exceeds key size limit of 256 bytes") # add routes for ROUTE_TABLE handlers: Dict[str, Callable] = {} for route in app.config["ROUTE_TABLE"]: if route.topic not in handlers: # generate one handler per topic handlers[route.topic] = partial( submit, client=client, q=q, topic=route.topic, metadata_headers=metadata_headers, ) handlers[route.topic].__name__ = f"submit({route.topic})" app.add_route( handler=handlers[route.topic], uri=route.uri, methods=[method.upper() for method in route.methods], ) return client, q
def test_static_add_route(): app = Sanic('test_static_add_route') async def handler1(request): return text('OK1') async def handler2(request): return text('OK2') app.add_route(handler1, '/test') app.add_route(handler2, '/test2') request, response = sanic_endpoint_test(app, uri='/test') assert response.text == 'OK1' request, response = sanic_endpoint_test(app, uri='/test2') assert response.text == 'OK2'
def test_url_attributes_no_ssl(path, query, expected_url): app = Sanic('test_url_attrs_no_ssl') async def handler(request): return text('OK') app.add_route(handler, path) request, response = app.test_client.get(path + '?{}'.format(query)) assert request.url == expected_url.format(HOST, PORT) parsed = urlparse(request.url) assert parsed.scheme == request.scheme assert parsed.path == request.path assert parsed.query == request.query_string assert parsed.netloc == request.host
def test_static_add_route(): app = Sanic('test_static_add_route') async def handler1(request): return text('OK1') async def handler2(request): return text('OK2') app.add_route(handler1, '/test') app.add_route(handler2, '/test2') request, response = app.test_client.get('/test') assert response.text == 'OK1' request, response = app.test_client.get('/test2') assert response.text == 'OK2'
def configure_app(config: ApplicationConfig, context: Context): # произведется подключение к базе данных и объект database запишется # в специальную контекстную переменную database init_db_sqlite(config, context) app = Sanic(__name__) for handler in get_routes(config, context): app.add_route( handler=handler, uri=handler.uri, methods=handler.methods, strict_slashes=True, ) return app
def test_dynamic_add_route_int(): app = Sanic('test_dynamic_add_route_int') results = [] async def handler(request, folder_id): results.append(folder_id) return text('OK') app.add_route(handler, '/folder/<folder_id:int>') request, response = app.test_client.get('/folder/12345') assert response.text == 'OK' assert type(results[0]) is int request, response = app.test_client.get('/folder/asdf') assert response.status == 404
def init_app(app: Sanic) -> Tuple[PublisherClient, SQLiteAckQueue]: """Initialize Sanic app with url rules.""" # Get PubSub timeout timeout = app.config.get("PUBLISH_TIMEOUT_SECONDS") # Initialize PubSub client client = PublisherClient() # Use a SQLiteAckQueue because: # * we use acks to ensure messages only removed on success # * persist-queue's SQLite*Queue is faster than its Queue # * SQLite provides thread-safe and process-safe access queue_config = { key[6:].lower(): value for key, value in app.config.items() if key.startswith("QUEUE_") } q = SQLiteAckQueue(**queue_config) # get metadata_headers config metadata_headers = app.config["METADATA_HEADERS"] # validate attribute keys for attribute in metadata_headers.values(): if len(attribute.encode("utf8")) > 256: # https://cloud.google.com/pubsub/quotas#resource_limits raise ValueError("Metadata attribute exceeds key size limit of 256 bytes") # generate one view_func per topic handlers = { route.topic: partial( submit, client=client, q=q, topic=route.topic, metadata_headers=metadata_headers, timeout=timeout, ) for route in app.config["ROUTE_TABLE"] } # add routes for ROUTE_TABLE for route in app.config["ROUTE_TABLE"]: app.add_route( handler=handlers[route.topic], uri=route.uri, methods=[method.upper() for method in route.methods], # required because handler.__name__ does not exist # must be a unique name for each handler name="submit_" + route.topic, ) return client, q
async def app(request, loop): app = Sanic('test_app') pool = await asyncpg.create_pool(dsn='postgresql://{}@{}/{}'.format( TEST_DB_USER, TEST_DB_HOST, TEST_DB_NAME, )) app.pool = pool async def test_main(request): """ The main route. Accepts POST requests with the following "Content-Type" headers: - application/json - octet-stream If the request has a json content type, then the request body should contain a "url" key with the location from where the resource should be downloaded. In case of the octet-stream, the binary data is considered a resource. """ try: validate_request(request) # TODO move to middleware except AssertionError: return json({'success': False, 'error': 'Wrong content type'}, 400) if is_binary_request(request): try: header, data, encoded_data = parse_raw_body(request.body) except Exception: return json({'success': False, 'error': 'Failed to parse request body'}, 400) elif is_json_request(request): data = request.load_json() else: return json({'success': False, 'error': 'Wrong content type'}, 400) try: await save_resource(app, request.content_type, data) except Exception as e: return json({'success': False, 'error': str(e)}, 400) return json({'success': True}, 201) app.add_route(test_main, '/', methods=['POST']) return app
def create_app(**kwargs): @strawberry.type class Query: hello: str = "strawberry" schema = strawberry.Schema(query=Query) class GraphQLView(BaseGraphQLView): def get_root_value(self): return Query() app = Sanic("test-app-" + str(random())) app.add_route( GraphQLView.as_view(schema=schema, graphiql=kwargs.get("graphiql", True)), "/graphql", ) return app
async def test_atomic(test_client): @atomic async def handler(request): await asyncio.sleep(0) return response.json({}) app = Sanic(__name__) app.add_route(handler, '/') aiojobs_setup(app) client = await test_client(app) resp = await client.get('/') assert resp.status == 200 scheduler = get_scheduler_from_app(app) assert scheduler.active_count == 0 assert scheduler.pending_count == 0
def create_web_routes( app: Sanic, receive_protocol: T_WebProtocol, uri: str, request_handler: Any, ): if receive_protocol == "http": app.add_route( handler=request_handler, uri=uri, methods=["POST"], ) else: app.add_websocket_route( handler=request_handler, uri=uri, )
class SanicApp(object): def __init__(self, host: str = '0.0.0.0', port: int = 9876, debug: bool = True, worker_num: int = multiprocessing.cpu_count(), log: str = '', conf: str = ''): self.host = host self.port = port self.debug = debug self.workerNum = worker_num self.app = None self.log = log self.logger = None self.initApp() self.initLog() def disableLog(self): logger.setLevel(logging.WARNING) def initApp(self): if self.app == None: self.app = Sanic(name='agileutil' + str(uuid.uuid1())) def initLog(self): if self.logger == None and self.log != '': self.logger = Log(self.log) def getLogger(self): self.initLog() return self.logger def run(self): self.initApp() self.app.run(host=self.host, port=self.port, debug=self.debug, workers=self.workerNum, access_log=False) def route(self, path, className): className.setLogger(self.getLogger()) self.app.add_route(className.as_view(), path)
def _create_app(self) -> Sanic: """Create a new app with the following API routes.""" SanicConfig.LOGO = "" app = Sanic(__name__, log_config=log.NOTSET) app.add_route(self._start, "/start/<name>", methods=['PUT']) app.add_route(self._stop, "/stop", methods=['PUT']) app.add_route(self._running, "/running") app.add_route(self._available, "/available") return app
def test_dynamic_add_route_unhashable(): app = Sanic('test_dynamic_add_route_unhashable') async def handler(request, unhashable): return text('OK') app.add_route(handler, '/folder/<unhashable:[A-Za-z0-9/]+>/end/') request, response = app.test_client.get('/folder/test/asdf/end/') assert response.status == 200 request, response = app.test_client.get('/folder/test///////end/') assert response.status == 200 request, response = app.test_client.get('/folder/test/end/') assert response.status == 200 request, response = app.test_client.get('/folder/test/nope/') assert response.status == 404
def test_dynamic_add_route_regex(): app = Sanic('test_dynamic_route_int') async def handler(request, folder_id): return text('OK') app.add_route(handler, '/folder/<folder_id:[A-Za-z0-9]{0,4}>') request, response = app.test_client.get('/folder/test') assert response.status == 200 request, response = app.test_client.get('/folder/test1') assert response.status == 404 request, response = app.test_client.get('/folder/test-123') assert response.status == 404 request, response = app.test_client.get('/folder/') assert response.status == 200
def test_dynamic_add_route_string(): app = Sanic('test_dynamic_add_route_string') results = [] async def handler(request, name): results.append(name) return text('OK') app.add_route(handler, '/folder/<name:string>') request, response = sanic_endpoint_test(app, uri='/folder/test123') assert response.text == 'OK' assert results[0] == 'test123' request, response = sanic_endpoint_test(app, uri='/folder/favicon.ico') assert response.text == 'OK' assert results[1] == 'favicon.ico'
def test_dynamic_add_route_unhashable(): app = Sanic('test_dynamic_add_route_unhashable') async def handler(request, unhashable): return text('OK') app.add_route(handler, '/folder/<unhashable:[A-Za-z0-9/]+>/end/') request, response = sanic_endpoint_test(app, uri='/folder/test/asdf/end/') assert response.status == 200 request, response = sanic_endpoint_test(app, uri='/folder/test///////end/') assert response.status == 200 request, response = sanic_endpoint_test(app, uri='/folder/test/end/') assert response.status == 200 request, response = sanic_endpoint_test(app, uri='/folder/test/nope/') assert response.status == 404
def test_dynamic_add_route_number(): app = Sanic('test_dynamic_add_route_number') results = [] async def handler(request, weight): results.append(weight) return text('OK') app.add_route(handler, '/weight/<weight:number>') request, response = app.test_client.get('/weight/12345') assert response.text == 'OK' assert type(results[0]) is float request, response = app.test_client.get('/weight/1234.56') assert response.status == 200 request, response = app.test_client.get('/weight/1234-56') assert response.status == 404
def test_with_middleware(): app = Sanic('test_with_middleware') class DummyView(HTTPMethodView): def get(self, request): return text('I am get method') app.add_route(DummyView.as_view(), '/') results = [] @app.middleware async def handler(request): results.append(request) request, response = sanic_endpoint_test(app) assert response.text == 'I am get method' assert type(results[0]) is Request
def test_with_decorator(): app = Sanic('test_with_decorator') results = [] def stupid_decorator(view): def decorator(*args, **kwargs): results.append(1) return view(*args, **kwargs) return decorator class DummyView(HTTPMethodView): decorators = [stupid_decorator] def get(self, request): return text('I am get method') app.add_route(DummyView.as_view(), '/') request, response = sanic_endpoint_test(app, method="get") assert response.text == 'I am get method' assert results[0] == 1
def test_composition_view_runs_methods_as_expected(method): app = Sanic('test_composition_view') view = CompositionView() def first(request): assert request.stream is None return text('first method') view.add(['GET', 'POST', 'PUT'], first) view.add(['DELETE', 'PATCH'], lambda x: text('second method')) app.add_route(view, '/') assert app.is_request_stream is False if method in ['GET', 'POST', 'PUT']: request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'first method' if method in ['DELETE', 'PATCH']: request, response = getattr(app.test_client, method.lower())('/') assert response.text == 'second method'