ich werde so langsam kirre. Ich wollte mir auf die Schnelle einen Quelltext-Schnipsel basteln. Zu Testzwecke wollte zunächst eine *.txt-Datei einlesen und diesen Inhalt in eine SQLite-Datenbank speichern. Es sei angemerkt, dass es Städte gibt, die Umlaute verwenden. Dies habe ich auch berücksichtigt. Aber aus dem schnellen Basteln wurde mal wieder eine ewige Grübelei.
Im nachfolgenden Quellcode sehen wir, dass ich in der populate_database()-Funktion die bytes()-Funktion auf die einzelnen Elemente anwende, in der Hoffnung einen Bytestring erzeugen zu können. Des Weiteren habe ich in der build_engine()-Funktion die berüchtigte text_factory = str auf das engine-Objekt angewendet. Nichts hilft. Weiter unten seht ihr den kompletten TraceBack.
Ich habe die *.txt-Datei hochgeladen. Dafür habe ich extra eine Repository bei BitBucket eingerichtet. Dort könnt ihr die *.txt-Datei herunterladen und es selbst texten.
Code: Alles auswählen
#!/usr/bin/python
# -*- coding: utf-8 -*-
from os import path
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, Text, String, Date, DECIMAL, ForeignKey
from sqlalchemy import Index
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
# setting up root class for declarative declaration
Base = declarative_base()
metadata = Base.metadata
session_factory = sessionmaker()
ScopedSession = scoped_session(session_factory)
class GeneralRegion(Base):
__tablename__ = "general_region"
id = Column(Integer, primary_key = True, unique = True, autoincrement = True)
region = Column(String(100), nullable = False, unique = True)
def populate_database(file_path = None, mode = 'r'):
with open(file_path, mode) as f:
for element in f:
data = GeneralRegion(region = bytes(element))
ScopedSession.add(data)
ScopedSession.commit()
ScopedSession.close()
return
def build_engine(dbms = None, db_driver = None, sqlite_path = None):
engine = create_engine('{dbms}+{db_driver}:///{file_path}'.format(
dbms = 'sqlite',
db_driver = u'pysqlite',
file_path = sqlite_path,
encoding = 'utf8',
echo = True))
engine.connect().connection.connection.text_factory = str
# We should bind engine to your model.
ScopedSession.configure(bind=engine)
return
def main():
dbms = raw_input('Enter dbms (e.g. sqlite): ')
if dbms == 'sqlite':
sqlite_path = raw_input('Enter path to sqlite file: ')
db_driver = 'pysqlite'
file_path = raw_input('Enter path to to txt-file: ')
build_engine(dbms = dbms, db_driver = db_driver, sqlite_path = sqlite_path)
populate_database(file_path = file_path)
return
if __name__ == "__main__":
main()
Traceback (most recent call last):
File "C:\Users\Sophus\Desktop\line_by_line.py", line 98, in <module>
main()
File "C:\Users\Sophus\Desktop\line_by_line.py", line 93, in main
populate_database(file_path = file_path)
File "C:\Users\Sophus\Desktop\line_by_line.py", line 61, in populate_database
ScopedSession.commit()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 906, in commit
self.transaction.commit()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 461, in commit
self._prepare_impl()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 441, in _prepare_impl
self.session.flush()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 2171, in flush
self._flush(objects)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 2291, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Python27\lib\site-packages\sqlalchemy\util\langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\session.py", line 2255, in _flush
flush_context.execute()
File "C:\Python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 389, in execute
rec.execute(self)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 548, in execute
uow
File "C:\Python27\lib\site-packages\sqlalchemy\orm\persistence.py", line 181, in save_obj
mapper, table, insert)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\persistence.py", line 835, in _emit_insert_statements
execute(statement, params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 945, in execute
return meth(self, multiparams, params)
File "C:\Python27\lib\site-packages\sqlalchemy\sql\elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1189, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1402, in _handle_dbapi_exception
exc_info
File "C:\Python27\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context
context)
File "C:\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute
cursor.execute(statement, parameters)
ProgrammingError: (sqlite3.ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. [SQL: u'INSERT INTO general_region (region) VALUES (?)'] [parameters: ('Aasb\xfcttel\n',)]