mgaitan / mesas_ba

Relevamiento de mesas sospechosas
0 stars 0 forks source link

Cómo usar db.sqlite ? #1

Open dmascialino opened 7 years ago

dmascialino commented 7 years ago

Buenas, estuve tratando de usar la db.sqlite,

el primer problema que encontré es que el md5 no coincide con el que dice el nobtebook (0e5d3f0c92ba8d18fc19b7a3ed742266):

laila@laila-desktop:/tmp$ wget http://lab.nqnwebs.com/descargas/db.sqlite
--2017-08-17 22:53:14--  http://lab.nqnwebs.com/descargas/db.sqlite
Resolving lab.nqnwebs.com (lab.nqnwebs.com)... 69.163.155.223
....
laila@laila-desktop:/tmp$ md5sum db.sqlite 
d75d744b6ce1f40f3fa411f16938db2c  db.sqlite

Luego intenté ejecutar en un notebook: [1]: %load_ext django_orm_magic

pass
---------------------------------------------------------------------------
CommandError                              Traceback (most recent call last)
<ipython-input-3-1f388a4ef101> in <module>()
----> 1 get_ipython().run_cell_magic('django_orm', '', '\npass')

~/.virtualenvs/mesas/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2101             magic_arg_s = self.var_expand(line, stack_depth)
   2102             with self.builtin_trap:
-> 2103                 result = fn(magic_arg_s, cell)
   2104             return result
   2105 

<decorator-gen-125> in django_orm(self, line, cell)

~/.virtualenvs/mesas/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django_orm_magic.py in django_orm(self, line, cell)
     69         django.setup()
     70         call_command('makemigrations', 'orm_magic', verbosity=0, interactive=False)
---> 71         call_command('migrate', 'orm_magic', verbosity=0, interactive=False)
     72 
     73         try:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/__init__.py in call_command(command_name, *args, **options)
    128         defaults['skip_checks'] = True
    129 
--> 130     return command.execute(*args, **defaults)
    131 
    132 

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/base.py in execute(self, *args, **options)
    328             if self.requires_migrations_checks:
    329                 self.check_migrations()
--> 330             output = self.handle(*args, **options)
    331             if output:
    332                 if self.output_transaction:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/commands/migrate.py in handle(self, *args, **options)
    128             if app_label not in executor.loader.migrated_apps:
    129                 raise CommandError(
--> 130                     "App '%s' does not have migrations." % app_label
    131                 )
    132             targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]

CommandError: App 'orm_magic' does not have migrations.

Esa celda la ejecuta con pass pues al tratar de ejecutar la celda en la que se declaran los modelos obtengo:

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
     62             if params is None:
---> 63                 return self.cursor.execute(sql)
     64             else:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute(self, query, params)
    325         if params is None:
--> 326             return Database.Cursor.execute(self, query)
    327         query = self.convert_query(query)

OperationalError: table "orm_magic_circuito" already exists

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
<ipython-input-2-3406c425637d> in <module>()
----> 1 get_ipython().run_cell_magic('django_orm', '', 'from django.db import models\nfrom django.db.models import Sum\n\nclass Seccion(models.Model):\n    numero = models.CharField(max_length=10)\n    nombre = models.CharField(max_length=100)\n    \n    def __str__(self):\n        return f\'{self.numero} - {self.nombre}\'\n\nclass Circuito(models.Model):\n    numero = models.CharField(max_length=10)\n    seccion = models.ForeignKey(\'Seccion\')\n\n    def __str__(self):\n        return u"Circuito %s (%s)" % (self.numero, self.seccion)\n    \nclass Mesa(models.Model):\n    numero = models.CharField(max_length=10)\n    circuito = models.ForeignKey(\'Circuito\')\n    fake_id = models.CharField(max_length=100, unique=True)\n    url = models.CharField(max_length=200)\n    \n    class Meta:\n        unique_together = (\'circuito\', \'numero\')\n    \n    @property\n    def computados_sen(self):\n        return self.resultados.filter(categoria=\'sen\').aggregate(Sum(\'votos\'))[\'votos__sum\']\n    \n    @property\n    def computados_dip(self):\n        return self.resultados.filter(categoria=\'dip\').aggregate(Sum(\'votos\'))[\'votos__sum\']\n    \n    @property\n    def computados(self):\n        # aprox\n        return (self.computados_sen + self.computados_dip) // 2\n\n\n    def __str__(self):\n        return u"Mesa %s (%s)" % (self.numero, self.circuito)\n    \n    @property\n    def absolute_url(self):\n        return f\'http://www.resultados.gob.ar/99/resu/content/telegramas/{self.url}\'\n    \n\nclass Partido(models.Model):\n    nombre = models.CharField(max_length=100, unique=True)\n        \n    def __str__(self):\n        return self.nombre\n    \n    \nclass Opcion(models.Model):\n    nombre = models.CharField(max_length=100, unique=True)\n    partido = models.ForeignKey(\'Partido\', null=True)    # blanco / nulo / etc. \n    \n    def __str__(self):\n        return self.nombre\n    \nclass VotoMesa(models.Model):\n    mesa = models.ForeignKey(\'Mesa\', related_name=\'resultados\')\n    categoria = models.CharField(max_length=20, choices=((\'dip\', \'Diputados\'), (\'sen\', \'Senadores\')))\n    opcion = models.ForeignKey(\'Opcion\')\n    votos = models.IntegerField()\n    \n    def __str__(self):\n        return u"%s: %s -> %d" % (self.get_categoria_display(), self.opcion, self.votos)\n    \n    \n    class Meta:\n        unique_together = (\'mesa\', \'opcion\', \'categoria\')')

~/.virtualenvs/mesas/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2101             magic_arg_s = self.var_expand(line, stack_depth)
   2102             with self.builtin_trap:
-> 2103                 result = fn(magic_arg_s, cell)
   2104             return result
   2105 

<decorator-gen-125> in django_orm(self, line, cell)

~/.virtualenvs/mesas/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django_orm_magic.py in django_orm(self, line, cell)
     69         django.setup()
     70         call_command('makemigrations', 'orm_magic', verbosity=0, interactive=False)
---> 71         call_command('migrate', 'orm_magic', verbosity=0, interactive=False)
     72 
     73         try:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/__init__.py in call_command(command_name, *args, **options)
    128         defaults['skip_checks'] = True
    129 
--> 130     return command.execute(*args, **defaults)
    131 
    132 

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/base.py in execute(self, *args, **options)
    328             if self.requires_migrations_checks:
    329                 self.check_migrations()
--> 330             output = self.handle(*args, **options)
    331             if output:
    332                 if self.output_transaction:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/core/management/commands/migrate.py in handle(self, *args, **options)
    202         post_migrate_state = executor.migrate(
    203             targets, plan=plan, state=pre_migrate_state.clone(), fake=fake,
--> 204             fake_initial=fake_initial,
    205         )
    206         # post_migrate signals have access to all models. Ensure that all models

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/migrations/executor.py in migrate(self, targets, plan, state, fake, fake_initial)
    113                 # The resulting state should still include applied migrations.
    114                 state = self._create_project_state(with_applied_migrations=True)
--> 115             state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
    116         else:
    117             # No need to check for `elif all_backwards` here, as that condition

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/migrations/executor.py in _migrate_all_forwards(self, state, plan, full_plan, fake, fake_initial)
    143                     if self.progress_callback:
    144                         self.progress_callback("render_success")
--> 145                 state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
    146                 migrations_to_run.remove(migration)
    147 

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/migrations/executor.py in apply_migration(self, state, migration, fake, fake_initial)
    242                 # Alright, do it normally
    243                 with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
--> 244                     state = migration.apply(state, schema_editor)
    245         # For replacement migrations, record individual statuses
    246         if migration.replaces:

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/migrations/migration.py in apply(self, project_state, schema_editor, collect_sql)
    127             else:
    128                 # Normal behaviour
--> 129                 operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
    130         return project_state
    131 

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/migrations/operations/models.py in database_forwards(self, app_label, schema_editor, from_state, to_state)
     95         model = to_state.apps.get_model(app_label, self.name)
     96         if self.allow_migrate_model(schema_editor.connection.alias, model):
---> 97             schema_editor.create_model(model)
     98 
     99     def database_backwards(self, app_label, schema_editor, from_state, to_state):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/base/schema.py in create_model(self, model)
    301                 sql += ' ' + tablespace_sql
    302         # Prevent using [] as params, in the case a literal '%' is used in the definition
--> 303         self.execute(sql, params or None)
    304 
    305         # Add any field index and index_together's (deferred as SQLite3 _remake_table needs it)

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/base/schema.py in execute(self, sql, params)
    118         else:
    119             with self.connection.cursor() as cursor:
--> 120                 cursor.execute(sql, params)
    121 
    122     def quote_name(self, name):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
     63                 return self.cursor.execute(sql)
     64             else:
---> 65                 return self.cursor.execute(sql, params)
     66 
     67     def executemany(self, sql, param_list):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/utils.py in __exit__(self, exc_type, exc_value, traceback)
     92                 if dj_exc_type not in (DataError, IntegrityError):
     93                     self.wrapper.errors_occurred = True
---> 94                 six.reraise(dj_exc_type, dj_exc_value, traceback)
     95 
     96     def __call__(self, func):

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/utils/six.py in reraise(tp, value, tb)
    683             value = tp()
    684         if value.__traceback__ is not tb:
--> 685             raise value.with_traceback(tb)
    686         raise value
    687 

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params)
     61         with self.db.wrap_database_errors:
     62             if params is None:
---> 63                 return self.cursor.execute(sql)
     64             else:
     65                 return self.cursor.execute(sql, params)

~/.virtualenvs/mesas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute(self, query, params)
    324     def execute(self, query, params=None):
    325         if params is None:
--> 326             return Database.Cursor.execute(self, query)
    327         query = self.convert_query(query)
    328         return Database.Cursor.execute(self, query, params)

OperationalError: table "orm_magic_circuito" already exists

Entonces, no me queda claro como aprovechar la base de datos existente.

Gracias y un gran abrazo!

mgaitan commented 7 years ago

@dmascialino porfa, probá bajar la db de nuevo desde acá y ejecutar la celda que declara los modelos. y si no funca, decima tambien la version de django. estás probando con 1.11 ?

dmascialino commented 7 years ago

@mgaitan hoy pude sentarme de vuelta, db.sqlite devuelve 404

Un pip freeze en mi virtualenv:

Django==1.11.4
django-orm-magic==0.4
mgaitan commented 7 years ago

acá está http://lab.nqnwebs.com/descargas/mesas_ba/db.sqlite, soy un nabo importante.