From 6b45bb1ff6d835fbccc7f756b5408f9c24ff2b06 Mon Sep 17 00:00:00 2001 From: Izalia Mae Date: Wed, 17 Nov 2021 07:42:46 -0500 Subject: [PATCH] sql.table.Column: force default to be server_default, http_server_async.response.Response: return json response when appropriate --- izzylib/http_server_async/misc.py | 4 ++++ izzylib/http_server_async/response.py | 3 +++ izzylib/sql/table.py | 12 +++++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/izzylib/http_server_async/misc.py b/izzylib/http_server_async/misc.py index eb6701c..c29da99 100644 --- a/izzylib/http_server_async/misc.py +++ b/izzylib/http_server_async/misc.py @@ -62,6 +62,10 @@ class Headers(DotDict): super().__setitem__(key, HeaderItem(key, value)) + def get(self, key, default=None): + return super().get(key.title(), default) + + def as_dict(self): data = {} diff --git a/izzylib/http_server_async/response.py b/izzylib/http_server_async/response.py index 9f57194..5c68a23 100644 --- a/izzylib/http_server_async/response.py +++ b/izzylib/http_server_async/response.py @@ -155,6 +155,9 @@ class Response: def set_error(self, message, status=500): try: + if self.request and 'json' in self.request.headers.getone('accept', ''): + return self.set_json({'error': message, 'code': status}, status=status) + return self.set_template('error.haml', context = { 'error_message': message, diff --git a/izzylib/sql/table.py b/izzylib/sql/table.py index fda4cc2..1da12a7 100644 --- a/izzylib/sql/table.py +++ b/izzylib/sql/table.py @@ -1,3 +1,5 @@ +import json + from sqlalchemy import ForeignKey from sqlalchemy import ( Column as sqlalchemy_column, @@ -9,6 +11,12 @@ from ..dotdict import DotDict ptype = type SqlTypes = {t.lower(): getattr(Types, t) for t in dir(Types) if not t.startswith('_')} +default_types = { + dict: json.dumps, + list: json.dumps, + tuple: json.dumps, + bool: lambda data: "1" if data else "0" +} class Column(sqlalchemy_column): @@ -34,7 +42,9 @@ class Column(sqlalchemy_column): except KeyError: raise KeyError(f'Invalid SQL data type: {type}') - if kwargs.get('default'): + if 'default' in kwargs.keys(): + value = kwargs.pop('default') + kwargs['server_default'] = default_types.get(ptype(value), str)(value) kwargs['nullable'] = False options = [name, type]