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

时间:2015-07-28 22:38:29

标签: python session heroku flask flask-sqlalchemy

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!

1 个答案:

答案 0 :(得分:0)

在此处充分利用您的网页模型。

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

你可能也会遇到条件问题 - 如果方法不是POST,那么什么都不会发生,并且不会记录任何关于它的消息。如果从路径声明中的方法中删除“GET”,则根本不需要该条件。

我建议您查看Flask-WTF扩展,以及打破表单验证并将步骤重定向到单独的函数。 Flask最好的方法是将元素分解为最小的可用组件,然后以多种不同的方式重新组装它们。

有关表单处理的更多信息,请查看Miguel Grinberg's Flask Mega-Tutorial(如果您还没有)。