Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migration Value Error #336

Closed
nadermx opened this issue Mar 12, 2018 · 2 comments
Closed

Migration Value Error #336

nadermx opened this issue Mar 12, 2018 · 2 comments

Comments

@nadermx
Copy link

nadermx commented Mar 12, 2018

I'm trying to start a new project wit the migrations feature.

I currently have a models.py file that looks like such

# -*- coding: utf-8 -*-
from flask import current_app
from datetime import datetime
from pony.orm import *
from passlib.hash import bcrypt_sha256
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
from flask_login import UserMixin

db = Database()

class User(UserMixin, db.Entity):
    username = Optional(unicode, unique=True)
    password_hash = Optional(unicode)
    email = Required(unicode)
    dt_registered = Optional(datetime, default=datetime.utcnow())
    dt_last_visit = Optional(datetime, default=datetime.utcnow())
    verified = Optional(bool, default=False)
    failed_login = Optional(int)
    last_failed_login = Optional(datetime, default=datetime.now)
    questions = Set(lambda: Question)
    answers = Set(lambda: Answer)
    votes = Set(lambda: Vote)
    comments = Set(lambda: Comment)
    info = Optional(Json)
    favorites = Optional(lambda: Favorite)
    tags = Optional(lambda: Tag)
    reputation = Optional(lambda: Reputation)
    status = Optional(bool)
    moderator = Optional(unicode)

    def hash_password(self, password):
        self.password_hash = bcrypt_sha256.hash(password)

    def verify_password(self, password):
        return bcrypt_sha256.verify(password, self.password_hash)

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        if not data['id']:
            return None
        user = User[data['id']]
        return user

class Comment(db.Entity):
    user = Required(lambda: User)
    question = Optional(lambda: Question)
    answer = Optional(lambda: Answer)
    votes = Optional(lambda: Vote)

class Question(db.Entity):
    content = Optional(unicode)
    user = Required(lambda: User)
    views = Optional(int)
    comments = Set(lambda: Comment)
    answers = Set(lambda: Answer)
    votes = Set(lambda: Vote)

class Answer(db.Entity):
    votes = Set(lambda: Vote)
    user = Required(lambda: User)
    comments = Set(lambda: Comment)
    question = Optional(lambda: Question)
    correct = Optional(bool, default=False)

class Tag(db.Entity):
    user = Required(lambda: User)

class Vote(db.Entity):
    user = Required(lambda: User)
    answer = Optional(lambda: Answer)
    question = Optional(lambda: Question)
    comment = Optional(lambda: Comment)
    content = Optional(unicode)


class Reputation(db.Entity):
    user = Required(lambda: User)

class Favorite(db.Entity):
    user = Required(lambda: User)

sql_debug(False)

Then in my app.py I have the following (Noting that it's a new database so i don't need to run models.db.generate_mapping(allow_auto_upgrade=True) or models.db.generate_mapping(create_tables=True)?

app.config.from_object('config')
# set a global db session for the app
app.wsgi_app = models.db_session(app.wsgi_app)
models.db.bind(app.config['DB_PROVIDER'], **app.config['DB_CONFIG'])

This works when I run my app.py. But when I try and run the migrate.py file that I have set up as following

#!/usr/bin/env python
import models
import config

models.db.migrate(config.DB_PROVIDER, **config.DB_CONFIG)

note my config.py file has the following

DB_PROVIDER = 'sqlite'
DB_CONFIG = {
  'filename': 'db.sqlite',
  'create_db': True,
}

I run python migrate.py make and I get

Traceback (most recent call last):
  File "migrate.py", line 5, in <module>
    models.db.migrate(config.DB_PROVIDER, **config.DB_CONFIG)
  File "<string>", line 2, in migrate
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/utils/utils.py", line 58, in cut_traceback
    return func(*args, **kwargs)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/orm/core.py", line 682, in migrate
    return migrate(self, command)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/command.py", line 61, in migrate
    return _migrate(db, cmd, **kwargs)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/command.py", line 96, in _migrate
    return graph.make(db=db, empty=empty, custom=custom, description=name)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/migration.py", line 228, in make
    generated = MigrationWriter(leaves, None, db).as_string()
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/writer.py", line 347, in as_string
    body = self._get_define_entities_block(imports)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/writer.py", line 323, in _get_define_entities_block
    entities.append(serialize_entity_declaration(entity, imports=imports))
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/serializer.py", line 30, in serialize_entity_declaration
    return serializer.serialize_entity_declaration(entity)
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/serializer.py", line 148, in serialize_entity_declaration
    lines.append('%s = %s' % (name, self.serialize(value)))
  File "/home/john/.virtualenvs/ca/lib/python3.6/site-packages/pony/migrate/serializer.py", line 245, in serialize
    raise ValueError
ValueError
@kozlovsky
Copy link
Member

Thanks for reporting, should be fixed now

@jgirardet
Copy link

I had the same errors. I updated today with latest git version, andnow I have the same error message but with one line more :

Traceback (most recent call last):
  File "migrate2.py", line 19, in <module>
    db.migrate(**db_params, migration_dir='mapistar/migrations')
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/orm/core.py", line 684, in migrate
    return migrate(self, command)
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/command.py", line 61, in migrate
    return _migrate(db, cmd, **kwargs)
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/command.py", line 96, in _migrate
    return graph.make(db=db, empty=empty, custom=custom, description=name)
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/migration.py", line 228, in make
    generated = MigrationWriter(leaves, None, db).as_string()
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/writer.py", line 347, in as_string
    body = self._get_define_entities_block(imports)
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/writer.py", line 323, in _get_define_entities_block
    entities.append(serialize_entity_declaration(entity, imports=imports))
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/serializer.py", line 30, in serialize_entity_declaration
    return serializer.serialize_entity_declaration(entity)
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/serializer.py", line 149, in serialize_entity_declaration
    lines.append('%s = %s' % (name, self.serialize(value)))
  File "/home/jim/.local/share/virtualenvs/mapistar-u3z0Ka1e/src/pony/pony/migrate/serializer.py", line 246, in serialize
    raise TypeError(type(value))
TypeError: <class 'descriptors.classproperty'>

kozlovsky added a commit that referenced this issue Jul 23, 2018
# Major features

* Hybrid methods and properties added: https://docs.ponyorm.com/entities.html#hybrid-methods-and-properties
* Allow to base queries on another queries: `select(x.a for x in prev_query if x.b)`
* Added support of Python 3.7
* Added support of PyPy
* `group_concat()` aggregate function added
* pony.flask subpackage added for integration with Flask

# Other features

* `distinct` option added to aggregate functions
* Support of explicit casting to `float` and `bool` in queries

# Improvements

* Apply @cut_traceback decorator only when pony.MODE is 'INTERACTIVE'

# Bugfixes

* In SQLite3 `LIKE` is case sensitive now
* #249: Fix incorrect mixin used for Timedelta
* #251: correct dealing with qualified table names
* #301: Fix aggregation over JSON Column
* #306: Support of frozenset constants added
* #308: Fixed an error when assigning JSON attribute value to the same attribute: obj.json_attr = obj.json_attr
* #313: Fix missed retry on exception raised during db_session.__exit__
* #314: Fix AttributeError: 'NoneType' object has no attribute 'seeds'
* #315: Fix attribute lifting for JSON attributes
* #321: Fix KeyError on obj.delete()
* #325: duplicating percentage sign in raw SQL queries without parameters
* #331: Overriding __len__ in entity fails
* #336: entity declaration serialization
* #357: reconnect after PostgreSQL server closed the connection unexpectedly
* Fix Python implementation of between() function and rename arguments: between(a, x, y) -> between(x, a, b)
* Fix retry handling: in PostgreSQL and Oracle an error can be raised during commit
* Fix optimistic update checks for composite foreign keys
* Don't raise OptimisticCheckError if db_session is not optimistic
* Handling incorrect datetime values in MySQL
* Improved ImportError exception messages when MySQLdb, pymysql, psycopg2 or psycopg2cffi driver was not found
* desc() function fixed to allow reverse its effect by calling desc(desc(x))
* __contains__ method should check if objects belong to the same db_session
* Fix pony.MODE detection; mod_wsgi detection according to official doc
* A lot of inner fixes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants