strawberry-resources


Namestrawberry-resources JSON
Version 0.10.0 PyPI version JSON
download
home_pagehttps://github.com/blb-ventures/strawberry-resources
SummaryIntrospection utilities to extract data from strawberry graphql
upload_time2023-10-06 18:43:16
maintainer
docs_urlNone
authorThiago Bellini Ribeiro
requires_python>=3.8,<4.0
licenseMIT
keywords strawberry django graphql resources forms
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # strawberry-resources

[![build status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fblb-ventures%2Fstrawberry-resources%2Fbadge%3Fref%3Dmain&style=flat)](https://actions-badge.atrox.dev/blb-ventures/strawberry-resources/goto?ref=main)
[![coverage](https://img.shields.io/codecov/c/github/blb-ventures/strawberry-resources.svg)](https://codecov.io/gh/blb-ventures/strawberry-resources)
[![downloads](https://pepy.tech/badge/strawberry-resources)](https://pepy.tech/project/strawberry-resources)
[![PyPI version](https://img.shields.io/pypi/v/strawberry-resources.svg)](https://pypi.org/project/strawberry-resources/)
![python version](https://img.shields.io/pypi/pyversions/strawberry-resources.svg)

Introspection utilities to extract data from the schema to use as helpers in the
client, like building an automatic form for input types.

## Installation

Just install the package with pip or your preferred package manager:

```shell
pip install strawberry-resources
```

## How to use

### Usage in a query

This lib provides a `Query` type that has two queries:

- `resources`: Returns a list of all available resources in the schema
- `resource`: Returns an specific resource given its name

You can use [merge_type](https://strawberry.rocks/docs/guides/tools#merge_types)
to merge it with your own `Query` type.

Then, given this example:

```python
@strawberry.enum
class Color(enum.Enum):
    YELLOW = strawberry.enum_value("yellow", description="Color Yellow")
    RED = "red"
    ORANGE = "orange"

@strawberry.type
class Fruit:
    name: str
    color: Annotated[Color, config(label="Color")]
    weight: Annotate[float, strawberry_resource.config(label="Weight")]

@strawberry.type
class Market:
    name: Annotate[str, strawberry_resource.config(label="Market Name")]
    fruits: Annotate[List[Fruit], strawberry_resource.config(label="Fruits")]

@strawberry.type
class Query:
    market: Market
```

You can query `resource(name: "Market")` which would return:

```json
{
  "resource": {
    "name": "Market"
    "fields": [
      {
        "__typename": "Field",
        "choices": null,
        "defaultValue": null,
        "filterable": false,
        "helpText": null,
        "kind": "STRING",
        "label": "Market Name",
        "multiple": false,
        "name": "name",
        "orderable": false,
        "resource": null,
        "validation": {
          "__typename": "BaseFieldValidation",
          "required": true
        }
      },
      {
        "__typename": "FieldObject",
        "label": "Fruits",
        "name": "fruits",
        "objKind": "OBJECT_LIST"
        "fields": [
          {
            "__typename": "Field",
            "choices": null,
            "defaultValue": null,
            "filterable": false,
            "helpText": null,
            "kind": "STRING",
            "label": "name",
            "multiple": false,
            "name": "name",
            "orderable": false,
            "resource": null,
            "validation": {
              "__typename": "BaseFieldValidation",
              "required": true
            }
          },
          {
            "__typename": "Field",
            "choices": [
              {
                "group": null,
                "label": "Color Yellow",
                "value": "YELLOW"
              },
              {
                "group": null,
                "label": "RED",
                "value": "RED"
              },
              {
                "group": null,
                "label": "ORANGE",
                "value": "ORANGE"
              }
            ],
            "defaultValue": null,
            "filterable": false,
            "helpText": null,
            "kind": "STRING",
            "label": "Color",
            "multiple": false,
            "name": "color",
            "orderable": false,
            "resource": null,
            "validation": {
              "__typename": "BaseFieldValidation",
              "required": true
            }
          },
          {
            "__typename": "Field",
            "choices": null,
            "defaultValue": null,
            "filterable": false,
            "helpText": null,
            "kind": "FLOAT",
            "label": "Weight",
            "multiple": false,
            "name": "weight",
            "orderable": false,
            "resource": null,
            "validation": {
              "__typename": "BaseFieldValidation",
              "required": true
            }
          }
        ],
      }
    ],
  }
}
```

### Exporting the resources

You can also use the resources statically by exporting them by using the command:

```shell
strawberry_resources export --app-dir <schema>
```

The export functions are also exposed in `strawberry_resources.exporter`. There are
2 functions there:

- `to_dict`: Will export the resources to a dictionary
- `to_json`: Will export the resources to a json string (used by the command above)

## Customizing the resource

Strawberry resource will introspect the schema to automatically fill some information
regarding the field. However, you can customize them by annotating your fields with
your own config.

In the example above we customized the `label` for most attributes, except for `Fruit.name`.
All possible config options are:

- `kind` (`FieldKind`): The kind of the field
- `multiple` (`bool`): If the field is multivalued (i.e. a List)
- `orderable` (`bool`): If the field is orderable`
- `filterable` (`bool`): If the field is filterable`
- `label` (`str | None`): An optional human friendly label for the field
- `help_text` (`str | FieldChoice`): An optional list with available choices for the field
- `default_value` (`JSON | None`): The default value for the field
- `validation` (`BaseFieldValidation`): Validation options for the field

Check the [types.py](strawberry_resources/types.py) module for more details.

## Integrations

### Django

If you are using Django, and by extend
[strawberry-graphql-django](https://github.com/strawberry-graphql/strawberry-graphql-django) or
[strawberry-django-plus](https://github.com/blb-ventures/strawberry-django-plus), the integration
will be automatically used to configure some options by introspecting your model.

The following will be retrieved from the fields in it, specially when typing it with
`strawberry.auto`:

- `kind`: The field kind will be automatically set based on the model field type. e.g. a `CharField`
  will generate a kind of `STRING`, a `DateTimeField` will generate a kind of `DATETIME` and so on.
- `orderable`: Will be automatically filled if the django type has an
  [ordering](https://strawberry-graphql.github.io/strawberry-graphql-django/references/ordering/)
  set on it, and the field itself is there
- `filterable`: Will be automatically filled if the django type has
  [filters](https://strawberry-graphql.github.io/strawberry-graphql-django/references/filters/)
  set on it, and the field itself is there
- `label`: Will be automatically filled using the field's `verbose_name` value
- `help_text`: Will be automatically filled using the field's `help_text` value
- `choices`: Will be automatically filled using the field's `choices` value
- `default_value`: Will be automatically filled using the field's `default` value

### Creating your own integration

You can create your own extension by creating an instance of
`strawberry_resources.integrations.StrawberryResourceIntegration`. It expects 4 attributes:

- `name`: The name of the integration
- `get_extra_mappings`: A callable that should return a dict mapping a type to a `FieldKind`
- `get_field_options`: A mapping that receives the type that contains the field, the field itself,
  the resolved type of the field and if it is a list of not. It is expect to return a dict with
  the options mentioned in the section above.
- `order`: An optional order to be used when running the integrations.

The integrations will run in the `order` they are defined. The official integrations in
this repo all have an order of `0`, so you can define yours to run before them by passing
a negative value, or after them by passing something greater than `0`.

NOTE: strawberry-resources is eager to have more integrations, so feel free to open a PR
for us sending yours! :)

## How options are resolved

All options will be merged recursively to generate the final resource options. That means that
options defined later will override the ones defined earlier. The order is the following:

- The options will be created with its `kind` retrieved from the kind mapping (considering the
  ones returned by the integrations as well), and its `label` will be set the same as its name
  by default.
- The integrations will run in the order they were defined, and each option returned will
  me merged recursively with the current options.
- At last, options will be retrieved by the field's annotations and will have the highest
  priority when merging with the rest.

## Licensing

The code in this project is licensed under MIT license. See [LICENSE](./LICENSE)
for more information.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/blb-ventures/strawberry-resources",
    "name": "strawberry-resources",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "strawberry,django,graphql,resources,forms",
    "author": "Thiago Bellini Ribeiro",
    "author_email": "thiago@bellini.dev",
    "download_url": "https://files.pythonhosted.org/packages/34/ac/c0dc4f8a06fe32c5e06c893a26b53e15f36ec245087b90c3acc517889f25/strawberry_resources-0.10.0.tar.gz",
    "platform": null,
    "description": "# strawberry-resources\n\n[![build status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fblb-ventures%2Fstrawberry-resources%2Fbadge%3Fref%3Dmain&style=flat)](https://actions-badge.atrox.dev/blb-ventures/strawberry-resources/goto?ref=main)\n[![coverage](https://img.shields.io/codecov/c/github/blb-ventures/strawberry-resources.svg)](https://codecov.io/gh/blb-ventures/strawberry-resources)\n[![downloads](https://pepy.tech/badge/strawberry-resources)](https://pepy.tech/project/strawberry-resources)\n[![PyPI version](https://img.shields.io/pypi/v/strawberry-resources.svg)](https://pypi.org/project/strawberry-resources/)\n![python version](https://img.shields.io/pypi/pyversions/strawberry-resources.svg)\n\nIntrospection utilities to extract data from the schema to use as helpers in the\nclient, like building an automatic form for input types.\n\n## Installation\n\nJust install the package with pip or your preferred package manager:\n\n```shell\npip install strawberry-resources\n```\n\n## How to use\n\n### Usage in a query\n\nThis lib provides a `Query` type that has two queries:\n\n- `resources`: Returns a list of all available resources in the schema\n- `resource`: Returns an specific resource given its name\n\nYou can use [merge_type](https://strawberry.rocks/docs/guides/tools#merge_types)\nto merge it with your own `Query` type.\n\nThen, given this example:\n\n```python\n@strawberry.enum\nclass Color(enum.Enum):\n    YELLOW = strawberry.enum_value(\"yellow\", description=\"Color Yellow\")\n    RED = \"red\"\n    ORANGE = \"orange\"\n\n@strawberry.type\nclass Fruit:\n    name: str\n    color: Annotated[Color, config(label=\"Color\")]\n    weight: Annotate[float, strawberry_resource.config(label=\"Weight\")]\n\n@strawberry.type\nclass Market:\n    name: Annotate[str, strawberry_resource.config(label=\"Market Name\")]\n    fruits: Annotate[List[Fruit], strawberry_resource.config(label=\"Fruits\")]\n\n@strawberry.type\nclass Query:\n    market: Market\n```\n\nYou can query `resource(name: \"Market\")` which would return:\n\n```json\n{\n  \"resource\": {\n    \"name\": \"Market\"\n    \"fields\": [\n      {\n        \"__typename\": \"Field\",\n        \"choices\": null,\n        \"defaultValue\": null,\n        \"filterable\": false,\n        \"helpText\": null,\n        \"kind\": \"STRING\",\n        \"label\": \"Market Name\",\n        \"multiple\": false,\n        \"name\": \"name\",\n        \"orderable\": false,\n        \"resource\": null,\n        \"validation\": {\n          \"__typename\": \"BaseFieldValidation\",\n          \"required\": true\n        }\n      },\n      {\n        \"__typename\": \"FieldObject\",\n        \"label\": \"Fruits\",\n        \"name\": \"fruits\",\n        \"objKind\": \"OBJECT_LIST\"\n        \"fields\": [\n          {\n            \"__typename\": \"Field\",\n            \"choices\": null,\n            \"defaultValue\": null,\n            \"filterable\": false,\n            \"helpText\": null,\n            \"kind\": \"STRING\",\n            \"label\": \"name\",\n            \"multiple\": false,\n            \"name\": \"name\",\n            \"orderable\": false,\n            \"resource\": null,\n            \"validation\": {\n              \"__typename\": \"BaseFieldValidation\",\n              \"required\": true\n            }\n          },\n          {\n            \"__typename\": \"Field\",\n            \"choices\": [\n              {\n                \"group\": null,\n                \"label\": \"Color Yellow\",\n                \"value\": \"YELLOW\"\n              },\n              {\n                \"group\": null,\n                \"label\": \"RED\",\n                \"value\": \"RED\"\n              },\n              {\n                \"group\": null,\n                \"label\": \"ORANGE\",\n                \"value\": \"ORANGE\"\n              }\n            ],\n            \"defaultValue\": null,\n            \"filterable\": false,\n            \"helpText\": null,\n            \"kind\": \"STRING\",\n            \"label\": \"Color\",\n            \"multiple\": false,\n            \"name\": \"color\",\n            \"orderable\": false,\n            \"resource\": null,\n            \"validation\": {\n              \"__typename\": \"BaseFieldValidation\",\n              \"required\": true\n            }\n          },\n          {\n            \"__typename\": \"Field\",\n            \"choices\": null,\n            \"defaultValue\": null,\n            \"filterable\": false,\n            \"helpText\": null,\n            \"kind\": \"FLOAT\",\n            \"label\": \"Weight\",\n            \"multiple\": false,\n            \"name\": \"weight\",\n            \"orderable\": false,\n            \"resource\": null,\n            \"validation\": {\n              \"__typename\": \"BaseFieldValidation\",\n              \"required\": true\n            }\n          }\n        ],\n      }\n    ],\n  }\n}\n```\n\n### Exporting the resources\n\nYou can also use the resources statically by exporting them by using the command:\n\n```shell\nstrawberry_resources export --app-dir <schema>\n```\n\nThe export functions are also exposed in `strawberry_resources.exporter`. There are\n2 functions there:\n\n- `to_dict`: Will export the resources to a dictionary\n- `to_json`: Will export the resources to a json string (used by the command above)\n\n## Customizing the resource\n\nStrawberry resource will introspect the schema to automatically fill some information\nregarding the field. However, you can customize them by annotating your fields with\nyour own config.\n\nIn the example above we customized the `label` for most attributes, except for `Fruit.name`.\nAll possible config options are:\n\n- `kind` (`FieldKind`): The kind of the field\n- `multiple` (`bool`): If the field is multivalued (i.e. a List)\n- `orderable` (`bool`): If the field is orderable`\n- `filterable` (`bool`): If the field is filterable`\n- `label` (`str | None`): An optional human friendly label for the field\n- `help_text` (`str | FieldChoice`): An optional list with available choices for the field\n- `default_value` (`JSON | None`): The default value for the field\n- `validation` (`BaseFieldValidation`): Validation options for the field\n\nCheck the [types.py](strawberry_resources/types.py) module for more details.\n\n## Integrations\n\n### Django\n\nIf you are using Django, and by extend\n[strawberry-graphql-django](https://github.com/strawberry-graphql/strawberry-graphql-django) or\n[strawberry-django-plus](https://github.com/blb-ventures/strawberry-django-plus), the integration\nwill be automatically used to configure some options by introspecting your model.\n\nThe following will be retrieved from the fields in it, specially when typing it with\n`strawberry.auto`:\n\n- `kind`: The field kind will be automatically set based on the model field type. e.g. a `CharField`\n  will generate a kind of `STRING`, a `DateTimeField` will generate a kind of `DATETIME` and so on.\n- `orderable`: Will be automatically filled if the django type has an\n  [ordering](https://strawberry-graphql.github.io/strawberry-graphql-django/references/ordering/)\n  set on it, and the field itself is there\n- `filterable`: Will be automatically filled if the django type has\n  [filters](https://strawberry-graphql.github.io/strawberry-graphql-django/references/filters/)\n  set on it, and the field itself is there\n- `label`: Will be automatically filled using the field's `verbose_name` value\n- `help_text`: Will be automatically filled using the field's `help_text` value\n- `choices`: Will be automatically filled using the field's `choices` value\n- `default_value`: Will be automatically filled using the field's `default` value\n\n### Creating your own integration\n\nYou can create your own extension by creating an instance of\n`strawberry_resources.integrations.StrawberryResourceIntegration`. It expects 4 attributes:\n\n- `name`: The name of the integration\n- `get_extra_mappings`: A callable that should return a dict mapping a type to a `FieldKind`\n- `get_field_options`: A mapping that receives the type that contains the field, the field itself,\n  the resolved type of the field and if it is a list of not. It is expect to return a dict with\n  the options mentioned in the section above.\n- `order`: An optional order to be used when running the integrations.\n\nThe integrations will run in the `order` they are defined. The official integrations in\nthis repo all have an order of `0`, so you can define yours to run before them by passing\na negative value, or after them by passing something greater than `0`.\n\nNOTE: strawberry-resources is eager to have more integrations, so feel free to open a PR\nfor us sending yours! :)\n\n## How options are resolved\n\nAll options will be merged recursively to generate the final resource options. That means that\noptions defined later will override the ones defined earlier. The order is the following:\n\n- The options will be created with its `kind` retrieved from the kind mapping (considering the\n  ones returned by the integrations as well), and its `label` will be set the same as its name\n  by default.\n- The integrations will run in the order they were defined, and each option returned will\n  me merged recursively with the current options.\n- At last, options will be retrieved by the field's annotations and will have the highest\n  priority when merging with the rest.\n\n## Licensing\n\nThe code in this project is licensed under MIT license. See [LICENSE](./LICENSE)\nfor more information.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Introspection utilities to extract data from strawberry graphql",
    "version": "0.10.0",
    "project_urls": {
        "Documentation": "https://github.com/blb-ventures/strawberry-resources",
        "Homepage": "https://github.com/blb-ventures/strawberry-resources",
        "Repository": "https://github.com/blb-ventures/strawberry-resources"
    },
    "split_keywords": [
        "strawberry",
        "django",
        "graphql",
        "resources",
        "forms"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "77769d5e39cb37184d206b3790f1ccbf0271eb23653225876fec319052d1f77a",
                "md5": "c3f2407e7954e576b4ec11f6d81839e9",
                "sha256": "116c576a1e3ae64a64f586fccea79c9bed8823842128c3b4feadca58f1c2b5fd"
            },
            "downloads": -1,
            "filename": "strawberry_resources-0.10.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c3f2407e7954e576b4ec11f6d81839e9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 18607,
            "upload_time": "2023-10-06T18:43:14",
            "upload_time_iso_8601": "2023-10-06T18:43:14.893771Z",
            "url": "https://files.pythonhosted.org/packages/77/76/9d5e39cb37184d206b3790f1ccbf0271eb23653225876fec319052d1f77a/strawberry_resources-0.10.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "34acc0dc4f8a06fe32c5e06c893a26b53e15f36ec245087b90c3acc517889f25",
                "md5": "8a9f33bdfe8755c4fbac9bcf9073546f",
                "sha256": "6267d5e1b68d2e667fafc3456d07d5ac85eb7376d457462d8076825270de749c"
            },
            "downloads": -1,
            "filename": "strawberry_resources-0.10.0.tar.gz",
            "has_sig": false,
            "md5_digest": "8a9f33bdfe8755c4fbac9bcf9073546f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 17304,
            "upload_time": "2023-10-06T18:43:16",
            "upload_time_iso_8601": "2023-10-06T18:43:16.612378Z",
            "url": "https://files.pythonhosted.org/packages/34/ac/c0dc4f8a06fe32c5e06c893a26b53e15f36ec245087b90c3acc517889f25/strawberry_resources-0.10.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-06 18:43:16",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "blb-ventures",
    "github_project": "strawberry-resources",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "strawberry-resources"
}
        
Elapsed time: 0.12783s