You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask测试客户端POST请求失败求助(TestDriven.io课程场景)

Fixing psycopg2.ProgrammingError: can't adapt type 'now' when inserting a user with SQLAlchemy

Hey, let's break down what's causing this error and get your test_add_user case passing smoothly.

What's going wrong here?

Looking at your error stack trace, the issue is clear: your INSERT query is trying to pass a raw sqlalchemy.sql.functions.now object as the created_date value. Psycopg2 (the PostgreSQL adapter for Python) doesn't know how to convert this Python object into a valid date/time value that PostgreSQL can understand, hence the can't adapt type 'now' error.

This almost always happens when you're manually passing func.now() to the created_date field when creating a User instance, instead of letting SQLAlchemy handle the timestamp automatically via a model default.

Step-by-step fix

1. Correct your User model definition

Update your User model to set func.now() as the default value for created_date. This tells SQLAlchemy to automatically populate the field with the current timestamp when a new user is created:

from sqlalchemy.sql import func
from project import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    active = db.Column(db.Boolean, default=True)
    # Use default=func.now() to auto-set the creation timestamp
    created_date = db.Column(db.DateTime, default=func.now())

2. Update your route handler to omit created_date

In your project/api/users.py route function, remove any manual reference to created_date when creating the User object. Let the model's default handle this field:

from flask import request, jsonify
from project.api.users import users_blueprint
from project.models import User
from project import db

@users_blueprint.route('/users', methods=['POST'])
def add_user():
    data = request.get_json()
    
    # Validate input fields
    if not data or 'username' not in data or 'email' not in data:
        return jsonify({
            'status': 'fail',
            'message': 'Missing required fields: username or email'
        }), 400
    
    # Check for existing user with the same email
    if User.query.filter_by(email=data['email']).first():
        return jsonify({
            'status': 'fail',
            'message': 'A user with this email already exists'
        }), 409
    
    # Create user WITHOUT passing created_date
    new_user = User(
        username=data['username'],
        email=data['email']
        # active=True is optional here if your model already sets default=True
    )
    
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({
        'status': 'success',
        'message': f'{data["email"]} was added!'
    }), 201

Why this works

By setting default=func.now() on the model column, SQLAlchemy generates the correct SQL to insert the current timestamp using PostgreSQL's native NOW() function. Instead of passing a Python now object to the database, it sends a SQL command that PostgreSQL understands perfectly.

Verify the fix

Run your test again to confirm it passes:

pytest tests/test_users.py::TestUserService::test_add_user -v

Your test_add_user case should now execute without the psycopg2.ProgrammingError exception.

内容的提问来源于stack exchange,提问作者turing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:22:54