python - flask with wtforms how to improve my code with either pluggable views or decorators or other? -
i'm newbie programmer using flask wtforms on gae take in data via forms , list data. working of views use similar methods of form creation, posting, , listing. wanted way simplify mess , reduce amount of code used.
i've seen 3 potential options:
- pluggable views flask
- just simple flask decorator somehow
- possibly method views? (see 1).
currently have 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 thinking sleeker :
@app.route('/new/<whatsnew>', methods) @mydecorator def new_whatsnew: stuff specific <whatsnew> @app.route('/list/<whatsnew>', methods) @mydecorator def list_whatsnew stuff specific <whatsnew>
and of course if there more acceptable ways (or no way around ). i'm not looking actual code though example nice proper design method this?
maybe need pluggable view 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)
Comments
Post a Comment