Flask DateTime won't set with default datetime.utcnow [duplicate]

本小妞迷上赌 提交于 2019-12-01 02:36:23

问题


I am new to SQLAlchemy and have been unable to set the DateTime for created. I have tried using the "default" option found in many examples. I have also tried setting it manually (I have it commented out). Neither have worked so far. Any help would be appreciated.

models.py

import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash

db = SQLAlchemy()

class User(db.Model):

  __tablename__    = 'users'
  uid              = db.Column(db.Integer, primary_key=True)
  firstname        = db.Column(db.String(40))
  lastname         = db.Column(db.String(40))
  email            = db.Column(db.String(120), unique=True)
  created          = db.Column(db.DateTime, default=datetime.datetime.utcnow())
  confirmed        = db.Column(db.DateTime, nullable=True)
  pwdhash          = db.Column(db.String(100))

  def __init__(self, firstname, lastname, email, password):
    self.firstname = firstname.title()
    self.lastname  = lastname.title()
    self.email     = email.lower()
    self.set_password(password)
    #self.created   = datetime.datetime.utcnow()
    self.confirmed = None

  def set_password(self, password):
    self.pwdhash   = generate_password_hash(password)

  def check_password(self, password):
    return check_password_hash(self.pwdhash, password)

routes.py

from tasks import app
from datetime import datetime
from flask import render_template, request, flash, session, url_for, redirect
from forms import ContactForm, SignupForm, SigninForm
from flask.ext.mail import Message, Mail
from models import db, User, Tags, Tasks

@app.route('/signup', methods=['GET', 'POST'])
def signup():
  form = SignupForm()

  if 'email' in session:
    return redirect(url_for('profile')) 

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('signup.html', form=form)
    else:
      newuser = User(form.firstname.data, form.lastname.data, form.email.data, form.password.data)
      db.session.add(newuser)
      db.session.commit()

      session['email'] = newuser.email
      return redirect(url_for('profile'))

  elif request.method == 'GET':
    return render_template('signup.html', form=form)

回答1:


The problem with your default is that you're calling datetime.utcnow immediately there, and the value returned (at the time of class definition) is always used as default. You need to pass the callable itself like following:

# Note the lack of parenthesis after datetime.utcnow
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)

This way SQLAlchemy will call datetime.utcnow itself upon row insert.



来源:https://stackoverflow.com/questions/20931479/flask-datetime-wont-set-with-default-datetime-utcnow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!