Beispiel #1
0
    def __init__(self):
        routes = import_module(settings.APISTAR_ROUTE_CONF).routes

        routes.append(Include('/static', static_urls))
        routes.append(Include('/docs', docs_urls))

        self.django_wsgi_app = get_wsgi_application()
        self.apistar_wsgi_app = CORSApp(routes=routes,
                                        settings=settings.APISTAR_SETTINGS)
Beispiel #2
0
def create_routes():
    """Create the routes for the application."""
    return [
        Route('/', 'GET', welcome),
        Route('/authorities/', 'GET', get_authorities),
        Route('/authorities/{authority}/gen/', 'GET', get_authority_generation),
        Route('/authorities/{authority}/load/', 'GET', get_authority_load),
        Route('/authorities/{authority}/lmp/', 'GET', get_authority_lmp),
        Route('/authorities/{authority}/trade/', 'GET', get_authority_trade),
        Include('/docs', docs_urls),
        Include('/static', static_urls)
    ]
Beispiel #3
0
def login():


routes = [
    Route('/', 'GET', welcome),
    Include('/docs', docs_urls),
    Include('/static', static_urls)
]

app = App(routes=routes)


if __name__ == '__main__':
    app.main()
Beispiel #4
0
def routing(controller):
    """
    获取当前Controller下所有route及其子Controller组成的Include
    :param controller:
    :return:
    """
    if not hasattr(controller, "prefix"):
        raise RuntimeError(f"{controller} is not routed! ")
    routes = []
    instance = controller()
    for name in vars(controller).keys():
        prop = getattr(controller, name)
        if hasattr(prop, "routes"):
            for route in prop.routes:
                route.controller = instance
                add_annotation(route.handler, find_ancestor(controller))
                routes.append(route)

    for child_controller in controller.__subclasses__():
        child_include = routing(child_controller)
        if child_include:
            routes.append(child_include)

    if routes:
        return Include(controller.prefix, controller.name, routes)
Beispiel #5
0
def process_app_routes(app, prefix: typing.Union[str, tuple] = None):
    """
    For a given dict of app data figure out if the app is nested
    and if so convert the routes to an Include with the appropriate
    URL prefix.
    """

    routes = app.get("routes")
    app_path = app.get("app_path")
    inc_name = ""
    url_prefix = "/"

    # If the app has no routes or is not nested (no or empty app_path), do nothing.
    if not routes or not app_path:
        return app

    if isinstance(prefix, tuple):
        url_prefix = prefix[0]
        if len(prefix) == 2:
            inc_name = prefix[1] + ":"
    elif prefix:
        url_prefix = prefix

    if url_prefix[-1] != "/":
        url_prefix += "/"

    inc_name += ":".join(app_path)

    namespaced_routes = [
        Route(
            r.url,
            r.method,
            r.handler,
            name=inc_name + ":" + r.name,
            documented=r.documented,
            standalone=r.standalone,
        ) for r in routes
    ]

    # Build an Include for the set of nested URLs with the matching prefix
    # for the directory structure
    # If a prefix param is present, pre-pend it as well
    app["routes"] = [
        Include(url_prefix + "/".join(app_path),
                name=inc_name,
                routes=namespaced_routes)
    ]

    return app
Beispiel #6
0
    def routes(self, admin="/admin") -> typing.List[Include]:
        """
        Generate the list of routes for all resources and admin views.

        :param admin: Admin path, disabled if None.
        :return: List of routes.
        """
        r = [
            Include(opts.url, r.name, r.routes)
            for r, opts in self.resources.items()
        ]

        private_routes = []

        if admin:
            a = Admin(*[r for r, opts in self.resources.items() if opts.admin])
            r.append(Include(admin, "admin", a.routes, documented=False))
            private_routes += a.metadata_routes

        if private_routes:
            r.append(
                Include("/_crud", "crud", private_routes, documented=False))

        return r
Beispiel #7
0
 def routes(cls) -> Include:
     """
     Returns:
         Les routes pour chaque action
     """
     return Include(
         url=f"/{cls.model.url_name}",
         name=cls.model.url_name,
         routes=[
             Route("/add/{acte_id}", method="POST", handler=cls.add_item()),
             Route("/{item_id}/", method="DELETE", handler=cls.delete_item()),
             # Route("/{acte_id}/", method="GET", handler=cls.one()),
             Route("/{item_id}/", method="PUT", handler=cls.update_item()),
             # Route("/patient/{patient_id}/", method="GET", handler=cls.liste()),
         ],
     )
Beispiel #8
0
    def do_routes(cls) -> Include:
        """
        Returns:
            Include: Les routes pour chaque action
        """

        bases_routes = [
            Route("/", method="POST", handler=cls.add()),
            Route("/{acte_id}/", method="GET", handler=cls.one()),
            Route("/{acte_id}/", method="DELETE", handler=cls.delete()),
            Route("/{acte_id}/", method="PUT", handler=cls.update()),
            Route("/patient/{patient_id}/", method="GET", handler=cls.liste()),
        ]

        routes = [*bases_routes, *cls.routes_supplementaires()]

        return Include(url=f"/{cls.model.url_name}",
                       name=cls.model.url_name,
                       routes=routes)
Beispiel #9
0
def routing(service, parent_prefix):
    """
    获取当前Service下所有route及其子Service组成的Include
    :param service:
    :param parent_prefix:
    :return:
    """
    if not hasattr(service, "prefix") or service.prefix == parent_prefix:
        raise RuntimeError(f"{service} is not routed! ")
    routes = []
    for name in dir(service):
        prop = getattr(service, name)
        if hasattr(prop, "routes"):
            for route in prop.routes:
                route.service = service
            routes.extend(prop.routes)

    for child_service in service.children:
        child_include = routing(child_service, service.prefix)
        if child_include:
            routes.append(child_include)

    if routes:
        return Include(service.prefix, service.name, routes)
Beispiel #10
0
from apistar import Include, Route
from apistar.handlers import static_urls

from core import views


routes = [
    Route('/', 'GET', views.welcome),
    Route('/me', 'POST', views.me, name='me'),
    Route('/criar-produto', 'POST', views.criar_produto, name='criar_produto'),
    Route('/listar-produtos', 'GET', views.listar_produtos, name='listar_produtos'),
    Route('/valida-cpf', 'POST', views.valida_cpf, name='valida_cpf'),
    Route('/criar-usuario', 'POST', views.criar_usuario, name='criar_usuario'),
    Route('/listar-usuarios', 'GET', views.listar_usuarios, name='listar_usuarios'),
    Include('/static', static_urls)
]
Beispiel #11
0
def subpath(var: schema.Integer):
    return {'var': var}


app = App(routes=[
    Route('/found/', 'GET', found),
    Route('/path_params/{var}/', 'GET', path_params),
    Route('/path_param/{var}/', 'GET', path_param),
    Route('/int/{var}/', 'GET', path_param_with_int),
    Route('/full_path/{var}', 'GET', path_param_with_full_path),
    Route('/max_length/{var}/', 'GET', path_param_with_max_length),
    Route('/number/{var}/', 'GET', path_param_with_number),
    Route('/integer/{var}/', 'GET', path_param_with_integer),
    Include('/subpath', [
        Route('/{var}/', 'GET', subpath),
    ]),
])

client = TestClient(app)


def test_200():
    response = client.get('/found/')
    assert response.status_code == 200
    assert response.json() == {'message': 'Found'}


def test_404():
    response = client.get('/404/')
    assert response.status_code == 404
Beispiel #12
0
class Env(environment.Environment):
    properties = {
        'DEBUG': typesystem.boolean(default=False),
        'DATABASE_URL': typesystem.string()
    }


env = Env()

transcription_routes = [
    Route('/', 'GET', routes.get_unvalidated_transcription),
    Route('/export', 'GET', routes.export_validated_transcriptions_as_csv),
    Route('/', 'POST', routes.create_validated_transcription)
]

routes = [Include('/transcription', transcription_routes)]

# Configure database settings.
settings = {
    "DATABASE": {
        "URL": env['DATABASE_URL'],
        "METADATA": Base.metadata
    },
}


class App(WSGIApp):
    def __call__(self, environ, start_response):
        cors = CORS(super().__call__, headers='*', methods='*', origin='*')
        return cors(environ, start_response)
Beispiel #13
0
from apistar import Include, Route
from apistar.handlers import docs_urls, static_urls, serve_static
from apps.details import detail_routes
from apps.files import file_routes
from apps.users import user_routes
from apps.login import login, logout
from apps.index import index

api_routes = [
    Include('/details', detail_routes),
    Include('/files', file_routes),
    Include('/users', user_routes),
    Route('/login', 'POST', login),
    Route('/logout', 'GET', logout),
]

routes = [
    Include('/api', api_routes),
    Include('/docs', docs_urls),
    Route('/dist/{path}', 'GET', serve_static),
    Route('/', 'GET', index),
    # Include('/static', static_urls)
]

for path in ('/details', '/login', '/fileList', '/admin'):
    routes.append(Route(path, 'GET', index, name=path))
        },
    )


def download_response_filename_in_url():
    return http.Response(b"...", headers={"Content-Type": "image/jpeg"})


routes = [
    Include(
        url="/parameters",
        name="parameters",
        routes=[
            Route(url="/no-parameters/", method="GET", handler=no_parameter),
            Route(url="/query-parameter/",
                  method="GET",
                  handler=query_parameter),
            Route(url="/body-parameter/",
                  method="POST",
                  handler=body_parameter),
        ],
    ),
    Include(
        url="/responses",
        name="responses",
        routes=[
            Route(url="/text-response/", method="GET", handler=text_response),
            Route(url="/empty-response/", method="GET",
                  handler=empty_response),
            Route(url="/error-response/", method="GET",
                  handler=error_response),
Beispiel #15
0
        "iat": pendulum.now(),
        "exp": pendulum.now() + pendulum.Duration(seconds=1000),
    }
    token = jwt.encode(payload)
    if token is None:
        raise exceptions.ConfigurationError("échec de l'encodage jwt")

    return token


routes_users = Include(
    url="/users",
    name="users",
    routes=[
        Route(url="/login/", method="POST", handler=login, name="login"),
        # Route(url="/", method="GET", handler=liste),
        # Route(url="/{id}/", method="PUT", handler=update),
        # # Route(url="/patients/", method="DELETE", handler=delete),
        # Route(url="/{id}/", method="DELETE", handler=delete),
        # Route(url="/{id}/", method="GET", handler=get),
    ],
)
"""
# MEDECIN = "medecin"
# SECRETAIRE = "secretaire"
# INTERNE = "interne"
# REMPLACANT = "remplacant"
# STATUT = (
#     (MEDECIN, 'Médecin'),
#     (SECRETAIRE, 'Secrétaire'),
#     (INTERNE, "Interne"),
#     (REMPLACANT, "Remplaçant"),
Beispiel #16
0
        try:
            payload = jwt.decode(token,
                                 settings['JWT_SECRET'],
                                 algorithms=['HS256'])
            return Authenticated(payload['user_id'])
        except jwt.exceptions.InvalidTokenError:
            raise Unauthorized()


@annotate(permissions=[])
async def create_token(data: LoginData, session: Session, settings: Settings):
    user = session.query(User).filter_by(email=data['username']).first()
    if not user or not user.password == data['password']:
        raise BadRequest({"message": "Email and password do not match"})
    expires = (datetime.now() + timedelta(days=5)).timestamp()
    token = jwt.encode({
        'user_id': user.id,
        'exp': int(expires)
    },
                       settings['JWT_SECRET'],
                       algorithm='HS256')

    return {
        'token_type': 'Bearer',
        'access_token': token.decode('utf-8'),
        'expires_in': int(expires),
    }


routes = Include('/tokens', [Route('/', 'POST', create_token)])
Beispiel #17
0
from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import welcome, student, students_Id
from project.views import list_tasks, add_task, delete_task, patch_task

task_routes = [
    Route('/', 'GET', list_tasks),
    Route('/', 'POST', add_task),
    Route('/{task_id}/', 'DELETE', delete_task),
    Route('/{task_id}/', 'PATCH', patch_task),
]

routes = [
    Route('/', 'GET', welcome),
    Include('/task', task_routes),
    Include('/docs', docs_routes),
    Include('/static', static_routes),
    Route('/students/id/{iD}', 'GET', students_Id),
    Route('/students', 'GET', student)
]
Beispiel #18
0
 def _blueprint_to_include(self, blueprint: Blueprint):
     temp_app = Flask('temp_app')
     temp_app.register_blueprint(blueprint)
     routes = self._extract_routes(temp_app)
     url_prefix = blueprint.url_prefix
     return Include(url='', name=blueprint.name, routes=routes)
Beispiel #19
0
from wsgicors import CORS
from apistar import App, Include

from settings import jwt_settings

from components.auth import Auth
from middlewares import EventHookAuth

from api import auth
from api import users
from api import status
from api import features
from api import services

components = [Auth(jwt_settings)]
event_hooks = [EventHookAuth()]

routes = [
    Include("/", name="Status", routes=status.routes),
    Include("/auth", name="Authentication", routes=auth.routes),
    Include("/users", name="User", routes=users.routes),
    Include("/features", name="Feature", routes=features.routes),
    Include("/services", name="Service", routes=services.routes),
]

app = App(routes=routes, components=components, event_hooks=event_hooks)
app = CORS(app, headers="*", methods="*", origin="*", maxage="86400")
Beispiel #20
0
    else:
        raise exceptions.Forbidden(
            f"Action non autorisée pour l'utilisateur {user.username}")


def update(new_data: PatientUpdateSchema,
           patient_id: int) -> http.JSONResponse:
    """modify patients

    Args:
        new_data: Rien n'est requis.
        id: patient id.
    """
    to_update = get_or_404(db.Patient, patient_id)
    to_update.set(**{k: v for k, v in new_data.items() if v})
    return http.JSONResponse(to_update.dico, status_code=201)


routes_patients = Include(
    url="/patients",
    name="patients",
    routes=[
        Route(url="/", method="POST", handler=add),
        Route(url="/", method="GET", handler=liste),
        Route(url="/{patient_id}/", method="PUT", handler=update),
        Route(url="/{patient_id}/", method="DELETE", handler=delete),
        Route(url="/{patient_id}/", method="GET", handler=one),
    ],
)
#
Beispiel #21
0
from apistar import Include

from idunn import settings
from idunn.utils.index_names import IndexNamesSettingsComponent
from idunn.utils.es_wrapper import ElasticSearchComponent
from idunn.utils.logging import init_logging, LogErrorHook
from idunn.utils.cors import CORSHeaders
from idunn.utils.app import IdunnApp
from idunn.api.urls import get_api_urls
from apistar_prometheus import PrometheusComponent, PrometheusHooks

init_logging(settings)

routes = [
    Include('/v1', name='v1', routes=get_api_urls(settings)),
]

components = [
    settings,
    ElasticSearchComponent(),
    IndexNamesSettingsComponent(),
    PrometheusComponent()
]

# WARNING: using Classes (and not instances) in hooks list causes a memory leak.
# See https://github.com/encode/apistar/issues/606 for more details
event_hooks = [LogErrorHook(), CORSHeaders(), PrometheusHooks()]

app = IdunnApp(routes=routes,
               schema_url='/schema',
               components=components,
Beispiel #22
0
from apistar import App, Include
from project.hooks import Cors, MustBeAuthenticated
from users.routes import routes as users_routes
from users.models import UserComponent

routes = [
    Include('', name='users', routes=users_routes),
]

event_hooks = [Cors, MustBeAuthenticated]
components = [UserComponent()]

app = App(routes=routes, event_hooks=event_hooks, components=components)

if __name__ == '__main__':
    app.serve('0.0.0.0', 5000, debug=True)
Beispiel #23
0
def subpath(var: typesystem.Integer):
    return {'var': var}


routes = [
    Route('/found/', 'GET', found),
    Route('/path_params/{var}/', 'GET', path_params),
    Route('/path_param/{var}/', 'GET', path_param),
    Route('/int/{var}/', 'GET', path_param_with_int),
    Route('/full_path/{var}', 'GET', path_param_with_full_path),
    Route('/max_length/{var}/', 'GET', path_param_with_max_length),
    Route('/number/{var}/', 'GET', path_param_with_number),
    Route('/integer/{var}/', 'GET', path_param_with_integer),
    Route('/string/{var}/', 'GET', path_param_with_string),
    Include('/subpath', [
        Route('/{var}/', 'GET', subpath),
    ],
            namespace='included'),
    Route('/x', 'GET', lambda: 1, name='x'),
    Include('/another_subpath', [Route('/x', 'GET', lambda: 1, name='x2')]),
]
wsgi_app = WSGIApp(routes=routes)
async_app = ASyncIOApp(routes=routes)

wsgi_client = TestClient(wsgi_app)
async_client = TestClient(async_app)


@pytest.mark.parametrize('client', [wsgi_client, async_client])
def test_200(client):
    response = client.get('/found/')
    assert response.status_code == 200
Beispiel #24
0
from apistar.frameworks.asyncio import ASyncIOApp as App
from apistar.handlers import docs_urls, static_urls
from apistar.backends import sqlalchemy_backend
from project.models import Base
from project.routes import user_routes


def welcome(name=None):
    if name is None:
        return {'message': 'Welcome to API Star!'}
    return {'message': 'Welcome to API Star, %s!' % name}


routes = [
    Route('/', 'GET', welcome),
    Include('/docs', docs_urls),
    Include('/static', static_urls),
    Include('/users', user_routes)
]

settings = {

    "DATABASE": {
        "URL": "mysql+pymysql://root:qw010203@localhost/apistar",
        "METADATA": Base.metadata
    }
}

app = App(
    routes=routes,
    settings=settings,
Beispiel #25
0

@annotate(renderers=[HTMLRenderer()])
def hello(username: str):
    return render_template('index.html', username=username)


def welcome(name=None):
    if name is None:
        return {'message': 'Welcome to API Star!'}
    return {'message': 'Welcome to API Star, %s!' % name}


routes = [
    Route('/', 'GET', hello),
    Include('/docs', docs_urls),
    Include('/static', static_urls),
    Include('/playgound', bs_api.playground.routes),
]

settings = {
    'TEMPLATES': {
        'ROOT_DIR': 'templates',       # Include the 'templates' direcotry.
        'PACKAGE_DIRS': ['apistar'],   # Include the buildin apistar templates.
    },
    'AUTHENTICATION': [BasicAuthentication()]
}

app = App(
    routes=routes,
    commands=bs_api.playground.commands,
Beispiel #26
0
from apistar import Include
from apistar.handlers import docs_urls, static_urls

from fortunes.urls import fortune_routes

routes = [
    Include('/fortunes', fortune_routes),
    Include('/docs', docs_urls),
    Include('/static', static_urls),
]
Beispiel #27
0
from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes

from project.views import attempts, welcome, add_teacher, delete_teacher, teacher_details, teachers_list

routes = [
    Route('/', 'GET', welcome),
    Route('/attempts/', 'GET', attempts),
    Route('/teachers/', 'GET', teachers_list),
    Route('/teachers/', 'POST', add_teacher),
    Route('/teacher/{teacher_id}/', 'GET', teacher_details),
    Route('/teacher/{teacher_id}/', 'DELETE', delete_teacher),
    Include('/docs', docs_routes),
    Include('/static', static_routes),
]
Beispiel #28
0
settings = {
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'db.sqlite3',
        }
    },
    'INSTALLED_APPS': [
        'core',
        'django.contrib.auth',
        'django.contrib.contenttypes',
    ],
    'AUTHENTICATION': [BasicDjangoAuthentication()],
}

if os.environ.get('TEST'):
    settings['DATABASES']['default']['NAME'] = 'test.db.sqlite3'

if os.environ.get('DEBUG'):
    routes.append(Include('/docs', docs_urls))

app = App(
    routes=routes,
    settings=settings,
    commands=django_orm.commands,
    components=django_orm.components,
)

if __name__ == '__main__':
    app.main()
Beispiel #29
0
from apistar.frameworks.wsgi import WSGIApp as App
from apistar.handlers import docs_urls, static_urls
from apistar.backends import sqlalchemy_backend
from db.models import Base
from api import routes


def welcome(name=None):
    if name is None:
        return {'message': 'Welcome to db Star!'}
    return {'message': 'Welcome to db Star, %s!' % name}


routes = routes + \
         [
             Include('/docs', docs_urls),
             Include('/static', static_urls)
         ]

# Configure database settings
settings = {
    "DATABASE": {
        "URL": "sqlite:///Test.db",
        "METADATA": Base.metadata
    }
}

app = App(routes=routes,
          settings=settings,
          commands=sqlalchemy_backend.commands,
          components=sqlalchemy_backend.components)
Beispiel #30
0
from apistar import App, Include
import custom_routes

routes = [Include("/api", name="api", routes=custom_routes.routes),]

app = App(routes)

if __name__ == "__main__":
    app.serve("127.0.0.1", 9090, debug=True)