gpt4 book ai didi

Flask DateTime 不会设置为默认 datetime.utcnow

转载 作者:行者123 更新时间:2023-12-03 15:32:14 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How Can I Automatically Populate SQLAlchemy Database Fields? (Flask-SQLAlchemy)

(2 个回答)


2年前关闭。




我是 Sqlalchemy 的新手,无法为创建的日期时间设置。我曾尝试使用许多示例中的“默认”选项。我也试过手动设置它(我已经注释掉了)。到目前为止,两者都没有工作。任何帮助,将不胜感激。

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)

最佳答案

您的问题 default是你打电话datetime.utcnow立即在那里,并且返回的值(在类定义时)始终用作默认值。您需要传递可调用本身,如下所示:

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

这样 SQLAlchemy 将调用 datetime.utcnow在行插入时本身。

关于Flask DateTime 不会设置为默认 datetime.utcnow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20931479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com