django-restit


Namedjango-restit JSON
Version 4.2.102 PyPI version JSON
download
home_pageNone
SummaryA Rest Framework for DJANGO
upload_time2024-06-13 17:43:13
maintainerNone
docs_urlNone
authorIan Starnes
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # RESTIT.. a REST framework for DJANGO

### Quick Steps

1. Install framework

2. Add "restit" to DJANGO apps.

3. Add "middleware"

    'rest.middleware.SessionMiddleware',
        'rest.middleware.GlobalRequestMiddleware',
        'rest.middleware.CorsMiddleware',   
   
4. add url(r'^rpc/', include('rest.urls')) to your urlpatterns in urls.py

## Quick Overview

This framework makes it easy to build a rest framework to use with any web or applicaiton development.

You can take any model and turn them into a REST Model by inheriting from RestModel.

```python
class ExampleTODO(models.Model, RestModel):
    your standard django fields
  ...
```



Next in your DJANGO app create a "rpc.py" file.

```python
# decorator that defines your routes, note the app_name is assumed
@rd.url('todo')
@rd.url('todo/<int:pk>')
@login_required
def on_rest_todo(request, pk=None):
    return ExampleTODO.on_rest_request(request, pk)
```

This will give you a full rest interface into your Django model.



### But wait there's more...

This framework is pretty powerful and allow you to define how you want to return your model objects, and how deep!

```python
class ExampleTODO(models.Model, RestModel):
    class RestMeta:
        GRAPHS = {
            "default": {
        "exclude":["priority"],
                "graphs":{
                    "user":"default"
                }
            },
            "list": {
        "fields":["id", "name", "priority"]
            }
        }
    user = models.ForeignKey(User, related_name="+")
  name = models.CharField(max_length=80)
  description = models.TextField(max_length=80)
  priority = models.IntegerField(default=0)
```

Above you can we we can define "graphs" that let us control what is returned.

So if we go to http://localhost:8000/rpc/rest_example/todo it will default to the "list" graph and return something that looks like...

```json
{
    "status": true,
    "size": 25,
    "count": 2,
    "data": [
        {
            "id": 1,
            "name": "test 1",
            "priority": 1,
      "user": 21
        },
        {
            "id": 2,
            "name": "test 2",
            "priority": 1,
      "user": 21
        },
    ]
}
```



So if we go to http://localhost:8000/rpc/rest_example/todo?graph=default

```json
{
    "status": true,
    "size": 25,
    "count": 2,
    "data": [
        {
            "id": 1,
            "name": "test 1",
            "description": "this is test 1",
      "user": {
        "id": 21,
        "username": "jsmith",
        "display_name": "TEST USER 5",
        "avatar": "http://localhost:8000/media/ax1fg.png"
      }
        },
        {
            "id": 2,
            "name": "test 2",
            "description": "this is test 2",
      "user": {
        "id": 21,
        "username": "jsmith",
        "display_name": "TEST USER 5",
        "avatar": "http://localhost:8000/media/ax1fg.png"
      }
        },
    ]
}
```





## More details...

## RestModel

The RestModel Class is a helper class that helps existing models adapt to the REST framework.  It is not required but highly recommended.

### API helpers

Key methods you can override

```
    def on_rest_get(self, request):
        # override the get method
        return self.restGet(request, graph)

    def on_rest_post(self, request):
        # override the post method
        return self.restGet(request, graph) 
    
    def on_rest_pre_save(self, request):
        # called before instance saved via rest, no return
        pass
        
    def on_rest_created(self, request):
        # called after new instance created via rest, no return
        pass

    def on_rest_saved(self, request):
        # called after old instance saved via rest, no return
        pass

    def on_rest_delete(self, request):
        can_delete = getattr(self.RestMeta, "CAN_DELETE", False)
        if not can_delete:
            return self.restStatus(request, False, error="deletion not allowed via rest for this model.")
        self.delete()
        return GRAPH_HELPERS.restStatus(request, True)

    @classmethod
    def onRestCanSave(cls, request):
        # override to validate permissions or anything if this can create or save this instance
        return True
        
    @classmethod
    def on_rest_list_filter(cls, request, qset):
        # override on do any pre filters, returns new qset
        # qset = qset.filter(id__gt=50)
        return qset
        
    @classmethod
    def on_rest_list(cls, request, qset=None):
        # normally you would override on_rest_list_filter, but you could override this
        return cls.restList(request, qset)
    
    @classmethod
    def on_rest_create(cls, request, pk=None):
        obj = cls.createFromRequest(request)
        return obj.restGet(request)
```



#### Creating and Saving

`createFromRequest(request, **kwargs)` - this allows you to pass a request object (normally a post) and create a new model from that request.  You can also pass in any override fields after the request.

```
    MyModel.createFromRequest(request, owner=request.user)
```

`saveFromRequest(request, **kwargs)` - this allows you to pass a request object (normally a post) and save data to the model from that request.  You can also pass in any override fields after the request.

```
    mode_instance.saveFromRequest(request, modified_by=request.user)
```

#### Other Helper Methods

`getFromRequest(cls, model_name)` - @classmethod - attempts to get the model instance from a request, check for the classname and classname+ "_id" in the REQUEST params.


`restGetModel(app_name, model_name)` - @staticmethod - grab Model class by app and model name.

`restGetGenericModel(self, fieldname)` - grab Model class by app and model name.

`restGetGenericRelation(self, fieldname)` - grab Model class by app and model name.

## Returning JSON Graph

Graphs can easily be built automatically from your models by setting the appropriate RestMeta properties.

`getGraph(name)` - @classmethod - Specify the name of the graph you want to return.

### RestMeta

This is a Property class you add to your models to define your graphs.

By default a graph will return just the fields with no recurse into of Foreign models.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "django-restit",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Ian Starnes",
    "author_email": "ians@311labs.com",
    "download_url": "https://files.pythonhosted.org/packages/7d/a7/62b64168f19d5d9fe7e74b26fb0af25d0321a451b0c15c7e0e9173e907bc/django_restit-4.2.102.tar.gz",
    "platform": null,
    "description": "# RESTIT.. a REST framework for DJANGO\n\n### Quick Steps\n\n1. Install framework\n\n2. Add \"restit\" to DJANGO apps.\n\n3. Add \"middleware\"\n\n    'rest.middleware.SessionMiddleware',\n        'rest.middleware.GlobalRequestMiddleware',\n        'rest.middleware.CorsMiddleware',   \n   \n4. add url(r'^rpc/', include('rest.urls')) to your urlpatterns in urls.py\n\n## Quick Overview\n\nThis framework makes it easy to build a rest framework to use with any web or applicaiton development.\n\nYou can take any model and turn them into a REST Model by inheriting from RestModel.\n\n```python\nclass ExampleTODO(models.Model, RestModel):\n    your standard django fields\n  ...\n```\n\n\n\nNext in your DJANGO app create a \"rpc.py\" file.\n\n```python\n# decorator that defines your routes, note the app_name is assumed\n@rd.url('todo')\n@rd.url('todo/<int:pk>')\n@login_required\ndef on_rest_todo(request, pk=None):\n    return ExampleTODO.on_rest_request(request, pk)\n```\n\nThis will give you a full rest interface into your Django model.\n\n\n\n### But wait there's more...\n\nThis framework is pretty powerful and allow you to define how you want to return your model objects, and how deep!\n\n```python\nclass ExampleTODO(models.Model, RestModel):\n    class RestMeta:\n        GRAPHS = {\n            \"default\": {\n        \"exclude\":[\"priority\"],\n                \"graphs\":{\n                    \"user\":\"default\"\n                }\n            },\n            \"list\": {\n        \"fields\":[\"id\", \"name\", \"priority\"]\n            }\n        }\n    user = models.ForeignKey(User, related_name=\"+\")\n  name = models.CharField(max_length=80)\n  description = models.TextField(max_length=80)\n  priority = models.IntegerField(default=0)\n```\n\nAbove you can we we can define \"graphs\" that let us control what is returned.\n\nSo if we go to http://localhost:8000/rpc/rest_example/todo it will default to the \"list\" graph and return something that looks like...\n\n```json\n{\n    \"status\": true,\n    \"size\": 25,\n    \"count\": 2,\n    \"data\": [\n        {\n            \"id\": 1,\n            \"name\": \"test 1\",\n            \"priority\": 1,\n      \"user\": 21\n        },\n        {\n            \"id\": 2,\n            \"name\": \"test 2\",\n            \"priority\": 1,\n      \"user\": 21\n        },\n    ]\n}\n```\n\n\n\nSo if we go to http://localhost:8000/rpc/rest_example/todo?graph=default\n\n```json\n{\n    \"status\": true,\n    \"size\": 25,\n    \"count\": 2,\n    \"data\": [\n        {\n            \"id\": 1,\n            \"name\": \"test 1\",\n            \"description\": \"this is test 1\",\n      \"user\": {\n        \"id\": 21,\n        \"username\": \"jsmith\",\n        \"display_name\": \"TEST USER 5\",\n        \"avatar\": \"http://localhost:8000/media/ax1fg.png\"\n      }\n        },\n        {\n            \"id\": 2,\n            \"name\": \"test 2\",\n            \"description\": \"this is test 2\",\n      \"user\": {\n        \"id\": 21,\n        \"username\": \"jsmith\",\n        \"display_name\": \"TEST USER 5\",\n        \"avatar\": \"http://localhost:8000/media/ax1fg.png\"\n      }\n        },\n    ]\n}\n```\n\n\n\n\n\n## More details...\n\n## RestModel\n\nThe RestModel Class is a helper class that helps existing models adapt to the REST framework.  It is not required but highly recommended.\n\n### API helpers\n\nKey methods you can override\n\n```\n    def on_rest_get(self, request):\n        # override the get method\n        return self.restGet(request, graph)\n\n    def on_rest_post(self, request):\n        # override the post method\n        return self.restGet(request, graph) \n    \n    def on_rest_pre_save(self, request):\n        # called before instance saved via rest, no return\n        pass\n        \n    def on_rest_created(self, request):\n        # called after new instance created via rest, no return\n        pass\n\n    def on_rest_saved(self, request):\n        # called after old instance saved via rest, no return\n        pass\n\n    def on_rest_delete(self, request):\n        can_delete = getattr(self.RestMeta, \"CAN_DELETE\", False)\n        if not can_delete:\n            return self.restStatus(request, False, error=\"deletion not allowed via rest for this model.\")\n        self.delete()\n        return GRAPH_HELPERS.restStatus(request, True)\n\n    @classmethod\n    def onRestCanSave(cls, request):\n        # override to validate permissions or anything if this can create or save this instance\n        return True\n        \n    @classmethod\n    def on_rest_list_filter(cls, request, qset):\n        # override on do any pre filters, returns new qset\n        # qset = qset.filter(id__gt=50)\n        return qset\n        \n    @classmethod\n    def on_rest_list(cls, request, qset=None):\n        # normally you would override on_rest_list_filter, but you could override this\n        return cls.restList(request, qset)\n    \n    @classmethod\n    def on_rest_create(cls, request, pk=None):\n        obj = cls.createFromRequest(request)\n        return obj.restGet(request)\n```\n\n\n\n#### Creating and Saving\n\n`createFromRequest(request, **kwargs)` - this allows you to pass a request object (normally a post) and create a new model from that request.  You can also pass in any override fields after the request.\n\n```\n    MyModel.createFromRequest(request, owner=request.user)\n```\n\n`saveFromRequest(request, **kwargs)` - this allows you to pass a request object (normally a post) and save data to the model from that request.  You can also pass in any override fields after the request.\n\n```\n    mode_instance.saveFromRequest(request, modified_by=request.user)\n```\n\n#### Other Helper Methods\n\n`getFromRequest(cls, model_name)` - @classmethod - attempts to get the model instance from a request, check for the classname and classname+ \"_id\" in the REQUEST params.\n\n\n`restGetModel(app_name, model_name)` - @staticmethod - grab Model class by app and model name.\n\n`restGetGenericModel(self, fieldname)` - grab Model class by app and model name.\n\n`restGetGenericRelation(self, fieldname)` - grab Model class by app and model name.\n\n## Returning JSON Graph\n\nGraphs can easily be built automatically from your models by setting the appropriate RestMeta properties.\n\n`getGraph(name)` - @classmethod - Specify the name of the graph you want to return.\n\n### RestMeta\n\nThis is a Property class you add to your models to define your graphs.\n\nBy default a graph will return just the fields with no recurse into of Foreign models.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Rest Framework for DJANGO",
    "version": "4.2.102",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ee1b758f16c78bda863302dc00d59acce1dd52e0d341ba3d9369a70b87f1bb3c",
                "md5": "7384b9842a5266c15303bfbe3c2f1a84",
                "sha256": "38d6844582b3b25bc1aa435d0df875835fbbda8f4c3cf9131982790a5d852d63"
            },
            "downloads": -1,
            "filename": "django_restit-4.2.102-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7384b9842a5266c15303bfbe3c2f1a84",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 996373,
            "upload_time": "2024-06-13T17:43:10",
            "upload_time_iso_8601": "2024-06-13T17:43:10.639158Z",
            "url": "https://files.pythonhosted.org/packages/ee/1b/758f16c78bda863302dc00d59acce1dd52e0d341ba3d9369a70b87f1bb3c/django_restit-4.2.102-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7da762b64168f19d5d9fe7e74b26fb0af25d0321a451b0c15c7e0e9173e907bc",
                "md5": "8fae92f00239f072807cabd005ecae3a",
                "sha256": "853e726130dde526fe52906c0c4679daf09ae872af924db752d0e1841d55dd3e"
            },
            "downloads": -1,
            "filename": "django_restit-4.2.102.tar.gz",
            "has_sig": false,
            "md5_digest": "8fae92f00239f072807cabd005ecae3a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 816742,
            "upload_time": "2024-06-13T17:43:13",
            "upload_time_iso_8601": "2024-06-13T17:43:13.443543Z",
            "url": "https://files.pythonhosted.org/packages/7d/a7/62b64168f19d5d9fe7e74b26fb0af25d0321a451b0c15c7e0e9173e907bc/django_restit-4.2.102.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-13 17:43:13",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "django-restit"
}
        
Elapsed time: 0.54161s