Created
September 13, 2010 20:20
-
-
Save ericmoritz/577956 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Takes a WTForm and saves it into a mongodb collection... who needs an ODM, we've got | |
| WTForms! | |
| """ | |
| from wtforms import * | |
| from wtforms.fields import Field | |
| from wtforms.widgets import TextInput, TextArea | |
| from flask import (Flask, abort, request, flash, redirect, | |
| url_for, render_template) | |
| import pymongo | |
| # Get a test database from pymongo | |
| content = pymongo.Connection().test.content | |
| app = Flask(__name__) | |
| class TagListField(Field): | |
| widget = TextInput() | |
| def _value(self): | |
| if self.data: | |
| return u', '.join(self.data) | |
| else: | |
| return u'' | |
| def process_formdata(self, valuelist): | |
| if valuelist: | |
| self.data = [x.lower().strip() for x in valuelist[0].split(',')] | |
| else: | |
| self.data = [] | |
| class PathField(Field): | |
| widget = TextInput() | |
| def process_formdata(self, valuelist): | |
| if valuelist: | |
| self.data = valuelist[0].lower() | |
| class ContentForm(Form): | |
| title = TextField("Title", validators=[validators.required()]) | |
| summary = TextField("Summary") | |
| body = TextField("Body", widget=TextArea()) | |
| tags = TagListField() | |
| @app.route("/edit/<path>/", methods=["GET", "POST"]) | |
| def edit(path): | |
| doc = content.find_one({'path': path}) | |
| if doc is None: | |
| doc = {} | |
| form = ContentForm(request.form, **doc) | |
| if request.method == "POST" and form.validate(): | |
| # Upsert the document | |
| content.update({'path': path}, | |
| form.data, | |
| upsert=True, | |
| safe=True) | |
| flash("%s updated" % (path, )) | |
| # redirect to the view page | |
| return redirect(url_for("view", path=path)) | |
| return render_template("edit.html", | |
| doc=doc, | |
| form=form) | |
| @app.route("/<path>/") | |
| def view(path): | |
| # Paths always have a leading slash | |
| doc = content.find_one({'path': path}) | |
| if doc is None: | |
| return redirect(url_for("edit", path=path)) | |
| return render_template("view.html", | |
| doc=doc) | |
| if __name__ == '__main__': | |
| app.run(debug=True, host="0.0.0.0", port=8001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment