# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pait', 'pait.api_doc', 'pait.app']

package_data = \
{'': ['*']}

install_requires = \
['PyYAML>=5.4.1,<6.0.0', 'pydantic>=1.7.3,<2.0.0']

setup_kwargs = {
    'name': 'pait',
    'version': '0.5.3',
    'description': 'Pait is a Python api tool. Pait enables your Python web framework to have type checking, parameter type conversion and interface document generation (power by inspect, pydantic)',
    'long_description': '# pait\nPait is an api tool that can be used in any python web framework (currently only `flask`, `starlette`, `sanic`, `tornado` are supported, other frameworks will be supported once Pait is stable).\n\nThe core functionality of Pait is to allow you to have FastAPI-like type checking and type conversion functionality (dependent on Pydantic and inspect) in any Python web framework, as well as documentation output\n\nPait\'s vision of documentation output is both code and documentation, with a simple configuration, you can get an md document or openapi (json, yaml)\n\n> Note:\n> \n> mypy check 100%\n> \n> test coverage 95%+ (exclude api_doc)\n> \n> python version >= 3.7 (support postponed annotations)\n \n[中文文档](https://github.com/so1n/pait/blob/master/README_ZH.md)\n# Installation\n```Bash\npip install pait\n```\n# Usage\nNote: The following code does not specify, all default to use the `starlette` framework. \nNote: There is no test case for the document output function, and the function is still being improved\n## 1.type checking and parameter type conversion\n### 1.1.Use in route handle\nA simple starlette route handler example:\n```Python\nimport uvicorn\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Route\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse\n\n\nasync def demo_post(request: Request) -> JSONResponse:\n    body_dict: dict = await request.json()\n    uid: int = body_dict.get(\'uid\')\n    user_name: str = body_dict.get(\'user_name\')\n    # The following code is only for demonstration, in general, we do some wrapping \n    if not uid:\n        raise ValueError(\'xxx\')\n    if type(uid) != int:\n        raise TypeError(\'xxxx\')\n    if 10 <= uid <= 1000:\n        raise ValueError(\'xxx\')\n\n    if not user_name:\n        raise ValueError(\'xxx\')\n    if type(user_name) != str:\n        raise TypeError(\'xxxx\')\n    if 2 <= len(user_name) <= 4:\n        raise ValueError(\'xxx\')\n    \n    return JSONResponse(\n        {\n            \'result\': {\n                \'uid\': body_dict[\'uid\'],\n                \'user_name\': body_dict[\'user_name\']\n            } \n        }\n    )\n\n\napp = Starlette(\n    routes=[\n        Route(\'/api\', demo_post, methods=[\'POST\']),\n    ]\n)\n\n\nuvicorn.run(app)\n```\nuse pait in starletter route handler:\n\n```Python\nimport uvicorn\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Route\nfrom starlette.responses import JSONResponse\n\nfrom pait.field import Body\nfrom pait.app.starlette import pait\nfrom pydantic import (\n    BaseModel,\n    conint,\n    constr,\n)\n\n\n# Create a Model based on Pydantic.BaseModel \nclass PydanticModel(BaseModel):\n    uid: conint(gt=10, lt=1000)  # Whether the auto-check type is int, and whether it is greater than or equal to 10 and less than or equal to 1000 \n    user_name: constr(min_length=2, max_length=4)  # Whether the auto-check type is str, and whether the length is greater than or equal to 2, less than or equal to 4\n\n\n\n# Decorating functions with the pait decorator\n@pait()\nasync def demo_post(\n    # pait through the Body () to know the current need to get the value of the body from the request, and assign the value to the model, \n    # and the structure of the model is the above PydanticModel, he will be based on our definition of the field automatically get the value and conversion and judgment\n    model: PydanticModel = Body.i()\n):\n    # Get the corresponding value to return\n    return JSONResponse({\'result\': model.dict()})\n\n\napp = Starlette(\n    routes=[\n        Route(\'/api\', demo_post, methods=[\'POST\']),\n    ]\n)\n\nuvicorn.run(app)\n```\nAs you can see, you just need to add a `pait` decorator to the routing function and change the parameters of `demo_post` to `model: PydanticModel = Body()`.\npait through `Body` to know the need to get the post request body data, and according to `conint(gt=10, lt=1000)` on the data conversion and restrictions, and assigned to `PydanticModel`, the user only need to use `Pydantic` as the call `model` can get the data.\n\nHere is just a simple demo, because we write the model can be reused, so you can save a lot of development time, the above parameters are only used to a way to write, the following will introduce pait support for the two ways to write and use.\n\n### 1.2.Parameter expression supported by pait\npait in order to facilitate the use of users, support a variety of writing methods (mainly the difference between TypeHints)\n- TypeHints  is PaitBaseModel, mainly used for parameters from multiple `Field`, and want to reuse model:\n  \n    PaitBaseModel can be used only for args parameters, it is the most flexible, PaitBaseModel has most of the features of Pydantic. BaseModel, which is not possible with Pydantic.:\n    ```Python\n    from pait.app.starlette import pait\n    from pait.field import Body, Header\n    from pait.model import PaitBaseModel\n\n\n    class TestModel(PaitBaseModel):\n        uid: int = Body.i()\n        content_type: str = Header.i(default=\'Content-Type\')\n\n\n    @pait()\n    async def test(model: PaitBaseModel):\n        return {\'result\': model.dict()}\n    ```\n- TypeHints is Pydantic.BaseModel, mainly used for parameters are derived from the same `Field`, and want to take the model: \n  \n    BaseModel can only be used with kwargs parameters, and the type hints of the parameters must be a class that inherits from `pydantic.BaseModel`, using the example:\n    ````Python\n    from pydantic import BaseModel\n    from pait.app.starlette import pait\n    from pait.field import Body\n    \n    \n    class TestModel(BaseModel):\n        uid: int\n        user_name: str\n    \n    \n    @pait()\n    async def test(model: BaseModel = Body.i()):\n        return {\'result\': model.dict()}\n    ````\n- When TypeHints is not one of the above two cases:\n  \n    can only be used for kwargs parameters and type hints are not the above two cases, if the value is rarely reused, or if you do not want to create a Model, you can consider this approach\n    ```Python\n    from pait.app.starlette import pait\n    from pait.field import Body\n\n\n    @pait()\n    async def test(uid: int = Body.i(), user_name: str = Body.i()):\n        return {\'result\': {\'uid\': uid, \'user_name\': user_name}}\n    ```\n### 1.3.Field\nField will help pait know how to get data from request.\nBefore introducing the function of Field, let’s take a look at the following example. `pait` will obtain the body data of the request according to Field.Body, and obtain the value with the parameter named key. Finally, the parameter is verified and assigned to the uid.\n```Python\nfrom pait.app.starlette import pait\nfrom pait.field import Body\n\n\n@pait()\nasync def demo_post(\n    # get uid from request body data\n    uid: int = Body.i()\n):\n    pass\n```\nThe following example will use a parameter called default.\nSince you can\'t use Content-Type to name the variables in Python, you can only use content_type to name them according to the naming convention of python, so there is no way to get the value directly from the header, so you can set the value of `alias` to Content-Type, and then Pait can get the value of Content-Type in the Header and assign it to the content_type variable.\nAnother example uses `raw_return` and sets it to True. At this time, `Pait` will not use the parameter name `header_dict` as the key to get the data, but directly assign the data of the entire header to the header_dict.\n\n```Python\nfrom pait.app.starlette import pait\nfrom pait.field import Body, Header\n\n\n@pait()\nasync def demo_post(\n    # get uid from request body data\n    uid: int = Body.i(),\n    # get Content-Type from header\n    content_type: str = Header.i(alias=\'Content-Type\'),\n    header_dict: str = Header.i(raw_return=True)\n\n):\n    pass\n```\nThe above only demonstrates the Body and Header of the field, but there are other fields as well::\n- Field.Body   Get the json data of the current request\n- Field.Cookie Get the cookie data of the current request\n- Field.File   Get the file data of the current request, depending on the web framework will return different file object types\n- Field.Form   Get the form data of the current request, if there are multiple duplicate keys, only the first one will be returned \n- Field.Header Get the header data of the current request\n- Field.Path   Get the path data of the current request (e.g. /api/{version}/test, you can get the version data)\n- Field.Query  Get the url parameters of the current request and the corresponding data, if there are multiple duplicate keys, only the first one will be returned \n- Field.MultiQuery Get the url parameter data of the current request, and return the list corresponding to the key\n- Field.MultiForm Get the form data of the current request, return the list corresponding to the key \n\nAll the fields above are inherited from `pydantic.fields.FieldInfo`, most of the parameters here are for api documentation, see for specific usage[pydantic doc](https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation)\n\n\nIn addition there is a field named Depends, he inherits from `object`, he provides the function of dependency injection, he only supports one parameter and the type of function, and the function\'s parameters are written in the same way as the routing function, the following is an example of the use of Depends, through Depends, you can reuse in each function to get the token function:\n\n```Python\nfrom pait.app.starlette import pait\nfrom pait.field import Body, Depends\n\n\ndef demo_depend(uid: str = Body.i(), password: str = Body.i()) -> str:\n    # fake db\n    token: str = db.get_token(uid, password)\n    return token\n\n\n@pait()\nasync def test_depend(token: str = Depends.i(demo_depend)):\n    return {\'token\': token}\n```\n\n### 1.4.requests object\nAfter using `Pait`, the proportion of the number of times the requests object is used will decrease, so `pait` does not return the requests object. If you need the requests object, you can fill in the parameters like `requests: Requests` (you need to use the TypeHints format) , You can get the requests object corresponding to the web framework\n```Python\nfrom starlette.requests import Request\n\n\n@params_verify()\nasync def demo_post(\n    request: Requests,\n    # get uid from request body data\n    uid: int = Body.i()  \n):\n    pass\n```\n\n### 1.5.Exception\n#### 1.5.1Exception Handling\nPait will leave the exception to the user to handle it. Under normal circumstances, pait will only throw the exception of `pydantic` and `PaitBaseException`. The user needs to catch the exception and handle it by himself, for example:\n```Python\nfrom starlette.applications import Starlette\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n\nfrom pait.exceptions import PaitBaseException\nfrom pydantic import ValidationError\n\nasync def api_exception(request: Request, exc: Exception) -> Response:\n    """\n    Handle exception code    \n    """\n\nAPP = Starlette()\nAPP.add_exception_handler(PaitBaseException, api_exception)\nAPP.add_exception_handler(ValidationError, api_exception)\n```\n#### 1.5.2Error Tip\nWhen you use pait incorrectly, pait will indicate in the exception the file path and line number of the function.\n```Bash\n  File "/home/so1n/github/pait/pait/func_param_handle.py", line 101, in set_value_to_kwargs_param\n    f\'File "{inspect.getfile(func_sig.func)}",\'\nPaitBaseException: \'File "/home/so1n/github/pait/example/starlette_example.py", line 28, in demo_post\\n kwargs param:content_type: <class \\\'str\\\'> = Header(key=None, default=None) not found value, try use Header(key={key name})\'\n```\nIf you need more information, can set the log level to debug to get more detailed information\n```Python\nDEBUG:root:\nasync def demo_post(\n    ...\n    content_type: <class \'str\'> = Header(key=None, default=None) <-- error\n    ...\n):\n    pass\n```\n## 2.Document Generation\n> Note: The function is being improved... \n\nIn addition to parameter verification and conversion, pait also provides the ability to output api documentation, which can be configured with simple parameters to output perfect documentation.\n\nNote: Currently only md, json, yaml type documents and openapi documents for json and yaml are supported for output.For the output of md, json, yaml, see \n[doc example](https://github.com/so1n/pait/blob/master/example/api_doc/example_doc)\n\n`pait` will automatically capture the request parameters and url, method and other information of the routing function.\nIn addition, it also supports labeling some relevant information. These labels will only be loaded into the memory when the Python program starts running, and will not affect the performance of the request, as in the following example:\n```Python\nfrom pait.app.starlette import pait\nfrom pait.model import PaitStatus\n\nfrom example.param_verify.model import UserSuccessRespModel, FailRespModel\n\n\n@pait(\n    author=("so1n",),\n    group="user",\n    status=PaitStatus.release,\n    tag=("user", "post"),\n    response_model_list=[UserSuccessRespModel, FailRespModel],\n)\ndef demo() -> None: \n  pass\n```\nParam:\n- author: List of authors who wrote the interface \n- group: The group to which the interface belongs \n- status: The status of the interface, currently only supports several states of `PaitStatus` \n  - default status:\n    - undefined: undefined \n  - in development:  \n    - design: Interface design \n    - dev: Under development and testing \n  - Development completed:  \n    - integration: 联合调试\n    - complete: development completed \n    - test: testing\n  - online:  \n    - release: online\n  - offline:  \n    - abnormal: The interface is abnormal and needs to be offline \n    - maintenance: In maintenance \n    - archive: archive\n    - abandoned: abandoned\n- tag: interface tag \n- response_model_list: return data, Need to inherit from `pait.model.PaitResponseModel`\n\n### 2.1.openapi\nCurrently pait supports most of the functions of openapi, a few unrealized features will be gradually improved through iterations (response-related more complex)\n\nThe openapi module of pait supports the following parameters (more parameters will be provided in the next version):\n- title: openapi\'s title \n- open_api_info: openapi\'s info param  \n- open_api_tag_list: related description of openapi tag \n- open_api_server_list: openapi server list\n- type_: The type of output, optionally json and yaml \n- filename: Output file name, or if empty, output to terminal\n\nThe following is the sample code output from the openapi documentation (modified by the 1.1 code). See [Example code](https://github.com/so1n/pait/tree/master/example/api_doc) and [doc example](https://github.com/so1n/pait/blob/master/example/api_doc/example_doc)\n```Python\nimport uvicorn\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Route\nfrom starlette.responses import JSONResponse\n\nfrom pait.field import Body\nfrom pait.app.starlette import pait\nfrom pydantic import (\n    BaseModel,\n    conint,\n    constr,\n)\n\n\n# Create a Model based on Pydantic.BaseModel \nclass PydanticModel(BaseModel):\n    uid: conint(gt=10, lt=1000)  # Whether the auto-check type is int, and whether it is greater than or equal to 10 and less than or equal to 1000 \n    user_name: constr(min_length=2, max_length=4)  # Whether the auto-check type is str, and whether the length is greater than or equal to 2, less than or equal to 4\n\n\n\n# Decorating functions with the pait decorator\n@pait()\nasync def demo_post(\n    # pait through the Body () to know the current need to get the value of the body from the request, and assign the value to the model, \n    # and the structure of the model is the above PydanticModel, he will be based on our definition of the field automatically get the value and conversion and judgment\n    model: PydanticModel = Body.i()\n):\n    # Get the corresponding value to return\n    return JSONResponse({\'result\': model.dict()})\n\n\napp = Starlette(\n    routes=[\n        Route(\'/api\', demo_post, methods=[\'POST\']),\n    ]\n)\n\nuvicorn.run(app)\n# --------------------\n\nfrom pait.app import load_app\nfrom pait.api_doc.open_api import PaitOpenApi\n\n\n# Extracting routing information to pait\'s data module\nload_app(app)\n# Generate openapi for routing based on data from the data module\nPaitOpenApi()\n```\n## 3.How to used in other web framework?\nIf the web framework is not supported, which you are using.\nCan be modified sync web framework according to [pait.app.flask](https://github.com/so1n/pait/blob/master/pait/app/flask.py)\n\nCan be modified async web framework according to [pait.app.starlette](https://github.com/so1n/pait/blob/master/pait/app/starlette.py)\n## 4.IDE Support\nWhile pydantic will work well with any IDE out of the box.\n- [PyCharm plugin](https://pydantic-docs.helpmanual.io/pycharm_plugin/)\n- [Mypy plugin](https://pydantic-docs.helpmanual.io/mypy_plugin/)\n\n## 5.Full example\nFor more complete examples, please refer to [example](https://github.com/so1n/pait/tree/master/example)',
    'author': 'So1n',
    'author_email': 'so1n897046026@gmail.com',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/so1n/pait',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.7,<4.0',
}


setup(**setup_kwargs)
