Last active
January 8, 2019 21:40
-
-
Save marteinn/cb36a8f49fb6c5f12acf4809a9fe488d to your computer and use it in GitHub Desktop.
Testing coconut language (http://coconut-lang.org/) and bottle.py
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
""" | |
Installation: | |
pip install coconut | |
pip install bottle | |
pip install peewee | |
Running: | |
coconut test.coco && python test.py | |
""" | |
from bottle import route, run, template, response, request | |
from peewee import Model, CharField, SqliteDatabase | |
from playhouse.shortcuts import model_to_dict, dict_to_model | |
# Models | |
db = SqliteDatabase('employees.db') | |
class BaseModel(Model): | |
class Meta: | |
database = db | |
class Employee(BaseModel): | |
email = CharField(unique=True) | |
company = CharField() | |
# Helpers | |
def response_ok(data) = {"data": data} | |
def response_not_found(data): | |
response.status = 404 | |
return {"data": data} | |
# Handlers | |
@route('/employees') | |
def index(): | |
return response_ok <| employees where: | |
employees = (Employee.select() |> map$(model_to_dict) |> list) | |
@route('/employees/<email>') | |
def detail(email): | |
matches = Employee.select() |> .where(Employee.email == email) |> map$(model_to_dict) |> list | |
case matches: | |
match [employee]: return response_ok <| employee | |
match _: return response_not_found <| "Employee not found" | |
@route('/employees/<email>', method='DELETE') | |
def delete(email): | |
status = Employee.delete() |> .where(Employee.email == email) |> .execute() | |
case status: | |
match 1: return response_ok <| "deleted" | |
match _: return response_not_found <| "employee not found" | |
@route('/employees', method='POST') | |
def create(): | |
employee = Employee.create(**request.forms) |> .save() | |
return response_ok <| "created" | |
@route('/create-local-db') | |
def create_local_db(): | |
db.create_tables <| [Employee] | |
return response_ok <| "created" | |
# Setup | |
def init_app() = ( | |
db |> .connect(), | |
run(host='localhost', port=8080), | |
) | |
init_app() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment