Skip to main content

Express.js-like framework built on Django

Project description

shanks

Shanks Django CLI

๐Ÿš€ CLI tool untuk generate Django project dengan Express.js syntax dan Prisma-like ORM.

PyPI version License: MIT

๐Ÿ“ฆ Installation

pip install shanks-django

โœจ Features

  • Express.js-like syntax - Familiar routing
  • Prisma-like ORM - Modern database queries
  • Auto-caching enabled - GET requests cached by default (10x faster!)
  • Smart cache invalidation - Auto-clear on POST/PUT/DELETE
  • Route grouping - Organize routes like Gin (Go)
  • Auto-type detection - No need to specify <int:id>
  • Swagger built-in - Auto-generated API docs
  • CLI generators - Generate CRUD & Auth instantly
  • SORM CLI - Prisma-like database management

๐Ÿš€ Quick Start

# Buat project baru
shanks new myproject
cd myproject

# Generate CRUD endpoints
shanks create posts --crud

# Generate auth endpoints  
shanks create auth --simple

# Run migrations
sorm make
sorm db migrate

# Or use push (make + migrate in one command)
sorm db push

# Start server
shanks run

Visit:

That's it! Your API now has:

  • โœ… Auto-caching enabled (10x faster GET requests)
  • โœ… Smart cache invalidation on writes
  • โœ… Swagger documentation
  • โœ… CRUD endpoints with pagination

๐Ÿ› ๏ธ CLI Commands

Development Server

# Start server (default: 127.0.0.1:8000)
shanks run

# Custom port
shanks run 3000

# Custom host dan port
shanks run 0.0.0.0:8000

Auto-reload seperti nodemon, langsung detect perubahan file.

Project Management

# Buat project baru dengan struktur Go-like
shanks new myproject

Struktur yang di-generate:

myproject/
โ”œโ”€โ”€ manage.py
โ”œโ”€โ”€ myproject/
โ”‚   โ”œโ”€โ”€ settings.py
โ”‚   โ”œโ”€โ”€ urls.py
โ”‚   โ””โ”€โ”€ wsgi.py
โ””โ”€โ”€ app/
    โ”œโ”€โ”€ models/
    โ”œโ”€โ”€ routes/
    โ”œโ”€โ”€ middleware/
    โ””โ”€โ”€ dto/

Generate CRUD Endpoints

# Generate full CRUD dengan model
shanks create posts --crud

Ini akan create:

  • app/models/posts.py - Model dengan SORM
  • app/routes/posts.py - Complete CRUD routes

Yang di-generate:

  • โœ… List dengan pagination (page, limit)
  • โœ… Get by ID (findById)
  • โœ… Create
  • โœ… Update
  • โœ… Delete
  • โœ… Auth checks
  • โœ… Error handling

Contoh hasil generate:

# app/routes/posts.py
from shanks import App, Response
from app.models import Post

app = App()

@app.get('api/posts')
def list_posts(req):
    page = int(req.query.get('page', 1))
    limit = int(req.query.get('limit', 10))
    posts = Post.find_many()
    return {'posts': [...], 'page': page, 'limit': limit}

@app.get('api/posts/<post_id>')
def get_post(req, post_id):
    post = Post.find_unique(id=post_id)
    if not post:
        return Response().status_code(404).json({'error': 'Not found'})
    return {'post': {...}}

@app.post('api/posts')
def create_post(req):
    post = Post.create(**req.body)
    return Response().status_code(201).json({'id': post.id})

@app.put('api/posts/<post_id>')
def update_post(req, post_id):
    post = Post.find_unique(id=post_id)
    post.update_self(**req.body)
    return {'updated': True}

@app.delete('api/posts/<post_id>')
def delete_post(req, post_id):
    post = Post.find_unique(id=post_id)
    post.delete_self()
    return {'deleted': True}

Generate Auth Endpoints

# Simple auth: /login, /register, /me
shanks create auth --simple

# Complete auth: + email verification
shanks create auth --complete

Yang di-generate untuk --simple:

  • POST /api/auth/register - Register user baru
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user

Yang di-generate untuk --complete:

  • Semua dari --simple
  • POST /api/auth/verify - Email verification
  • POST /api/auth/resend - Resend verification email

Generate Django Structure

# Generate full Django project structure
shanks generate django

Command ini akan:

  • โœ… Generate folder django_output/ dengan struktur Django standard
  • โœ… Convert Shanks routes ke Django urls.py
  • โœ… Copy semua models, migrations, dan app code
  • โœ… Siap untuk deployment dengan Gunicorn/uWSGI
  • โœ… Berguna untuk comparison atau deployment ke platform yang butuh Django standard

Output structure:

django_output/
โ”œโ”€โ”€ myproject/
โ”‚   โ”œโ”€โ”€ settings.py
โ”‚   โ”œโ”€โ”€ urls.py          # Generated from Shanks routes
โ”‚   โ””โ”€โ”€ wsgi.py
โ”œโ”€โ”€ entity/              # Your models
โ”œโ”€โ”€ internal/            # Your app code
โ”œโ”€โ”€ manage.py
โ””โ”€โ”€ README.md            # Deployment guide

Kenapa perlu ini?

  • ๐Ÿš€ Easy deployment - Banyak platform hosting familiar dengan Django standard
  • ๐Ÿ“Š Comparison - Compare Shanks vs Django structure
  • ๐Ÿ”„ Migration - Kalau mau migrate dari Shanks ke pure Django
  • ๐Ÿ“ฆ Compatibility - Beberapa tools butuh Django standard structure

Database Management (SORM)

# Create migrations
sorm make

# Apply migrations
sorm db migrate

# Create + apply migrations (one command)
sorm db push

# Reset database (flush all data)
sorm db reset

# Open database shell
sorm db shell

# Open admin panel (like Prisma Studio)
sorm studio

Command sorm mirip dengan Prisma CLI:

  • sorm make = prisma migrate dev --create-only
  • sorm db migrate = prisma migrate deploy
  • sorm db push = prisma db push
  • sorm studio = prisma studio (tapi pake Django Admin)

Auto-Type Detection di Routes

Sekarang gak perlu specify type di URL parameters! Shanks auto-detect:

# Auto-detect as int (karena nama berakhiran '_id')
@app.get('api/posts/<post_id>')
def get_post(req, post_id):
    return {'id': post_id}

# Auto-detect as string
@app.get('api/users/<username>')
def get_user(req, username):
    return {'username': username}

# Masih bisa explicit type kalau perlu
@app.get('api/posts/<slug:slug>')  # force as slug
def get_user(req, username):
    return {'username': username}

Auto-detection rules:

  • Parameter ends with _id atau nama id โ†’ treated as int
  • Lainnya โ†’ treated as string
  • Bisa tetap specify type explicitly: <int:id>, <slug:slug>, <uuid:uuid>

Route Grouping (Gin-style)

Organize routes dengan grouping seperti Gin di Go:

from shanks import App

app = App()

# Create route group
auth = app.group('api/v1/auth')

@auth.post('login')
def login(req):
    return {'message': 'Login'}

@auth.post('register')
def register(req):
    return {'message': 'Register'}

@auth.get('me')
def me(req):
    return {'user': req.user}

# Include group to main app
app.include(auth)

# urlpatterns auto-generated! โœจ

Hasil:

  • POST /api/v1/auth/login
  • POST /api/v1/auth/register
  • GET /api/v1/auth/me

With Middleware

# Auth middleware
def auth_middleware(req, res, next):
    if not req.headers.get('Authorization'):
        return Response().status_code(401).json({'error': 'Unauthorized'})
    next()

# Protected group with middleware
admin = app.group('api/v1/admin', auth_middleware)

@admin.get('users')
def get_users(req):
    return {'users': []}

@admin.get('settings')
def get_settings(req):
    return {'settings': {}}

app.include(admin)

Multiple Groups

# Auth routes
auth = app.group('api/v1/auth')
@auth.post('login')
def login(req): ...

# User routes
users = app.group('api/v1/users')
@users.get('')
def list_users(req): ...
@users.get('<user_id>')
def get_user(req, user_id): ...

# Post routes
posts = app.group('api/v1/posts')
@posts.get('')
def list_posts(req): ...

# Include all
app.include(auth, users, posts)

Lihat ROUTE_GROUPING_EXAMPLE.md untuk contoh lengkap!

Built-in Caching (Enabled by Default!)

Shanks automatically caches all GET requests - 10x faster responses with zero configuration!

from shanks import App

# Cache is enabled by default!
app = App()

@app.get('api/posts')
def list_posts(req):
    # First request: fetches from DB, caches result
    # Next requests: served from cache (10x faster!)
    return {'posts': [...]}

@app.post('api/posts')
def create_post(req):
    # Automatically invalidates /api/posts cache
    return {'created': True}

Customize Cache

# Change cache TTL (default 5 minutes)
app.cache_config(ttl=600)  # Cache for 10 minutes

# Cache specific methods
app.cache_config(ttl=300, methods=['GET', 'HEAD'])

# Disable cache for specific group
realtime = app.group('api/realtime')
realtime.disable_cache()  # No caching for realtime endpoints

# Different cache settings per group
api_v1 = app.group('api/v1')
api_v1.cache_config(ttl=60)  # 1 minute cache

api_v2 = app.group('api/v2')
api_v2.cache_config(ttl=600)  # 10 minutes cache

Manual Cache Control

from shanks import invalidate_cache, get_cache

# Clear all cache
invalidate_cache()

# Clear specific pattern
invalidate_cache('/api/posts')

# Direct cache access
cache = get_cache()
cache.set('key', 'value', ttl=300)
value = cache.get('key')
cache.delete('key')

How It Works

  1. Auto-cache GET requests: First request fetches from DB and caches
  2. Smart invalidation: POST/PUT/DELETE automatically clear related cache
  3. Pattern matching: /api/posts/123 invalidates /api/posts cache
  4. TTL-based: Cache expires after configured time (default 5 minutes)

Benefits:

  • โšก 10x faster response times
  • ๐Ÿ”„ Automatic - no code changes needed
  • ๐Ÿง  Smart invalidation on writes
  • ๐Ÿ’พ Memory efficient with TTL
  • ๐ŸŽฏ Pattern-based invalidation

Code Quality

# Format code dengan Black
shanks format

# Lint dengan Flake8
shanks lint

# Format + Lint sekaligus
shanks check

Help

# Lihat semua commands
shanks help

๐Ÿ“– Dokumentasi Lengkap

CLI ini adalah bagian dari Shanks Django framework yang menyediakan:

  • Express.js-like syntax untuk routing
  • Prisma-like ORM untuk database queries
  • Built-in caching, CORS, Swagger
  • Middleware support
  • Multi-database support (PostgreSQL, MySQL, MongoDB, Redis)

Untuk dokumentasi lengkap tentang API, ORM, middleware, dan fitur lainnya:

๐ŸŽ VSCode Extension

Install extension untuk snippets dan IntelliSense:

  1. Buka VSCode
  2. Extensions (Ctrl+Shift+X)
  3. Cari "Shanks Django"
  4. Install

Atau langsung: https://marketplace.visualstudio.com/items?itemName=Ararya.shanks-django

Snippets yang tersedia:

  • shanks-app - Create new Shanks app
  • shanks-get - GET route
  • shanks-post - POST route
  • shanks-crud - Full CRUD template
  • Dan banyak lagi...

๐Ÿค Contributing

Contributions welcome! Check Contributing Guide.

# Clone repository
git clone https://github.com/Ararya/shanks-django.git
cd shanks-django

# Install dependencies
pip install -e ".[dev]"

# Run tests
pytest

๐Ÿ“ License

MIT License - see LICENSE file.

๐Ÿ”— Links


Made with โค๏ธ by Ararya

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

shanks_django-0.2.6.tar.gz (41.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

shanks_django-0.2.6-py3-none-any.whl (39.8 kB view details)

Uploaded Python 3

File details

Details for the file shanks_django-0.2.6.tar.gz.

File metadata

  • Download URL: shanks_django-0.2.6.tar.gz
  • Upload date:
  • Size: 41.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for shanks_django-0.2.6.tar.gz
Algorithm Hash digest
SHA256 08bb57b5c51a4d118289d1fc879aaab65cb4958e0b3b3559ff0d82dab54a0ce6
MD5 f4b8d17d12534db957ec82daac54ac57
BLAKE2b-256 2bc469ee19d1590ca5ea497b3f2afd583dba03b1454ab8eb295f5f8283968386

See more details on using hashes here.

File details

Details for the file shanks_django-0.2.6-py3-none-any.whl.

File metadata

  • Download URL: shanks_django-0.2.6-py3-none-any.whl
  • Upload date:
  • Size: 39.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for shanks_django-0.2.6-py3-none-any.whl
Algorithm Hash digest
SHA256 4af6ea66ab4be876ad4742ca177fb737ea8c735f151b22f3f9f6acfaab80c3a6
MD5 3019c947f3ff696ecb04b1450626b3e3
BLAKE2b-256 bd96bed33bb531f058e0789abab59d64a5ff5add87d594e4139ed264aa358f7e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page