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/<int: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/<int: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/<int: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

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:

# Old way (masih bisa dipakai)
@app.get('api/posts/<int:post_id>')
def get_post(req, post_id):
    return {'id': post_id}

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

@app.get('api/users/<username>')  # auto-detect as string
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 = app.get_urls()

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.0.tar.gz (37.4 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.0-py3-none-any.whl (36.0 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for shanks_django-0.2.0.tar.gz
Algorithm Hash digest
SHA256 122990f402c3a7391157757874fb69fce955435e1d03ff00654ede87aeaadfd8
MD5 7ef7363ac2f61e93d5248a337109f9ba
BLAKE2b-256 05b26201ccb768cb876422a0716c60ac8c3dd1df18a59e95a4d1c7f65e55b08b

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for shanks_django-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ea1000394cc61fbfd766bbb384ec3a41ac72fd95849dee89aeffb5ec7ad8018c
MD5 39e1693cd2aa471730f99f81bf8743a8
BLAKE2b-256 6f1f952e73d4c6f0c33fd3cd0d3a4defc09d8c330ee2fe166bf5f438fb5172e1

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