I am learning Flask
and I have found various snippets which show how to define models with SQLAlchemy
, REST API with Flask-restless
and forms with Flask-wtf
(I'm not very familiar with REST API). More precisely I took inspiration from:
- Flask-restless Quickstart (from the doc)
- Automatically create a WTForms Form from model (which dates back to 2011)
- This SO question for the basic template
However I have not been able to create a fully working example. Building on the bits you can find online, I want to create a model with 2 classes Person
and Computer
(a Person
can be associated with several Computer
s) and a form to add a new Person
. Here is the code I have assembled.
The layout is the following:
test_flask/
├── test_flask.py
├── config.py
└── templates
└── new_person.html
The main file test_flask.py
contains:
from flask import Flask, request, flash, redirect, render_template, url_for
import flask.ext.sqlalchemy
from wtforms.ext.sqlalchemy.orm import model_form
import flask.ext.restless
from flaskext.wtf import Form
# Create the Flask application and the Flask-SQLAlchemy object.
app = Flask(__name__)
app.config.from_object('config')
db = flask.ext.sqlalchemy.SQLAlchemy(app)
# Create the Flask-SQLALchemy models.
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
birth_date = db.Column(db.Date)
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
purchase_time = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
owner = db.relationship('Person', backref=db.backref('computers',
lazy='dynamic'))
# Create the database tables.
db.create_all()
# Create the Flask-Restless API manager.
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
# Create API endpoints.
manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Computer, methods=['GET'])
# Create a form class for class Person.
PersonForm = model_form(Person, base_class=Form)
@app.route('/')
def hello():
return 'Hello World'
@app.route("/api/new_person")
def new_person():
# The new person
person = Person()
# Create a form
form = PersonForm(request.form, person)
if form.validate_on_submit():
form.populate_obj(person)
person.post()
flash("new person %s inserted updated" % person)
return redirect(url_for("new_person"))
return render_template("new_person.html", form=form)
if __name__ == '__main__':
# start the flask loop
app.run()
The config.py
file contains:
DEBUG = True
WTF_CSRF_SECRET_KEY = 'a random string'
SECRET_KEY = 'you-will-never-guess'
WTF_CSRF_ENABLED = True
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
The template new_person.html
contains:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="application/json">
<title>New person</title>
</head>
{% block body %}
<form action="new_person" method=post class=add-entry>
<dl>
<dt>Name:
<dd>{{form.name}}
<dt>Birth date:
<dd>{{form.birth_date}}
<dd><input type=submit value=submit>
</dl>
</form>
{% endblock %}
</html>
I can see the form to add a new person at http://127.0.0.1:5000/api/new_person/
but I got a "Method Not Allowed" error when submitting it.