Giter VIP home page Giter VIP logo

drf-generators's Introduction

DRF Generators

Writing APIs can be boring and repetitive work. Don't write another CRUDdy view in Django Rest Framework. With DRF Generators, one simple command will generate all of your Views, Serializers, and even Urls for your Django Rest Framework application!

For a full step-by-step tutorial, check out my blog post!

This is not intended to give you a production quality API. It was intended to jumpstart your development and save you from writing the same code over and over for each model.


Supported Python versions Latest Version License Travis CI Django 1.11, 2.2, 3.0 DRF 3.11



Installation

Install with pip:

$ pip install drf-generators

or Clone the repo and install manually:

$ git clone https://github.com/brobin/drf-generators.git
$ cd drf-generators
$ python setup.py install

To use DRF Generators, add it your INSTALLED_APPS.

INSTALLED_APPS = (
    ...
    'rest_framework',
    'drf_generators',
    ...
)

Note: In order to use the APIView classes, you must have the rest framework DEFAULT_PAGINATION_CLASS and PAGE_SIZE set.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 15
}

Usage

To use the generators, run the following command, where app is the application to generate an API for.

$ python manage.py generate {app} {options}
Option Action
--serializers Generate only Serializers for your app.
--views Generate only Views for your app.
--urls Generate only urls for your app.
--force Overwrite existing files without the warning prompt.
-f, --format Format to use when generating views and urls. Valid options: viewset, apiview, function, modelviewset. Default: viewset.
-d, --depth Serialization depth for related models. Default: 0

Example: Generate everything for the app api with function style views, overwriting existing files, with a serialization depth of 2.

$ python manage.py generate api --format function --force --depth=2

Serializers

Drf Generators will create serializers.py for your application. It currently uses rest framework's ModelSerializer for serialization of the models defined in models.py.

class ModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User

Views

DRF Generators will create views.py for your application. It can generate ViewSet, APIView and function based views. Set the --format option when running the generator to pick the preferred style

ViewSet

python manage.py generate api --format viewset

class ModelViewSet(ViewSet):

    def list(self, request):
        ...
    def create(self, request):
        ...
    def retrieve(self, request, pk=None):
        ...
    def update(self, request, pk=None):
        ...
    def destroy(self, request, pk=None):
        ...

APIView

python manage.py generate api --format apiview

class ModelAPIView(APIView):

    def get(self, request, id, format=None):
        ...
    def put(self, request, id, format=None):
        ...
    def delete(self, request, id, format=None):
        ...

class ModelAPIListView(APIView):

    def get(self, request, format=None):
        ...
    def post(self, request, format=None):
        ...

Function

python manage.py generate api --format function

@api_view(['GET', 'POST'])
def model_list(request):
    if request.method == 'GET':
        ...
    elif request.method == 'POST':
        ...

@api_view(['GET', 'PUT', 'DELETE'])
def model_detail(request, pk):
    if request.method == 'GET':
        ...
    elif request.method == 'PUT':
        ...
    elif request.method == 'DELETE':
        ...

ModelViewSet

python manage.py generate api --format modelviewset

class MyModelViewSet(ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Urls

Finally, DRF Generator will create you a default urls.py to match the View format you are using.

ViewSet & ModeViewSet Routes

router = SimpleRouter()

router.register(r'model', views.ModelViewSet, 'Model')

urlpatterns = router.urls

APIView urls

url(r'^model/([0-9]+)$', views.ModelAPIView.as_view()),
url(r'^model', views.ModelAPIListView.as_view()),

Function urls

urlpatterns = [

    url(r'^model/(?P<pk>[0-9]+)$', views.model_detail),
    url(r'^model/$', views.model_list),

]

urlpatterns = format_suffix_patterns(urlpatterns)

Tests

A full application built with drf-generators can be found in the tests directory. Instructions on running the tests can be found in the test project's README.

License

MIT License. See LICENSE.

drf-generators's People

Contributors

adambain avatar aljp avatar brobin avatar edwardbetts avatar giovan avatar guest007 avatar jeverling avatar jnegro avatar silegon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

drf-generators's Issues

Fix up command line arguments

Having just --apiview is kinda bad, especially when I add new subclasses of BaseGenerator to support function based views, etc.

Perhaps have a --format option that is required. i.e.

python manage.py generate --format apiview app
python manage.py generate --format viewset app
python manage.py generate --format function app

Add ability to exclude fields from generator

This may be just an edge case for myself, but I have added django-simple-history to my project to track changes made to instances of my models, and use that in the admin. I want to exclude the history field from each model, and when I ran the generate management command, the generator created serializer and modelviewset classes from the relationship for historical records, along with corresponding URLs. Now I know I can delete these and clean it up on my own, but could there be an option to define an excluded model from generation? Thank you

Add support for generating an API from a different app

I have a well-established Django app with its models.py and other bits in an app called schema. I started developing an API in a different app called api but didn't get far. Then I discovered this amazing project! Is there a way to make it write out the generated API files in a different app from the source app? Thanks

File missing from pip install

Hi there.

The file <path-to-python-site-packages>/drf_generators/management/__init__.py is missing when installing drf-generators from pip, as described at http://brobin.me/blog/2015/4/13/how-to-quickly-write-an-api-in-django

This produces the following error:

$ python manage.py generate api --format modelviewset
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named management.commands.generate

It appears easily fixed by:

touch <path-to-python-site-packages>/drf_generators/management/__init__.py

After this, running python manage.py generate api --format modelviewset seems to run without any problems.

django 1.9

Hi
I'm just start project and use django 1.9(b1). May be it's better to use

elif django.VERSION[1] >= 8:

instead of

elif django.VERSION[1] == 8:

?
Or something like that...

Django 2.0 Support

Is drf-generators supports Django 2.0 ? There no any information in README regarding Django version support.

Option for printing to stdout instead of wrting to file

Instead of writing / overwriting a file, I would like an option to print to stdout.

It would let the user decide to pipe the output to another file, or copy just parts of the output, without worrying about overwriting existing files.

Use drf-generators on an existing project?

Hello, Pls have a look at the Turkle project at hltcoe/turkle#32. We're trying to add an api to it, but concerned that the generators will blow away existing files or otherwise radically change the underlying code design. Your input would be very much appreciated. Thanks in advance.

Support Function based views

Suport function based views as described in the drf documentation.

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer

@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = SnippetSerializer(snippet, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Add ViewSet Views

Many people use ViewSet instead of APIView. Add a command argument for the type of views to generate.

Add generation of test data using the faker library

Perhaps a good feature would be to include generation of test data. Nobody likes creating test data and there are good libraries out there for it.

django-faker does this but it appears that it is no longer maintained and has no support for Python 3. Can be implemented using the faker library.

Example command: python manage.py fake api 15, would add 15 of each object in the api app.

Add Permission classes to Views

Add default authentication to views.

Example for viewset, modelviewset, apiview

from rest_framework import permissions

class SomeViewSet(SomeViewType):
    permission_classes = (permissions.SomePermission,)

Example for function based

@permission_classes(permissions.SomePermission,)
def some_veiw():
    ...

Add tests with nested relations

The Post and Category models in the test api are related, but we never test the relations in the api. Test with different depths and compare outputs.

Generator only producing API View

Using Django 2.2.2 and Python 3.7.3 the generator command will only create APIView views.py regardless of the command given. I tested this with an existing, a brand new, and another developer's venv, to the same result.

It does write a new file, but only APIView.

final touch

that appeared after all what i have done

Using the URLconf defined in example_api.urls, Django tried these URL patterns, in this order:

^admin/
^api/

The empty path didn't match any of these

Add Authentication classes to Views

Add default authentication to views.

Example for viewset, modelviewset, apiview

from rest_framework import authentication, permissions

class SomeViewSet(SomeViewType):
    authentication_classes = (authentication.TokenAuthentication,)

Example for function based

@authentication_classes(...)
def some_veiw():
    ...

'AppCommand' has no attribute 'option_list'

I'm attempting to run the generator for app named "manager"

python manage.py generate manager --format modelviewset

I'm getting the following error

  File "/python/api/lib/python3.5/site-packages/drf_generators/management/commands/generate.py", line 8, in <module>
    class Command(AppCommand):
  File "python/api/lib/python3.5/site-packages/drf_generators/management/commands/generate.py", line 33, in Command
    option_list = AppCommand.option_list + base_options
AttributeError: type object 'AppCommand' has no attribute 'option_list'

[help wanted] Is is possible to set view restriction in models?

Hello there - I just found this AMAZING repo and it works wonders of initializing a pretty comprehensive start for a fully covering api!

I have quite a few models that are read-only, and I was wondering if it is possible to define this somewhere, such the irrelevant properties in views and serializers are not set?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.