Example #1
0
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)
Example #2
0
def test_bp_with_host():
    app = Sanic('test_bp_host')
    bp = Blueprint('test_bp_host', url_prefix='/test1', host="example.com")

    @bp.route('/')
    def handler(request):
        return text('Hello')

    @bp.route('/', host="sub.example.com")
    def handler(request):
        return text('Hello subdomain!')

    app.blueprint(bp)
    headers = {"Host": "example.com"}
    request, response = app.test_client.get(
        '/test1/',
        headers=headers)
    assert response.text == 'Hello'

    headers = {"Host": "sub.example.com"}
    request, response = app.test_client.get(
        '/test1/',
        headers=headers)

    assert response.text == 'Hello subdomain!'
Example #3
0
def test_bp_strict_slash():
    app = Sanic('test_route_strict_slash')
    bp = Blueprint('test_text')

    @bp.get('/get', strict_slashes=True)
    def handler(request):
        return text('OK')

    @bp.post('/post/', strict_slashes=True)
    def handler(request):
        return text('OK')

    app.blueprint(bp)

    request, response = app.test_client.get('/get')
    assert response.text == 'OK'
    assert response.json == None

    request, response = app.test_client.get('/get/')
    assert response.status == 404

    request, response = app.test_client.post('/post/')
    assert response.text == 'OK'

    request, response = app.test_client.post('/post')
    assert response.status == 404
Example #4
0
def blueprint_app():
    app = Sanic('blueprints')

    first_print = Blueprint('first', url_prefix='/first')
    second_print = Blueprint('second', url_prefix='/second')

    @first_print.route('/foo')
    def foo():
        return text('foo from first')

    @first_print.route('/foo/<param>')
    def foo_with_param(request, param):
        return text(
            'foo from first : {}'.format(param))

    @second_print.route('/foo')  # noqa
    def foo():
        return text('foo from second')

    @second_print.route('/foo/<param>')  # noqa
    def foo_with_param(request, param):
        return text(
            'foo from second : {}'.format(param))

    app.blueprint(first_print)
    app.blueprint(second_print)

    return app
Example #5
0
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
Example #6
0
def create_app(ignore_exceptions=None, debug=False, **config):
    import os
    app = Sanic(__name__)
    for key, value in config.items():
        app.config[key] = value

    app.debug = debug

    if ignore_exceptions:
        app.config['RAVEN_IGNORE_EXCEPTIONS'] = ignore_exceptions

    @app.route('/an-error/', methods=['GET', 'POST'])
    def an_error(request):
        raise ValueError('hello world')

    @app.route('/log-an-error/', methods=['GET'])
    def log_an_error(request):
        logger = logging.getLogger('random-logger')
        logger.error('Log an error')
        return response.text('Hello')

    @app.route('/capture/', methods=['GET', 'POST'])
    def capture_exception(request):
        try:
            raise ValueError('Boom')
        except Exception:
            request.app.extensions['sentry'].captureException()
        return response.text('Hello')

    @app.route('/message/', methods=['GET', 'POST'])
    def capture_message(request):
        request.app.extensions['sentry'].captureMessage('Interesting')
        return response.text('World')

    return app
Example #7
0
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
Example #8
0
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
Example #9
0
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
Example #10
0
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
Example #11
0
def test_bp_exception_handler():
    app = Sanic('test_middleware')
    blueprint = Blueprint('test_middleware')

    @blueprint.route('/1')
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route('/2')
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route('/3')
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/1')
    assert response.status == 400


    request, response = sanic_endpoint_test(app, uri='/2')
    assert response.status == 200
    assert response.text == 'OK'

    request, response = sanic_endpoint_test(app, uri='/3')
    assert response.status == 200
Example #12
0
def test_bp_listeners():
    app = Sanic('test_middleware')
    blueprint = Blueprint('test_middleware')

    order = []

    @blueprint.listener('before_server_start')
    def handler_1(sanic, loop):
        order.append(1)

    @blueprint.listener('after_server_start')
    def handler_2(sanic, loop):
        order.append(2)

    @blueprint.listener('after_server_start')
    def handler_3(sanic, loop):
        order.append(3)

    @blueprint.listener('before_server_stop')
    def handler_4(sanic, loop):
        order.append(5)

    @blueprint.listener('before_server_stop')
    def handler_5(sanic, loop):
        order.append(4)

    @blueprint.listener('after_server_stop')
    def handler_6(sanic, loop):
        order.append(6)

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/')

    assert order == [1,2,3,4,5,6]
Example #13
0
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
Example #14
0
def test_static_file(static_file_directory, file_name):
    app = Sanic('test_static')
    app.static(
        '/testing.file', get_file_path(static_file_directory, file_name))

    request, response = app.test_client.get('/testing.file')
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
Example #15
0
def test_static_directory(file_name, base_uri, static_file_directory):

    app = Sanic('test_static')
    app.static(base_uri, static_file_directory)

    request, response = app.test_client.get(
        uri='{}/{}'.format(base_uri, file_name))
    assert response.status == 200
    assert response.body == get_file_content(static_file_directory, file_name)
Example #16
0
def test_single_listener(listener_name):
    """Test that listeners on their own work"""
    random_name_app = Sanic(''.join(
        [choice(ascii_letters) for _ in range(choice(range(5, 10)))]))
    output = list()
    # Register listener
    random_name_app.listener(listener_name)(
        create_listener(listener_name, output))
    start_stop_app(random_name_app)
    assert random_name_app.name + listener_name == output.pop()
Example #17
0
def test_all_listeners():
    random_name_app = Sanic(''.join(
        [choice(ascii_letters) for _ in range(choice(range(5, 10)))]))
    output = list()
    for listener_name in AVAILABLE_LISTENERS:
        listener = create_listener(listener_name, output)
        random_name_app.listener(listener_name)(listener)
    start_stop_app(random_name_app)
    for listener_name in AVAILABLE_LISTENERS:
        assert random_name_app.name + listener_name == output.pop()
Example #18
0
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
Example #19
0
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
Example #20
0
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
Example #21
0
def test_fails_if_endpoint_not_found():
    app = Sanic('fail_url_build')

    @app.route('/fail')
    def fail():
        return text('this should fail')

    with pytest.raises(URLBuildError) as e:
        app.url_for('passes')

    assert str(e.value) == 'Endpoint with name `passes` was not found'
Example #22
0
def test_simple_url_for_getting_with_more_params(args, url):
    app = Sanic('more_url_build')

    @app.route('/myurl')
    def passes(request):
        return text('this should pass')

    assert url == app.url_for('passes', **args)
    request, response = app.test_client.get(url)
    assert response.status == 200
    assert response.text == 'this should pass'
Example #23
0
def test_fails_url_build_if_params_not_passed():
    app = Sanic('fail_url_build')

    @app.route('/fail')
    def fail():
        return text('this should fail')

    with pytest.raises(ValueError) as e:
        app.url_for('fail', _scheme='http')

    assert str(e.value) == 'When specifying _scheme, _external must be True'
Example #24
0
def test_bp_with_url_prefix():
    app = Sanic('test_text')
    bp = Blueprint('test_text', url_prefix='/test1')

    @bp.route('/')
    def handler(request):
        return text('Hello')

    app.blueprint(bp)
    request, response = sanic_endpoint_test(app, uri='/test1/')

    assert response.text == 'Hello'
Example #25
0
def test_bp():
    app = Sanic('test_text')
    bp = Blueprint('test_text')

    @bp.route('/')
    def handler(request):
        return text('Hello')

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

    assert response.text == 'Hello'
Example #26
0
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'
Example #27
0
def test_bp():
    app = Sanic('test_text')
    bp = Blueprint('test_text')

    @bp.route('/')
    def handler(request):
        return text('Hello')

    app.blueprint(bp)
    request, response = app.test_client.get('/')
    assert app.is_request_stream is False

    assert response.text == 'Hello'
Example #28
0
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 /'
Example #29
0
def test_register_system_signals():
    """Test if sanic register system signals"""
    app = Sanic('test_register_system_signals')

    @app.route('/hello')
    async def hello_route(request):
        return HTTPResponse()

    app.run(HOST, PORT,
            before_start=set_loop,
            after_start=stop,
            after_stop=after)
    assert calledq.get() == True
Example #30
0
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
Example #31
0
def test_remove_inexistent_route():
    app = Sanic('test_remove_inexistent_route')

    with pytest.raises(RouteDoesNotExist):
        app.remove_route('/test')
Example #32
0
import os
import socket
import logging
from sanic import Sanic
from sanic.response import json
from sanic_function_deps.function_helper import create_function_deps

app = Sanic()
function_deps = create_function_deps()
logger = logging.getLogger()

APP_TOKEN = os.environ['TOKEN']
APP_PORT = 8000
APP_TIMEOUT = int(os.environ.get('TIMEOUT', 10))


@app.route('/', methods=["POST"])
@function_deps(['token', 'domain', 'port'])
async def test(token: str, domain: str, port: int):

    if token != APP_TOKEN:
        return json({
            'error': 'Incorrect token',
            'domain': domain,
            'port': port,
            'status': 'N/A'
        })

    s = socket.socket()
    s.settimeout(APP_TIMEOUT)
    try:
Example #33
0
)
from libs.permissions.projects import has_project_permissions
from libs.redis_db import RedisToStream
from polyaxon.settings import CeleryQueues, RoutingKeys
from streams.authentication import authorized
from streams.consumers import Consumer
from streams.socket_manager import SocketManager

logger = logging.getLogger('polyaxon.streams.api')

SOCKET_SLEEP = 2
MAX_RETRIES = 7
RESOURCES_CHECK = 7
CHECK_DELAY = 5

app = Sanic(__name__)


def _get_project(username, project_name):
    try:
        return Project.objects.get(name=project_name, user__username=username)
    except Project.DoesNotExist:
        raise exceptions.NotFound('Project was not found')


def _get_experiment(project, experiment_sequence):
    try:
        return Experiment.objects.get(project=project, sequence=experiment_sequence)
    except (Experiment.DoesNotExist, ValidationError):
        raise exceptions.NotFound('Experiment was not found')
Example #34
0
def test_app_registry_retrieval_from_multiple():
    instance = Sanic("test")
    Sanic("something_else")
    assert Sanic.get_app("test") is instance
Example #35
0
def test_get_app_does_not_exist():
    with pytest.raises(SanicException,
                       match='Sanic app name "does-not-exist" not found.'):
        Sanic.get_app("does-not-exist")
Example #36
0
def test_get_app_default():
    instance = Sanic("test")
    assert Sanic.get_app() is instance
Example #37
0
def test_app_no_registry():
    Sanic("no-register", register=False)
    with pytest.raises(SanicException,
                       match='Sanic app name "no-register" not found.'):
        Sanic.get_app("no-register")
Example #38
0
import asyncio
from datetime import datetime
import multiprocessing
import time

from sanic import Sanic, response
from sanic.exceptions import abort, SanicException
from sanic.log import logger
from sanic_jinja2 import SanicJinja2

from .model import Secret
from . import settings

app = Sanic('seenoevil')
app.static('/static', settings.STATIC_PATH)
jinja = SanicJinja2(app)
last_cleanup = multiprocessing.Value('f', time.time())


@app.route("/", methods=['GET', 'POST'])
async def create(request):
    if request.method == 'POST':
        request.json or abort(400)
        try:
            secret = Secret.deserialize(request.json)
        except (TypeError, ValueError):
            abort(400)
        secret.save(force_insert=True)
        return response.json({'path': app.url_for('show', token=secret.token)})
    else:
        context = {
Example #39
0
def create_app(
    api_title: str, api_description: str, blueprints: Iterable[Blueprint], managers: BaseManagers,
) -> Sanic:
    """
    Create the Sanic application.

    :param api_title: the title of the API in the /swagger endpoint.
    :param api_description: the description of the API in /swagger endpoint.
    :param blueprints: the Sanic blueprints to register.
    :param managers: the microservice's managers.
    :return: the created Sanic application.
    """
    app = Sanic(__name__, log_config=get_sanic_logger_config(config.LOG_JSON_INDENT))
    app.config.TESTING = config.ENV == Environment.TESTING

    swagger_config = dict(
        API_TITLE=api_title,
        API_DESCRIPTION=api_description,
        API_SCHEMES=["https"],
        API_VERSION="1.0.0",
        SWAGGER_UI_CONFIGURATION=dict(
            validatorUrl=None, displayRequestDuration=True, docExpansion="list",
        ),
    )
    app.config.update(swagger_config)

    monitoring_registry = initialize_monitoring()

    @app.route("/")
    @doc.summary("Health check.")
    @doc.response(HTTPStatus.NO_CONTENT.value, "Ok", description="The server is running ok.")
    async def health_check(request: Request) -> HTTPResponse:
        return HTTPResponse(status=HTTPStatus.OK)

    # TODO: Evaluate whether to expose it over another port.
    @app.route("/metrics")
    @doc.summary("Expose Prometheus metrics.")
    def metrics(request: Request) -> HTTPResponse:
        latest_metrics = prometheus_client.generate_latest(monitoring_registry)
        return HTTPResponse(
            body=latest_metrics.decode("utf-8"),
            content_type=prometheus_client.CONTENT_TYPE_LATEST,
            headers={"Content-Length": str(len(latest_metrics))},
        )

    @app.listener("after_server_start")
    async def after_server_start(*args: Any, **kwargs: Any) -> None:
        await managers.initialize()

    @app.listener("before_server_stop")
    async def before_server_stop(*args: Any, **kwargs: Any) -> None:
        await managers.teardown()

    @app.listener("after_server_stop")
    async def after_server_stop(*args: Any, **kwargs: Any) -> None:
        multiprocess.mark_process_dead(os.getpid())

    @app.middleware("request")
    async def before_request(request: Request) -> None:
        sanic_before_request_handler(request)

    @app.middleware("response")
    async def after_response(request: Request, response: HTTPResponse) -> None:
        sanic_after_request_handler(request, response)

    @app.exception(ApiException)
    async def handle_exception(request: Request, exception: ApiException) -> HTTPResponse:
        _LOGGER.exception(exception)
        return json_response(
            body={"error_code": exception.error_code, "message": exception.error_message},
            status=exception.status_code,
        )

    @app.exception(SanicException)
    async def handle_unknown_exception(request: Request, exception: SanicException) -> HTTPResponse:
        _LOGGER.exception(exception)
        return json_response(
            body={"error_code": ApiException.error_code, "message": ApiException.error_message},
            status=HTTPStatus(exception.status_code),
        )

    @app.exception(Exception)
    async def handle_bare_exception(request: Request, exception: Exception) -> HTTPResponse:
        _LOGGER.exception(exception)
        return json_response(
            body={"error_code": ApiException.error_code, "message": ApiException.error_message},
            status=ApiException.status_code,
        )

    for blueprint in blueprints:
        app.blueprint(blueprint)
    app.blueprint(swagger_blueprint)

    return app
Example #40
0
def test_env_prefix_float_values():
    environ["MYAPP_TEST_ROI"] = "2.3"
    app = Sanic(name=__name__, env_prefix="MYAPP_")
    assert app.config.TEST_ROI == 2.3
    del environ["MYAPP_TEST_ROI"]
Example #41
0
def test_env_prefix_string_value():
    environ["MYAPP_TEST_TOKEN"] = "somerandomtesttoken"
    app = Sanic(name=__name__, env_prefix="MYAPP_")
    assert app.config.TEST_TOKEN == "somerandomtesttoken"
    del environ["MYAPP_TEST_TOKEN"]
Example #42
0
def test_update(app: Sanic, conf_object):
    app.update_config(conf_object)
    assert app.config["TEST_SETTING_VALUE"] == 1
Example #43
0
def test_update_from_lowercase_key(app: Sanic):
    d = {"test_setting_value": 1}
    app.update_config(d)
    assert "test_setting_value" not in app.config
Example #44
0
# @Author: Huang Sizhe <huangsizhe>
# @Date:   08-Apr-2017
# @Email:  [email protected]
# @Last modified by:   huangsizhe
# @Last modified time: 08-Apr-2017
# @License: MIT

from sanic import Sanic
from sanic.response import json, text
from sanic_mongo import GridFS

app = Sanic(__name__)
mongo_uri = "mongodb://{host}:{port}/{database}".format(database='test',
                                                        port=27017,
                                                        host='localhost')

GridFS.SetConfig(app, test_fs=(mongo_uri, "fs"))
GridFS(app)


@app.get('/pics')
async def get(request):
    cursor = app.GridFS["test_fs"].find()
    result = [{i._id: i.name} async for i in cursor]
    return json({"result": result})


@app.post('/pics')
async def new(request):
    doc = request.files.get('file')
Example #45
0
def test_app_set_context(app):
    app.ctx.foo = 1

    retrieved = Sanic.get_app(app.name)
    assert retrieved.ctx.foo == 1
from re import match as regex_match

from services.loggerServices.loggerService import LoggerService
from services.mongoDbService.leagueProvider import (parse_league_from_request,
                                                    parse_league_from_db)
from services.mongoDbService.teamProvider import (
    parse_team_from_request, parse_team_from_db, find_team_most_scored,
    find_team_least_scored, find_team_most_wins, find_team_least_wins)
from services.mongoDbService.matchProvider import (
    parse_match_from_db, parse_match_from_request,
    parse_ended_match_from_request)
from services.mongoDbService.mongoDbService import MongoDbService
from models.models import (LeagueSchema, TeamSchema, MatchSchema)

logger = LoggerService().logger
app = Sanic()
db = MongoDbService()
"""
League Routes
"""


@app.post('/league')
async def post_handler_league(request):
    """
    Create a new League
    :param request:
        name : String - the league name
        season : Number - the season year
    :return
    request example
Example #47
0
def test_get_app_no_default():
    with pytest.raises(SanicException,
                       match="No Sanic apps have been registered."):
        Sanic.get_app()
Example #48
0
from sanic import Sanic
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text

bp = Blueprint('blueprint_request_stream')
app = Sanic('request_stream')


class SimpleView(HTTPMethodView):
    @stream_decorator
    async def post(self, request):
        result = ''
        while True:
            body = await request.stream.get()
            if body is None:
                break
            result += body.decode('utf-8')
        return text(result)


@app.post('/stream', stream=True)
async def handler(request):
    async def streaming(response):
        while True:
            body = await request.stream.get()
            if body is None:
                break
            body = body.decode('utf-8').replace('1', 'A')
Example #49
0
def test_get_app_does_not_exist_force_create():
    assert isinstance(Sanic.get_app("does-not-exist", force_create=True),
                      Sanic)
Example #50
0
#!/usr/bin/env python3
#


from sanic import Sanic
from .api import api

app = Sanic(__name__)
app.config.from_envvar('CHEKAWA_SETTINGS')
app.blueprint(api)


# 路由
'''
url: The full URL of the request, ie: http://localhost:8090/posts/1/?foo=bar

scheme: The URL scheme associated with the request: http or https

host: The host associated with the request: localhost:8080

path: The path of the request: /posts/1/

query_string: The query string of the request: foo=bar or a blank string ''

uri_template: Template for matching route handler: /posts/<id>/

token: The value of Authorization header: Basic YWRtaW46YWRtaW4=
'''
Example #51
0
def test_app_registry_wrong_type():
    with pytest.raises(SanicException,
                       match="Registered app must be an instance of Sanic"):
        Sanic.register_app(1)
Example #52
0
def test_empty_load_env_prefix(env_prefix):
    environ["SANIC_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__, env_prefix=env_prefix)
    assert getattr(app.config, "TEST_ANSWER", None) is None
    del environ["SANIC_TEST_ANSWER"]
Example #53
0
def test_app_registry_retrieval():
    instance = Sanic("test")
    assert Sanic.get_app("test") is instance
Example #54
0
#!/usr/bin/env python
# coding: utf8
from bson.json_util import dumps
from sanic import response, Sanic
from sanic.request import Request

from shoppinglist.configuration import read_config
from shoppinglist.database import Database

# Initialize the config
_config = read_config('shoppinglist.ini')

# Initialize the sanic app
_app = Sanic()

_db = Database(
    _config('url', namespace='mongo'),
    _config('database', namespace='mongo'),
)


def main():
    # Run the app
    _app.run(
        host=_config('host', namespace='server'),
        port=_config('port', namespace='server', parser=int),
    )


@_app.route('/')
async def home(request):
Example #55
0
def test_app_name_required():
    with pytest.raises(SanicException):
        Sanic()
Example #56
0
def test_auto_bool_env_prefix():
    environ["SANIC_TEST_ANSWER"] = "True"
    app = Sanic(name=__name__)
    assert app.config.TEST_ANSWER is True
    del environ["SANIC_TEST_ANSWER"]
Example #57
0
def test_app_registry():
    instance = Sanic("test")
    assert Sanic._app_registry["test"] is instance
Example #58
0
def test_env_prefix():
    environ["MYAPP_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__, env_prefix="MYAPP_")
    assert app.config.TEST_ANSWER == 42
    del environ["MYAPP_TEST_ANSWER"]
Example #59
0
File: main.py Project: AhmerW/Edus
import os
import ssl
import sys
import asyncio
import platform
import threading
from sanic import Sanic
from functools import wraps
from sanic.response import json, text
from sanic.exceptions import ServerError, abort, NotFound
from gateway import Gateway

_cls = "cls" if platform.system().lower().startswith("win") else "clear"

app = Sanic(__name__)
VERSION = 'v1'
MAIN_ROUTE = '/api/{0}/'.format(VERSION)

ROUTES = [
    '{0}messages/add/'.format(MAIN_ROUTE), '{0}login/'.format(MAIN_ROUTE),
    '{0}register/'.format(MAIN_ROUTE), '{0}friend/add/'.format(MAIN_ROUTE),
    '{0}gather'.format(MAIN_ROUTE)
]

server = Gateway()


def authorized(func):
    @wraps(func)
    async def deco(req, *args, **kwargs):
        uid, token = req.form.get('uid'), req.form.get('token')
Example #60
0
def test_auto_env_prefix():
    environ["SANIC_TEST_ANSWER"] = "42"
    app = Sanic(name=__name__)
    assert app.config.TEST_ANSWER == 42
    del environ["SANIC_TEST_ANSWER"]