0

I'm a newbie programmer using flask with wtforms on GAE to take in data via forms and just list the data. Everything is currently working but most of my views use very similar methods of form creation, posting, and listing. I wanted a way to simplify the mess and reduce the amount of code I used.

I've seen three potential options:

  1. Pluggable views from Flask
  2. Just a simple flask decorator somehow
  3. Possibly Method views? (see 1).

Currently I have a few of these /new/post /new/home etc..

Relevant Snipets of code below: Views:

@app.route('/new/post', methods = ['GET', 'POST'])
@login_required
def new_post():

    form = PostForm()
    if form.validate_on_submit():
        post = Post(title = form.title.data,
                    content = form.content.data,
                    hometest = form.hometest.data,
                    author = users.get_current_user())
        post.put()
        flash('Post saved on database.')
        return redirect(url_for('list_posts'))
    form.hometest.choices = [ (h.key.id(),h.homename)for h in Home.query()]
    return render_template('new_post.html', form=form)

@app.route('/new/home',methods = ['GET','POST'])
def home_new():
    form = HomeForm()
    if form.validate_on_submit():
        home = Home(homeid = int(form.homeid.data),
                    homename = form.homename.data)
        home.put()
        flash('Home saved on database')
        return redirect(url_for('home'))
    return render_template('new_home.html',form = form)

Models:

class Home(ndb.Model):
    homeid = ndb.IntegerProperty(required=True)
    homename = ndb.StringProperty(required=True)
    hometest = ndb.IntegerProperty(required=True)

class Post(db.Model):
    title = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    when = db.DateTimeProperty(auto_now_add = True)
    author = db.UserProperty(required = True)

Forms:

class PostForm(Form):
    title = wtf.TextField('Title', validators=[validators.Required()])
    content = wtf.TextAreaField('Content', validators=[validators.Required()])
    hometest = wtf.SelectField(u'Home Name List', coerce=int,validators=[validators.optional()])

class HomeForm(wtf.Form):
    homeid = TextField('ID of Home', [validators.Length(min=1, max=25)])
    homename = TextField('Name of Home', [validators.Length(min=4, max=25)])

I was thinking something sleeker like :

@app.route('/new/<whatsnew>', methods)
@mydecorator
def new_whatsnew:
     Stuff specific to <whatsnew>


@app.route('/list/<whatsnew>', methods)
@mydecorator
def list_whatsnew
     Stuff specific to <whatsnew>

And of course if there are more acceptable ways (or no way around this ). I'm not looking for actual code though an example would be nice but which is the proper design method for this?

3 Answers 3

2

Maybe you need a pluggable view like this:

class FormView(View):
    def __init__(self):
        self.form_class = None
        self.template = ''
        self.success_url = ''

    def on_validate(self, form):
        pass

    def on_invalidate(self, form):
        pass

    def dispatch_request(self):
        form = self.form_class()

        if form.validate_on_submit():
            self.on_validate(form)
            return redirect(self.success_url)

        self.on_invalidate(form)
        return render_template(self.template, form=form)
0
0

Thanks for the answer. I'm still a bit confused. So to use this by say my post view or home view

def postview(FormView):
   self.form_class = "HomeForm"
   self.template = 'homelist.html' #without html # this is the form template?
   self.success_url = url_for('homelist') #redirect goes here?

... From the pluggable view documentation here I'm confused about the usage of :

def dispatch_request(self):
        context = {'objects': self.get_objects()}
        return self.render_template(context)

In the parent class and the below in the one that inherits:

def get_objects(self):
        return User.query.all()

The context is a built in Flask object, but the magic that links the form template to a formmodel, puts it into my gae model, and then sends you to another url confused me still.

0

I'm getting a :

File "/Volumes/320gb/Dropbox/Projects/git_projects/virtualenvs/gae/gae_take2000/flask/app.py", line 723, in make_response raise ValueError('View function did not return a response') ValueError: View function did not return a response

Error when I add a new SensorsView. Works fine for all the other almost identical views. Here are two identical ones.

Obviously the error is something about POST but I can't figure out why it's breaking.

ParentClass:

class FormView(View):
    methods = ['GET', 'POST']

    def __init__(self):
        self.form_class     = None
        self.template       = ''
        self.success_url    = ''
        self.sfield         = False

    def on_validate(self, form):
        pass

    def on_invalidate(self, form):
        pass

    def on_sfield(self, form):
        pass

    def dispatch_request(self):
        form = self.form_class()

        if self.sfield:
            form = self.on_sfield(form)

        if request.method == 'GET':
            return render_template(self.template, form=form)

        if request.method == 'POST':
            if form.validate_on_submit():
                self.on_validate(form)
                return redirect(url_for(self.success_url))

Inherited ZoneView (working perfectly):

class ZoneView(FormView):
    def __init__(self):
        FormView.__init__(self)
        self.form_class     = ZoneForm
        self.template       = 'new_zone.html'
        self.success_url    = 'ZoneList'
        self.sfield         = True

    def on_sfield(self,form):
        form.homekey.choices = [ (h.key.id(),h.homename)for h in Home.query()]
        return form

    def on_validate(self, form):
        zone = Zone(zname    = form.zname.data,
                    zonemac     = form.zonemac.data) #,        homekey    = form.homekey.data

        zone.put()
        flash('Zone saved on database.')

app.add_url_rule('/new/zone', view_func=ZoneView.as_view('ZoneView'),  methods = ['GET', 'POST'])

SensorsView (not working with error):

class SensorsView(FormView):
    def __init__(self):
        FormView.__init__(self)
        self.form_class     = SensorForm
        self.template       = 'new_sensors.html'
        self.success_url    = 'SensorList'
        self.sfield         = True

    def on_sfield(self,form):
        form.zonekey.choices = [ (h.key.id(),h.zname)for h in Zone.query()]
        return form

    def on_validate(self, form):
        sensor = Sensor(sensortype = form.sensortype.data,
                        pinmapping = form.pinmapping.data)
        #        zonekey = form.zonekey.data
        sensor.put()
        flash('Home saved on database.')

app.add_url_rule('/new/sensor', view_func=SensorsView.as_view('SensorsView'),    methods = ['GET', 'POST'])

The templates: **new_zone:**

{% extends "base.html" %}
{% import 'macros.html' as mymacros %}



{% block content %}
<h1 id="">This is where your zone name will come into play</h1>
<form action="{{ url_for('ZoneView') }}" method="post" accept-charset="utf-8">
    {{ form.csrf_token }}


    <p>
        {{mymacros.form_fields(form)}}
    </p>


    <p><input type="submit" value="Save Zone"/></p>
</form>
{% endblock %}

new_sensors.html

{% extends "base.html" %}
{% import 'macros.html' as mymacros %}

{% block content %}
<h1 id="">This is where your home name will come into play</h1>
<form action="{{ url_for('SensorsView') }}" method="post" accept-charset="utf-8">
    {{ form.csrf_token }}

    <p>
        {{mymacros.myform_field(form.sensortype)}}
    </p>

    <p><input type="submit" value="Save post"/></p>
</form>
{% endblock %}

The codes were cut-paste and changed to fit. Pretty much identical. I have no clue why it's complaining about View function. Is there a typo I just don't see ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.