flask-restx-marshmallow


Nameflask-restx-marshmallow JSON
Version 0.1.1 PyPI version JSON
download
home_pagehttps://github.com/1746104160/flask-restx-marshmallow
SummaryA successful practice combining flask_restx with marshmallow
upload_time2023-07-11 05:38:43
maintainer
docs_urlNone
author1746104160
requires_python>=3.10,<4.0
licenseMIT
keywords flask flask_restx sqlalchemy marshmallow
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <!--
 * @Description: README for flask_restx_marshmallow
 * @version: 0.1.1
 * @Author: 1746104160
 * @Date: 2023-06-02 13:05:58
 * @LastEditors: 1746104160 shaojiahong2001@outlook.com
 * @LastEditTime: 2023-06-16 18:04:55
 * @FilePath: /flask_restx_marshmallow/README.md
-->
# Flask-RESTX-marshmallow

Flask-RESTX-marshmallow is an extension for [Flask](https://flask.palletsprojects.com/en/latest/) and [Flask-RESTX](https://flask-restx.readthedocs.io/en/latest/), which is a successful practice combining flask_restx with marshmallow.

## Compatibility

Flask-RESTX-marshmallow requires Python 3.10+.

## Installation

Install the extension with pip:

```bash
pip install flask-restx-marshmallow
```

or with poetry:

```bash
poetry add flask-restx-marshmallow
```

## Quickstart

With Flask-RESTX-marshmallow, you only import the api instance to route and document your endpoints.

```python
import uuid

import sqlalchemy as sa
from flask import Flask
from marshmallow import fields, post_load

from flask_restx_marshmallow import (
    Api,
    JSONParameters,
    QueryParameters,
    Resource,
    SQLAlchemy,
    StandardSchema,
)

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
api = Api(
    app,
    version="0.1.1",
    title="example API",
    description="api interface for example app",
)
db = SQLAlchemy(app)
ns = api.namespace("example", description="example operations")


class Task(db.Model):
    id = db.Column(db.String(32), primary_key=True)
    task = db.Column(db.String(80))

    def __init__(self, id, task):
        self.id = id.hex
        self.task = task

    def __repr__(self):
        return "<Task %r>" % self.task


class QueryTaskParameters(QueryParameters):
    id = fields.UUID(metadata={"description": "The task unique identifier"})

    @post_load
    def process(self, data, **_kwargs):
        if "id" in data:
            return {"data": Task.query.filter_by(id=data["id"].hex).first()}
        return {"code": 1, "message": "id is required", "success": False}


class CreateTaskParameters(JSONParameters):
    task = fields.String(
        required=True, metadata={"description": "The task details"}
    )

    @post_load
    def process(self, data, **_kwargs):
        try:
            task = Task(id=uuid.uuid4(), task=data["task"])
            db.session.add(task)
        except sa.exc.IntegrityError as e:
            db.session.rollback()
            return {"code": 1, "message": str(e), "success": False}
        else:
            db.session.commit()
            return {
                "message": f"create task success with id {uuid.UUID(task.id)}"
            }


class TaskSchema(StandardSchema):
    data = fields.Nested(
        {
            "id": fields.UUID(
                metadata={"description": "The task unique identifier"},
            ),
            "task": fields.String(metadata={"description": "The task details"}),
        }
    )


@ns.route("/")
class TaskManage(Resource):
    """task manage"""

    @ns.parameters(params=QueryTaskParameters(), location="query")
    @ns.response(
        code=200,
        description="query task by id",
        model=TaskSchema(message="query task success"),
    )
    def get(self, task):
        """query task by id"""
        return task

    @ns.parameters(params=CreateTaskParameters(), location="body")
    @ns.response(
        code=200,
        description="create a new task",
        model=None,
        name="CreateSchema",
        message="create successfully",
    )
    def post(self, res):
        """create a new task"""
        return res


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    api.register_doc(app)
    app.run(debug=True)
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/1746104160/flask-restx-marshmallow",
    "name": "flask-restx-marshmallow",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "",
    "keywords": "flask,flask_restx,sqlalchemy,marshmallow",
    "author": "1746104160",
    "author_email": "shaojiahong2001@outlook.com",
    "download_url": "https://files.pythonhosted.org/packages/89/77/b59314d223ffdc3959bc76e18cb54d590b66feda4d638519f2bfad7fa0af/flask_restx_marshmallow-0.1.1.tar.gz",
    "platform": null,
    "description": "<!--\n * @Description: README for flask_restx_marshmallow\n * @version: 0.1.1\n * @Author: 1746104160\n * @Date: 2023-06-02 13:05:58\n * @LastEditors: 1746104160 shaojiahong2001@outlook.com\n * @LastEditTime: 2023-06-16 18:04:55\n * @FilePath: /flask_restx_marshmallow/README.md\n-->\n# Flask-RESTX-marshmallow\n\nFlask-RESTX-marshmallow is an extension for [Flask](https://flask.palletsprojects.com/en/latest/) and [Flask-RESTX](https://flask-restx.readthedocs.io/en/latest/), which is a successful practice combining flask_restx with marshmallow.\n\n## Compatibility\n\nFlask-RESTX-marshmallow requires Python 3.10+.\n\n## Installation\n\nInstall the extension with pip:\n\n```bash\npip install flask-restx-marshmallow\n```\n\nor with poetry:\n\n```bash\npoetry add flask-restx-marshmallow\n```\n\n## Quickstart\n\nWith Flask-RESTX-marshmallow, you only import the api instance to route and document your endpoints.\n\n```python\nimport uuid\n\nimport sqlalchemy as sa\nfrom flask import Flask\nfrom marshmallow import fields, post_load\n\nfrom flask_restx_marshmallow import (\n    Api,\n    JSONParameters,\n    QueryParameters,\n    Resource,\n    SQLAlchemy,\n    StandardSchema,\n)\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///test.db\"\napi = Api(\n    app,\n    version=\"0.1.1\",\n    title=\"example API\",\n    description=\"api interface for example app\",\n)\ndb = SQLAlchemy(app)\nns = api.namespace(\"example\", description=\"example operations\")\n\n\nclass Task(db.Model):\n    id = db.Column(db.String(32), primary_key=True)\n    task = db.Column(db.String(80))\n\n    def __init__(self, id, task):\n        self.id = id.hex\n        self.task = task\n\n    def __repr__(self):\n        return \"<Task %r>\" % self.task\n\n\nclass QueryTaskParameters(QueryParameters):\n    id = fields.UUID(metadata={\"description\": \"The task unique identifier\"})\n\n    @post_load\n    def process(self, data, **_kwargs):\n        if \"id\" in data:\n            return {\"data\": Task.query.filter_by(id=data[\"id\"].hex).first()}\n        return {\"code\": 1, \"message\": \"id is required\", \"success\": False}\n\n\nclass CreateTaskParameters(JSONParameters):\n    task = fields.String(\n        required=True, metadata={\"description\": \"The task details\"}\n    )\n\n    @post_load\n    def process(self, data, **_kwargs):\n        try:\n            task = Task(id=uuid.uuid4(), task=data[\"task\"])\n            db.session.add(task)\n        except sa.exc.IntegrityError as e:\n            db.session.rollback()\n            return {\"code\": 1, \"message\": str(e), \"success\": False}\n        else:\n            db.session.commit()\n            return {\n                \"message\": f\"create task success with id {uuid.UUID(task.id)}\"\n            }\n\n\nclass TaskSchema(StandardSchema):\n    data = fields.Nested(\n        {\n            \"id\": fields.UUID(\n                metadata={\"description\": \"The task unique identifier\"},\n            ),\n            \"task\": fields.String(metadata={\"description\": \"The task details\"}),\n        }\n    )\n\n\n@ns.route(\"/\")\nclass TaskManage(Resource):\n    \"\"\"task manage\"\"\"\n\n    @ns.parameters(params=QueryTaskParameters(), location=\"query\")\n    @ns.response(\n        code=200,\n        description=\"query task by id\",\n        model=TaskSchema(message=\"query task success\"),\n    )\n    def get(self, task):\n        \"\"\"query task by id\"\"\"\n        return task\n\n    @ns.parameters(params=CreateTaskParameters(), location=\"body\")\n    @ns.response(\n        code=200,\n        description=\"create a new task\",\n        model=None,\n        name=\"CreateSchema\",\n        message=\"create successfully\",\n    )\n    def post(self, res):\n        \"\"\"create a new task\"\"\"\n        return res\n\n\nif __name__ == \"__main__\":\n    with app.app_context():\n        db.create_all()\n    api.register_doc(app)\n    app.run(debug=True)\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A successful practice combining flask_restx with marshmallow",
    "version": "0.1.1",
    "project_urls": {
        "Homepage": "https://github.com/1746104160/flask-restx-marshmallow",
        "Repository": "https://github.com/1746104160/flask-restx-marshmallow"
    },
    "split_keywords": [
        "flask",
        "flask_restx",
        "sqlalchemy",
        "marshmallow"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "de6202769f66d0ab9bb17e2b730779f157df101344ac7dd5baccad7510bf0d68",
                "md5": "4fcf6e8afd7783383de7df243107cb26",
                "sha256": "caddb1c2144123c2c28dde40d5b2c63f85c6b0a834c68cd3ee75a81ffdffcdf3"
            },
            "downloads": -1,
            "filename": "flask_restx_marshmallow-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4fcf6e8afd7783383de7df243107cb26",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 472993,
            "upload_time": "2023-07-11T05:38:39",
            "upload_time_iso_8601": "2023-07-11T05:38:39.769270Z",
            "url": "https://files.pythonhosted.org/packages/de/62/02769f66d0ab9bb17e2b730779f157df101344ac7dd5baccad7510bf0d68/flask_restx_marshmallow-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8977b59314d223ffdc3959bc76e18cb54d590b66feda4d638519f2bfad7fa0af",
                "md5": "fd3e5e3f5e9983aecea4b91323786891",
                "sha256": "ca5d4ab946254371cfdb492784d00aa2e822435645017814a69e3ffc0dd209ef"
            },
            "downloads": -1,
            "filename": "flask_restx_marshmallow-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "fd3e5e3f5e9983aecea4b91323786891",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 475640,
            "upload_time": "2023-07-11T05:38:43",
            "upload_time_iso_8601": "2023-07-11T05:38:43.690537Z",
            "url": "https://files.pythonhosted.org/packages/89/77/b59314d223ffdc3959bc76e18cb54d590b66feda4d638519f2bfad7fa0af/flask_restx_marshmallow-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-11 05:38:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "1746104160",
    "github_project": "flask-restx-marshmallow",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "flask-restx-marshmallow"
}
        
Elapsed time: 2.16903s