miguelgrinberg / flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
MIT License
8.54k stars 4.21k forks source link

psycopg2.ProgrammingError: #502

Closed Makeem49 closed 3 years ago

Makeem49 commented 3 years ago

Hello Miguel, Thanks for your contribution in my programming career. I'm having problem with my app i'm currently building though it's a clone application. So, whenever i tried to add a new user i usually get this error : psycopg2.ProgrammingError: can't adapt type 'builtin_function_or_method' . Below is my model code and config for database url

confi.py

pd_str = 'postgresql://postgres:Olayinka1?@localhost:5432/snakeeyes' 
SQLALCHEMY_DATABASE_URI=pd_str

Model.py

from snakeeyes.extensions import db
import datetime
from werkzeug.security import check_password_hash, generate_password_hash
from flask_login import UserMixin
from snakeeyes.extensions import login_manager
from flask import current_app
from itsdangerous import TimedJSONWebSignatureSerializer

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(24), nullable=True, unique=True)
    email = db.Column(db.String(128), nullable=False, unique = True)
    active = db.Column(db.Boolean, default = True, nullable=False)
    hash_password = db.Column(db.String(240), nullable=False)
    confirmed = db.Column(db.Boolean(), default = False, nullable=False)

    sign_in_count = db.Column(db.Integer, default=0)
    current_sign_in_on = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    current_sign_in_ip = db.Column(db.String(24)) 
    last_sign_in_on = db.Column(db.DateTime(), default=datetime.datetime.utcnow)
    last_sign_in_ip = db.Column(db.String(24)) 

    @property
    def password(self):
        raise AttributeError('Password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.hash_password = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.hash_password, password)

    def is_active(self):
        return self.active

    def track_user_activities(self, ip_address):
        self.sign_in_count = +1

        self.last_sign_in_on = self.current_sign_in_on
        self.last_sign_in_ip = self.current_sign_in_ip

        self.current_sign_in_ip = ip_address
        self.current_sign_in_on = datetime.datetime.utcnow

        return True

    def generate_token(self, expiration=3600):
        s = TimedJSONWebSignatureSerializer('current_app.config["SECRET_KEY"]', expires_in=expiration)
        return s.dumps({"user_id": self.id})

    def verify_token(self,token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False

        if data.get('user_id') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def generate_reset_token(self):
        s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'])
        return s.dumps({'user_id': self.user.id})

    @staticmethod
    def confirm_reset_token(token):
        s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False

        user = User.query.get(data.get('user_id'))

        return user
miguelgrinberg commented 3 years ago

The error message that you provided is incomplete. Please indicate the complete error, including stack trace and any other information printed to the console.

Makeem49 commented 3 years ago

Traceback (most recent call last): File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\app.py", line 2464, in call return self.wsgi_app(environ, start_response) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\app.py", line 2458, in wsgi_app ctx.auto_pop(error) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\ctx.py", line 452, in auto_pop self.pop(exc) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\ctx.py", line 438, in pop app_ctx.pop(exc) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\ctx.py", line 238, in pop self.app.do_teardown_appcontext(exc) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask\app.py", line 2321, in do_teardown_appcontext func(exc) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\flask_sqlalchemy__init__.py", line 858, in shutdown_session self.session.commit() File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\scoping.py", line 163, in do return getattr(self.registry(), name)(*args, **kwargs) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 1046, in commit self.transaction.commit() File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 504, in commit self._prepare_impl() File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 483, in _prepare_impl self.session.flush() File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 2540, in flush self._flush(objects) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 2682, in _flush transaction.rollback(_capture_exception=True) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in exit with_traceback=exctb, File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise raise exception File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\session.py", line 2642, in _flush flush_context.execute() File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 422, in execute rec.execute(self) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 589, in execute uow, File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\persistence.py", line 236, in save_obj update, File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\orm\persistence.py", line 995, in _emit_update_statements statement, multiparams File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\base.py", line 1011, in execute return meth(self, multiparams, params) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\sql\elements.py", line 298, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\base.py", line 1130, in _execute_clauseelement distilled_params, File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\base.py", line 1317, in _execute_context e, statement, parameters, cursor, context File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\base.py", line 1511, in _handle_dbapi_exception sqlalchemy_exception, with_traceback=excinfo[2], from=e File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_ raise exception File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\base.py", line 1277, in _execute_context cursor, statement, parameters, context File "C:\Users\Makeem\Desktop\snake-app-restructuring\env\lib\site-packages\sqlalchemy\engine\default.py", line 608, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'builtin_function_or_method' [SQL: UPDATE users SET sign_in_count=%(sign_in_count)s, current_sign_in_on=%(current_sign_in_on)s, current_sign_in_ip=%(current_sign_in_ip)s WHERE users.id = %(users_id)s] [parameters: {'sign_in_count': 1, 'current_sign_in_on': <built-in method utcnow of type object at 0x00007FFCBE9FD6C0>, 'current_sign_in_ip': '127.0.0.1', 'users_id': 4}] (Background on this error at: http://sqlalche.me/e/13/f405) 127.0.0.1 - - [21/Feb/2021 09:42:32] "POST /login HTTP/1.1" 200 - 127.0.0.1 - - [21/Feb/2021 09:48:58] "POST /login HTTP/1.1" 500 -

miguelgrinberg commented 3 years ago

I think this line:

self.current_sign_in_on = datetime.datetime.utcnow

should be:

self.current_sign_in_on = datetime.datetime.utcnow()
Makeem49 commented 3 years ago

Thanks Miguel, it worked.

On Sun, Feb 21, 2021 at 10:59 AM Miguel Grinberg notifications@github.com wrote:

I think this line:

self.current_sign_in_on = datetime.datetime.utcnow

should be:

self.current_sign_in_on = datetime.datetime.utcnow()

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/miguelgrinberg/flasky/issues/502#issuecomment-782880347, or unsubscribe https://github.com/notifications/unsubscribe-auth/AOHHQSM7D32VHGKFZI6AXWDTAEUV5ANCNFSM4X7B6PZQ .