Skip to content

Instantly share code, notes, and snippets.

@Donut3228
Created February 9, 2020 20:58
Show Gist options
  • Save Donut3228/8b3653abb4e898c054f0a514a22af8cf to your computer and use it in GitHub Desktop.
Save Donut3228/8b3653abb4e898c054f0a514a22af8cf to your computer and use it in GitHub Desktop.
import os
app_dir = os.path.join(os.path.abspath(os.path.curdir), 'marina/api')
classes = []
def get_models_names():
with open(f'{app_dir}/models.py', 'r') as f:
models = f.read()
arr = models.split('class ')
arr.pop(0)
for each in arr:
x = each.split("(", 1)[0]
if 'Base' not in x:
print(x)
classes.append(x)
return ', '.join(classes)
def make_serializers():
with open(f'{app_dir}/serializers.py', 'w') as f:
serializer = '''class {}Serializer(HyperlinkedModelSerializer):
class Meta:
model = {}
fields = '__all__'
'''
kod = f'''from rest_framework.serializers import HyperlinkedModelSerializer
from api.models import {models_import}
'''
for each in classes:
tmp = serializer
kod += tmp.format(each, each, each)
f.write(kod)
def make_viewsets():
with open(f'{app_dir}/views.py', 'w') as f:
viewset = '''class {}ViewSet(ModelViewSet):
serializer_class = {}Serializer
queryset = {}.objects.all()
'''
kod = f'''from rest_framework.viewsets import ModelViewSet
from api.models import {models_import}
from api.serializers import {'Serializer, '.join(models_import.split(', ')) + 'Serializer'}
'''
for each in classes:
tmp = viewset
kod += tmp.format(each, each, each)
f.write(kod)
def make_routers():
with open(f'{app_dir}/urls.py', 'w') as f:
viewset = '''
router.register('{}s', {}ViewSet)
'''
kod = f'''from django.urls import path, include
from rest_framework import routers
from api.views import {'ViewSet, '.join(models_import.split(', ')) + 'ViewSet'}
router = routers.DefaultRouter()
'''
for each in classes:
tmp = viewset
kod += tmp.format(str.lower(each), each)
kod += '''
urlpatterns = [
path('api/', include(router.urls))
]
'''
f.write(kod)
models_import = get_models_names()
make_serializers()
make_viewsets()
make_routers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment