I can't find a proper way to redirect data from submitted form to a REST api.
Currently - like in example below - "POST" method is handled in the view/route (see route "add_person()").
My sample data model (SQLAlchemy-based):
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
Form for rendering via html (wtforms-based):
class PersonForm(FlaskForm):
name = TextField("Person name", validators=[DataRequired()])
View/route declaration:
@views.route('add_person', methods=["GET", "POST"])
def add_person():
form = PersonForm()
if request.method == 'POST' and form.validate_on_submit():
person = Person()
person.name = form.name.data
db.session.add(person)
db.session.commit()
return redirect(url_for('view.add_person'))
return render_template('person_add.html', form=form)
HTML template:
<form method="POST" action="/add_person">
{{ form.csrf_token }}
{{ form.name.label }} {{ form.name(size=20) }}
<input type="submit" value="Submit">
</form>
Now I'd like to delegate database/CRUD related actions to a REST api.
API endpoint generated for a "Person" data model is: "/api/person".
If I switch form's "action" from:
"/add_person"
to:
"/api/person",
then I'm redirected to the API url, so I guess that's not a proper way of doing that.
I think I still should be using the view/route handling and make a POST api call there instead of persisting the "Person" object. Is this the cleanest solution? How could I approach this?
I'll answer this myself. I ended up with staying with form's "/add_person" POST action that's handled in Flask, and then making request to API endpoint using Python "requests" library.