Created
November 24, 2024 05:57
-
-
Save rg3915/8a1dd6fd7fcc589d1d5a2c49e228702d to your computer and use it in GitHub Desktop.
Cria arquivos básicos para API em Django Ninja
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Este script gera uma estrutura básica de API Django com os seguintes arquivos: | |
1. urls.py: Arquivo principal de configuração de URLs do Django, que inclui: | |
- Rota para a aplicação core | |
- Rota para a API v1 | |
- Rota para o painel admin | |
- Configuração de arquivos estáticos | |
2. api.py: Arquivo de configuração da API usando Django Ninja, que: | |
- Inicializa a API | |
- Configura o roteador principal | |
3. core/api.py: Arquivo com as rotas da API core, contendo: | |
- Definição do roteador com tag 'Core' | |
- Exemplo de endpoint para listar usuários | |
Como usar: | |
python create_api.py -f /path/to/your/project | |
O script criará automaticamente todos os diretórios necessários e os arquivos | |
com a estrutura básica para começar a desenvolver uma API usando Django e Django Ninja. | |
""" | |
import argparse | |
from pathlib import Path | |
from typing import Optional | |
class APIGenerator: | |
def __init__(self, base_path: str): | |
self.base_path = Path(base_path) | |
self.urls_content = '''from django.conf import settings | |
from django.conf.urls.static import static | |
from django.contrib import admin | |
from django.urls import include, path | |
from .api import api | |
urlpatterns = ( | |
[ | |
path('', include('backend.core.urls', namespace='core')), | |
path('api/v1/', api.urls), | |
path('admin/', admin.site.urls), | |
] | |
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | |
) | |
''' | |
self.api_content = '''from ninja import NinjaAPI | |
api = NinjaAPI() | |
api.add_router('', 'backend.core.api.router') | |
''' | |
self.core_schema_content = '''from ninja import Field, ModelSchema | |
class UserSchema(ModelSchema): | |
full_name: str = Field(None, alias='get_full_name') | |
username: str = Field(None) | |
class Meta: | |
model = User | |
fields = ('first_name', 'last_name', 'email') | |
''' | |
self.core_api_content = '''from ninja import Router, Schema | |
from .schemas import UserSchema | |
router = Router(tags=['Core']) | |
@router.get('users', response=list[UserSchema]) | |
def list_users(request): | |
return User.objects.all() | |
''' | |
def create_directory(self, path: Optional[Path] = None) -> None: | |
"""Create directory if it doesn't exist.""" | |
dir_path = path or self.base_path | |
if not dir_path.exists(): | |
dir_path.mkdir(parents=True) | |
print(f"Created directory: {dir_path}") | |
def write_file(self, filename: str, content: str, subdirectory: Optional[str] = None) -> None: | |
"""Write content to a file in the specified directory.""" | |
if subdirectory: | |
file_path = self.base_path / subdirectory / filename | |
self.create_directory(self.base_path / subdirectory) | |
else: | |
file_path = self.base_path / filename | |
with open(file_path, 'w') as f: | |
f.write(content) | |
print(f"Created {file_path}") | |
def generate(self) -> None: | |
"""Generate all required files and directories.""" | |
try: | |
# Create base directory | |
self.create_directory() | |
# Create files | |
self.write_file('urls.py', self.urls_content) | |
self.write_file('api.py', self.api_content) | |
self.write_file('api.py', self.core_api_content, 'core') | |
self.write_file('schemas.py', self.core_schema_content, 'core') | |
print("API structure created successfully!") | |
except Exception as e: | |
print(f"Error creating API structure: {str(e)}") | |
raise | |
def main(): | |
# Parse command line arguments | |
parser = argparse.ArgumentParser(description='Create Django API structure') | |
parser.add_argument('-f', '--folder', required=True, help='Path where the API structure will be created') | |
args = parser.parse_args() | |
# Create and run generator | |
generator = APIGenerator(args.folder) | |
generator.generate() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment