sanic_crud is a REST API framework for creating a CRUD (Create/Retrieve/Update/Delete) API using Sanic and PeeWee You can use sanic_crud to automatically create an API from your PeeWee models

Installation

python -m pip install sanic-crud

Example

from peewee import CharField, DateTimeField, SqliteDatabase, Model
import datetime
from sanic import Sanic
from sanic_crud import generate_crud

db = SqliteDatabase('my_app.db')

class BaseModel(Model):
    class Meta:
        database = db

class Person(BaseModel):
    name = CharField()
    email = CharField()
    create_datetime = DateTimeField(default=datetime.datetime.now, null=True)

db.create_tables([Person])

app = Sanic(__name__)
generate_crud(app, [Person])
app.run(host="0.0.0.0", port=8000, debug=True)

simple_server.py

from sanic import Sanic
from sanic_crud import generate_crud
from .model import db, Person


db.create_tables([Person])

app = Sanic(__name__)
generate_crud(app, [Person])
app.run(host="0.0.0.0", port=8000, debug=True)

model_with_custom_messages.py

from peewee import CharField, DateTimeField, SqliteDatabase, Model
import datetime
from sanic_crud import CrudConfig, ResponseMessages


db = SqliteDatabase('my_app.db')


class BaseModel(Model):
    class Meta:
        database = db

config = CrudConfig()
response_messages = ResponseMessages()
response_messages.ErrorDoesNotExist = 'Custom error message here: {}'
config.response_messages = response_messages


class Person(BaseModel):
    crud_config = config

    name = CharField()
    email = CharField()
    create_datetime = DateTimeField(default=datetime.datetime.now, null=True)

model_with_custom_config.py

from peewee import CharField, DateTimeField, SqliteDatabase, Model
import datetime
from sanic_crud import CrudConfig


db = SqliteDatabase('my_app.db')


class BaseModel(Model):
    class Meta:
        database = db

config = CrudConfig()
config.COLLECTION_MAX_RESULTS_PER_PAGE = 500


class Person(BaseModel):
    crud_config = config

    name = CharField()
    email = CharField()
    create_datetime = DateTimeField(default=datetime.datetime.now, null=True)

model.py

from peewee import CharField, DateTimeField, SqliteDatabase, Model
import datetime


db = SqliteDatabase('my_app.db')


class BaseModel(Model):
    class Meta:
        database = db


class Person(BaseModel):
    name = CharField()
    email = CharField()
    create_datetime = DateTimeField(default=datetime.datetime.now, null=True)

 

keywords: pythonsanic