Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extension for WTForms #11

Open
cthoyt opened this issue Sep 25, 2018 · 3 comments
Open

Extension for WTForms #11

cthoyt opened this issue Sep 25, 2018 · 3 comments
Assignees
Labels
enhancement New feature or request

Comments

@cthoyt
Copy link
Contributor

cthoyt commented Sep 25, 2018

Would be cool to automatically generate a form for use with Flask / Flask-WTF automatically from a given EasyConfig. Will submit PR later :)

@cthoyt
Copy link
Contributor Author

cthoyt commented Sep 25, 2018

Is there a smart way for introspecting which fields have default values?

@cthoyt
Copy link
Contributor Author

cthoyt commented Sep 25, 2018

Okay this isn't so complete but it's bed time. Also disregard the weird name of the variable in the test.

# -*- coding: utf-8 -*-

"""Test the Flask-WTF wrapper."""

import dataclasses
from typing import Type

import flask
from flask_wtf import FlaskForm
from wtforms import BooleanField, IntegerField, StringField
from wtforms.validators import DataRequired

from easy_config import EasyConfig

type_to_field = {
    str: StringField,
    int: IntegerField,
    bool: BooleanField,
}


def form_from_config(cls: Type[EasyConfig]):
    """Build a Flask-WTF form based on the given EasyConfig class."""
    attrs = {}

    for field in dataclasses.fields(cls):
        field_cls = type_to_field[field.type]
        attribute = field_cls(field.name, validators=[DataRequired()])
        if field.default is not dataclasses.MISSING:
            attribute.default = field.default
        attrs[field.name] = attribute

    return type(f'{cls.NAME}Form', (FlaskForm,), attrs)


def test_with_default():
    class ExampleConfig(EasyConfig):
        """Example EasyConfig subclass to test with."""

        FILES = None
        NAME = 'MyProgram'

        number: bool



    form_cls = form_from_config(ExampleConfig)
    app = flask.Flask('test_app')

    with app.app_context():
        form = form_cls(csrf_enabled=False)
        for field in form:
            print(field)

        fields = list(form)
        assert 1 == len(fields)
        field = fields[0]
        assert str(field) == '<input id="number" name="number" required type="checkbox" value="y">'

@scolby33
Copy link
Owner

Same discussion as #4 (comment) applies.

@scolby33 scolby33 added the enhancement New feature or request label Oct 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants