Exemplo n.º 1
0
def router():
    def hello_world(request):
        return "hello world"

    def sayhi(request, name: str):
        return f"hi, {name}"

    router = Router(
        Routes(
            HttpRoute("/sayhi/{name}", sayhi, "sayhi", "get"),
            SubRoutes(
                "/hello",
                [
                    HttpRoute(
                        "/world", hello_world, "hello-world", method="get"),
                    SocketRoute("/socket_world", lambda websocket: None),
                ],
            ),
        ))

    @router.http("/about", name=None, method="get")
    def about(request, name: str = None):
        return str(request.url)

    router.http("/about/{name}", about, method="get")

    @router.http("/http_view")
    class HTTP(HTTPView):
        pass

    @router.websocket("/socket_view", name="socket")
    class Socket(SocketView):
        pass

    return router
Exemplo n.º 2
0
def test_routes_operator():
    from indexpy import HttpRoute, Routes

    routes = Routes()
    routes << Routes(
        HttpRoute("/login", test_routes_operator),
        HttpRoute("/register", test_routes_operator),
    )
    routes == Routes(
        HttpRoute("/login", test_routes_operator),
        HttpRoute("/register", test_routes_operator),
    )

    (
        routes
        << Routes(
            HttpRoute("/login", test_routes_operator),
            HttpRoute("/register", test_routes_operator),
        )
    ) == (
        Routes(
            HttpRoute("/login", test_routes_operator),
            HttpRoute("/register", test_routes_operator),
        )
        + Routes(
            HttpRoute("/login", test_routes_operator),
            HttpRoute("/register", test_routes_operator),
        )
    )
Exemplo n.º 3
0
    def routes(self) -> Routes:
        async def redirect():
            return request.url.replace(path=request.url.path + "/")

        async def template():
            return HTMLResponse(self.html_template)

        async def json_docs():
            openapi = self.create_docs(request)
            return JSONResponse(
                openapi,
                headers={
                    "hash": md5(json.dumps(openapi).encode()).hexdigest()
                })

        async def heartbeat():
            async def g():
                openapi = self.create_docs(request)
                yield {
                    "id": md5(json.dumps(openapi).encode()).hexdigest(),
                    "data": json.dumps(openapi),
                }
                while not request.app.should_exit:
                    await asyncio.sleep(1)

            return g()

        return Routes(
            HttpRoute("", redirect),
            HttpRoute("/", template),
            HttpRoute("/json", json_docs),
            HttpRoute("/heartbeat", heartbeat),
        )
Exemplo n.º 4
0
    def routes(self) -> Routes:
        async def template() -> HttpResponse:
            return HTMLResponse(self.html_template)

        async def docs() -> HttpResponse:
            openapi = self.create_docs(request)
            return JSONResponse(openapi)

        return Routes(HttpRoute("/", template), HttpRoute("/docs", docs))
Exemplo n.º 5
0
    def routes(self) -> List[HttpRoute]:
        async def template(request: Request) -> Response:
            return HTMLResponse(self.html_template)

        async def docs(request: Request) -> Response:
            openapi = self.create_docs(request)
            return JSONResponse(openapi)

        return [
            HttpRoute("/", template, method="get"),
            HttpRoute("/docs", docs, method="get"),
        ]
Exemplo n.º 6
0
def test_prefix():
    from indexpy.routing import HttpRoute, Routes

    assert [
        route.path for route in ("/auth" // Routes(
            HttpRoute("/login", test_prefix),
            HttpRoute("/register", test_prefix),
        ))
    ] == [
        route.path for route in (Routes(
            HttpRoute("/auth/login", test_prefix),
            HttpRoute("/auth/register", test_prefix),
        ))
    ]
Exemplo n.º 7
0
def app():
    app = Index()

    @app.router.http("/hello", method="get")
    async def hello(request):
        return "hello world"

    class Name(BaseModel):
        name: str

    class T:
        @app.router.http("/path/{name}", method="get")
        async def path(request, name: str = Path(...)):
            return f"path {name}"

    def http_middleware(endpoint):
        @wraps(endpoint)
        async def wrapper(request):
            response = convert_response(await endpoint(request))
            response.body += b"; http middleware"
            return response

        return wrapper

    def only_empty(request):
        return b""

    def get_path(request, path: Name = Exclusive("path")):
        return request.url.path

    def holiday(request):
        return "play game with girlfriend"

    app.router.extend(
        Routes(
            HttpRoute("/only/empty", only_empty, method="get"),
            SubRoutes(
                "/the-third-path",
                Routes(
                    HttpRoute("/path/{name}", get_path, method="get"),
                    Routes(
                        HttpRoute("/holiday", holiday, method="get"),
                        http_middlewares=[http_middleware],
                    ),
                ),
            ),
            http_middlewares=[http_middleware],
        ))

    return app
Exemplo n.º 8
0
    def routes(self) -> List[HttpRoute]:
        async def template(request: Request) -> Response:
            return HTMLResponse(self.html_template)

        async def docs(request: Request) -> Response:
            openapi = self.create_docs(request)
            media_type = request.query_params.get("type", self.media_type)

            if media_type == "json":
                return JSONResponse(openapi)
            return YAMLResponse(openapi)

        return [
            HttpRoute("/", template, method="get"),
            HttpRoute("/docs", docs, method="get"),
        ]
Exemplo n.º 9
0
def test_lshift():
    from indexpy import Index
    from indexpy.routing import HttpRoute, SocketRoute

    app = Index()

    async def hello():
        return "hello world"

    async def hello_ws():
        ...

    (app.router << HttpRoute("/hello", hello, name="hello") << SocketRoute(
        "/hello", hello_ws, name="hello_ws"))

    assert app.router.search("http", "/hello")[0] == {}
    assert app.router.search("websocket", "/hello")[0] == {}

    assert app.router.search("http", "/hello") != (app.router.search(
        "websocket", "/hello"))
Exemplo n.º 10
0
def test_openapi_page():
    app = Index()
    openapi = OpenAPI("Title", "description", "1.0")
    app.router.extend(SubRoutes("/openapi", openapi.routes))

    @app.router.http("/hello", method="get")
    @describe_response(200, content=List[str])
    async def hello(request):
        """
        hello
        """
        pass

    class Username(BaseModel):
        name: str

    @app.router.http("/path/{name}", method="get")
    async def path(request, name: str = Path(...)):
        pass

    @app.router.http("/http-view")
    class HTTPClass(HTTPView):
        @describe_response(
            HTTPStatus.OK,
            content={"text/html": {
                "schema": {
                    "type": "string"
                },
            }},
        )
        async def get(self):
            """
            ...

            ......
            """

        @describe_response(HTTPStatus.CREATED, content=Username)
        async def post(self):
            """
            ...

            ......
            """

        @describe_response(HTTPStatus.NO_CONTENT)
        async def delete(self):
            """
            ...

            ......
            """

    def just_middleware(endpoint):
        describe_extra_docs(
            endpoint,
            {
                "parameters": [{
                    "name": "Authorization",
                    "in": "header",
                    "description": "JWT Token",
                    "required": True,
                    "schema": {
                        "type": "string"
                    },
                }]
            },
        )
        return endpoint

    middleware_routes = SubRoutes(
        "/middleware",
        [
            HttpRoute("/path/{name}", path, "middleware-path", method="get"),
            HttpRoute("/http-view", HTTPClass, "middleware-HTTPClass"),
        ],
        http_middlewares=[just_middleware],
    )

    app.router.extend(middleware_routes)

    client = TestClient(app)
    assert client.get("/openapi/docs").status_code == 200
    openapi_docs_text = client.get("/openapi/docs").text
    assert (
        openapi_docs_text ==
        '{"openapi":"3.0.0","info":{"title":"Title","description":"description","version":"1.0"},"paths":{"/hello":{"get":{"summary":"hello","responses":{"200":{"description":"Request fulfilled, document follows","content":{"application/json":{"schema":{"title":"ParsingModel[List[str]]","type":"array","items":{"type":"string"}}}}}}}},"/http-view":{"get":{"summary":"...","description":"......","responses":{"200":{"description":"Request fulfilled, document follows","content":{"text/html":{"schema":{"type":"string"}}}}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]},"post":{"summary":"...","description":"......","responses":{"201":{"description":"Document created, URL follows","content":{"application/json":{"schema":{"title":"Username","type":"object","properties":{"name":{"title":"Name","type":"string"}},"required":["name"]}}}}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]},"delete":{"summary":"...","description":"......","responses":{"204":{"description":"Request fulfilled, nothing follows"}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]}},"/path/{name}":{"get":{"parameters":[{"in":"path","name":"name","description":"","required":true,"schema":{"title":"Name","type":"string"}},{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}],"responses":{"422":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"loc":{"title":"Loc","description":"error field","type":"array","items":{"type":"string"}},"type":{"title":"Type","description":"error type","type":"string"},"msg":{"title":"Msg","description":"error message","type":"string"}},"required":["loc","type","msg"]}}}},"description":"Failed to verify request parameters"}}}},"/middleware/path/{name}":{"get":{"parameters":[{"in":"path","name":"name","description":"","required":true,"schema":{"title":"Name","type":"string"}},{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}],"responses":{"422":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"loc":{"title":"Loc","description":"error field","type":"array","items":{"type":"string"}},"type":{"title":"Type","description":"error type","type":"string"},"msg":{"title":"Msg","description":"error message","type":"string"}},"required":["loc","type","msg"]}}}},"description":"Failed to verify request parameters"}}}},"/middleware/http-view":{"get":{"summary":"...","description":"......","responses":{"200":{"description":"Request fulfilled, document follows","content":{"text/html":{"schema":{"type":"string"}}}}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]},"post":{"summary":"...","description":"......","responses":{"201":{"description":"Document created, URL follows","content":{"application/json":{"schema":{"title":"Username","type":"object","properties":{"name":{"title":"Name","type":"string"}},"required":["name"]}}}}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]},"delete":{"summary":"...","description":"......","responses":{"204":{"description":"Request fulfilled, nothing follows"}},"parameters":[{"name":"Authorization","in":"header","description":"JWT Token","required":true,"schema":{"type":"string"}}]}}},"tags":[],"servers":[{"url":"http://testserver","description":"Current server"}],"definitions":{}}'
    )
Exemplo n.º 11
0
def test_openapi_page():
    app = Index()
    app.router.extend(
        SubRoutes("/openapi",
                  OpenAPI("Title", "description", "1.0").routes))

    @app.router.http("/hello", method="get")
    async def hello(request):
        """
        hello

        接口描述
        """
        pass

    class Path(BaseModel):
        name: str

    @app.router.http("/path/{name}", method="get")
    async def path(request, path: Path):
        pass

    @app.router.http("/http-view")
    class HTTPClass(HTTPView):
        @describe_response(
            HTTPStatus.OK,
            content={"text/html": {
                "schema": {
                    "type": "string"
                },
            }},
        )
        async def get(self):
            """
            ...

            ......
            """

        @describe_response(HTTPStatus.CREATED, content=Path)
        async def post(self):
            """
            ...

            ......
            """

        @describe_response(HTTPStatus.NO_CONTENT)
        async def delete(self):
            """
            ...

            ......
            """

    def just_middleware(endpoint):
        describe_extra_docs(
            endpoint,
            {
                "parameters": [{
                    "name": "Authorization",
                    "in": "header",
                    "description": "JWT Token",
                    "required": True,
                    "schema": {
                        "type": "string"
                    },
                }]
            },
        )
        return endpoint

    middleware_routes = SubRoutes(
        "/middleware",
        [
            HttpRoute("/path/{name}", path, "middleware-path", method="get"),
            HttpRoute("/http-view", HTTPClass, "middleware-HTTPClass"),
        ],
        http_middlewares=[just_middleware],
    )

    app.router.extend(middleware_routes)

    client = TestClient(app)
    assert client.get("/openapi/docs").status_code == 200
    openapi_docs_text = client.get("/openapi/docs").text

    _ = """definitions: {}
info:
  description: description
  title: Title
  version: '1.0'
openapi: 3.0.0
paths:
  /hello:
    get:
      description: 接口描述
      summary: hello
  /http-view:
    delete:
      description: '......'
      parameters: &id001
      - description: JWT Token
        in: header
        name: Authorization
        required: true
        schema:
          type: string
      responses:
        204:
          description: Request fulfilled, nothing follows
      summary: '...'
    get:
      description: '......'
      parameters: *id001
      responses:
        200:
          content: &id002
            text/html:
              schema:
                type: string
          description: Request fulfilled, document follows
      summary: '...'
    post:
      description: '......'
      parameters: *id001
      responses:
        201:
          content:
            application/json:
              schema:
                properties:
                  name:
                    title: Name
                    type: string
                required:
                - name
                title: Path
                type: object
          description: Document created, URL follows
      summary: '...'
  /middleware/http-view:
    delete:
      description: '......'
      parameters: *id001
      responses:
        204:
          description: Request fulfilled, nothing follows
      summary: '...'
    get:
      description: '......'
      parameters: *id001
      responses:
        200:
          content: *id002
          description: Request fulfilled, document follows
      summary: '...'
    post:
      description: '......'
      parameters: *id001
      responses:
        201:
          content:
            application/json:
              schema:
                properties:
                  name:
                    title: Name
                    type: string
                required:
                - name
                title: Path
                type: object
          description: Document created, URL follows
      summary: '...'
  /middleware/path/{name}:
    get:
      parameters:
      - description: ''
        in: path
        name: name
        required: true
        schema:
          title: Name
          type: string
      - &id003
        description: JWT Token
        in: header
        name: Authorization
        required: true
        schema:
          type: string
  /path/{name}:
    get:
      parameters:
      - description: ''
        in: path
        name: name
        required: true
        schema:
          title: Name
          type: string
      - *id003
servers:
- description: Current server
  url: http://testserver
tags: []
"""
    assert openapi_docs_text == _
Exemplo n.º 12
0
    """
    async def message_gen():
        for i in range(5):
            await asyncio.sleep(1)
            yield {"id": i, "data": "hello"}

    return message_gen()


@required_method("GET")
async def sources(filepath: str = Path()):
    """
    Return source files
    """
    realpath = FilePath(".") / filepath.lstrip("./")
    try:
        return FileResponse(realpath)
    except FileNotFoundError:
        raise HTTPException(404)


app = Index(
    debug=True,
    routes=[
        HttpRoute("/", homepage),
        HttpRoute("/exc", exc),
        HttpRoute("/message", message),
        HttpRoute("/sources/{filepath:path}", sources),
    ],
)