Skip to content

Instantly share code, notes, and snippets.

@saaj
Last active September 12, 2018 09:50
Show Gist options
  • Save saaj/c86a96c3fcd2068ce1d09b473895712b to your computer and use it in GitHub Desktop.
Save saaj/c86a96c3fcd2068ce1d09b473895712b to your computer and use it in GitHub Desktop.
Marshmallow field validation for an empty text field
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import itertools\n",
"\n",
"from marshmallow import Schema, fields"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(True, undefined, None)\n",
"(True, None, None)\n",
"(True, '', None)\n",
"(True, 'some string', None)\n",
"(False, undefined, None)\n",
"(False, None, None)\n",
"(False, '', None)\n",
"(False, 'some string', None)\n"
]
}
],
"source": [
"def test(**kwargs):\n",
" class TestSchema(Schema):\n",
" name = fields.Str(**kwargs)\n",
" s = TestSchema()\n",
" return s.load({'name': None})\n",
"\n",
"class Undefined:\n",
" def __repr__(self):\n",
" return 'undefined'\n",
"\n",
"undefined = Undefined()\n",
"required = [True, False]\n",
"default = missing = [undefined, None, '', 'some string']\n",
"\n",
"for p in itertools.product(required, default, missing):\n",
" kwargs = dict(zip(['required', 'default', 'missing'], p))\n",
" kwargs = {k: v for k, v in kwargs.items() if v is not undefined}\n",
" if not test(**kwargs).errors:\n",
" print(p)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment