简体   繁体   中英

Flask-SLAlchemy session.add() and session.commit() don't work

I have a heroku app that I am trying to add a database to. I am using Flask-SLAlchemy, PostgreSQL (and psql). I've already created a table in the database, but I cannot add any rows to it. Here is what I believe to be all relevant code:

import flask
import keys
import requests_oauthlib
import json
import os
import psycopg2
import urlparse
from flask import (Flask, jsonify, render_template, redirect, url_for, request, make_response)
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'heroku-url-here'
db = SQLAlchemy(app)

class Page (db.Model):
    __tablename__ = "pages"
    title = db.Column('Title', db.String)
    date = db.Column('Date', db.String, primary_key=True)
    writing = db.Column('Writing', db.String)

    def __init__(self, title, date, writing):
        self.title = title
        self.date = date
        self.writing = writing

    def __repr__(self):
        return '<Page %r>' % self.date


app.secret_key = keys.secret_key
# db.create_all()
# this created the database already after I ran it once, it made a psycopg2 error after that first time.

@app.route('/db', methods=['GET', 'POST'])
def db():
    if request.method == 'POST':
        title = request.form['title']
        date = request.form['date']
        writing = request.form['writing']
        newest = Page(title, date, writing)
        print newest
        db.session.add(newest)
        db.session.commit()
    else:
        title = None
        date = None
        writing = None
    return flask.redirect(flask.url_for('home'))

In my heroku logs, there are no errors shown. The code runs to the the print newest line, and the newly created Page is printed as <Page u'whatever-the-date-was'> . When a form is submitted in my html template, it calls the function by using the action {{url_for('db')}} .

This is my first time using heroku and flask and basically doing any back-end stuff, so please explain thoroughly if you have an answer. Thanks in advance!

Take advantage of your Page model here.

db.session.add(Page(
    title = request.form['title']
    date = request.form['date']
    writing = request.form['writing']
    ))
db.session.commit()

You'll probably also run into trouble with your conditional - if the method isn't POST then nothing will happen, and there won't be any message logged about it. If you remove the 'GET' from the methods in the route declaration you won't need that conditional at all.

I'd recommend taking a look at the Flask-WTF extension, as well as breaking out your form validation and redirect steps into separate functions. Flask works best by breaking down elements to their smallest usable components and then reassembling them in many different ways.

For more info on form handling, check out Miguel Grinberg's Flask Mega-Tutorial (if you haven't already).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM