I am trying to populate my database with puppypopulator.py provided in the lesson. But the problem that I am facing is when I am querying it against a session in the shell to check if I have correctly populated my database but to my disconcert I find this error:-
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more in formation.
>>> from sqlalchemy import create_engine
>>> from sqlalchemy.orm import sessionmaker
>>> from database_setup_puppy import Base, Puppy, Shelter
>>> engine = create_engine('sqlite:///puppies.db
File "<stdin>", line 1
engine = create_engine('sqlite:///puppies.db
^
SyntaxError: EOL while scanning string literal
>>> engine = create_engine('sqlite:///puppies.db')
>>> Base.metadata.bind = engine
>>> DBSession = sessionmaker(bind = engine)
>>> session = DBSession()
>>> session.query(Puppy).all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2703, in all
return list(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2855, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2878, in _execute_and_instances
result = conn.execute(querycontext.statement, self._para ms)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sq l/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multipara ms, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1189, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/ut il/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cau se)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: puppy.dateOfBirth [SQL: u'SELECT puppy.id AS puppy_id, puppy.name AS puppy_name, puppy.gender AS puppy_g ender, puppy."dateOfBirth" AS "puppy_dateOfBirth", puppy.pic ture AS puppy_picture, puppy.shelter_id AS puppy_shelter_id, puppy.weight AS puppy_weight \nFROM puppy']
>>> session.query(Shelter).all()
[]
>>> session.query(Puppy).all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2703, in all
return list(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2855, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/or m/query.py", line 2878, in _execute_and_instances
result = conn.execute(querycontext.statement, self._para ms)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sq l/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multipara ms, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1189, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/ut il/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cau se)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/en gine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: puppy.dateOfBirth [SQL: u'SELECT puppy.id AS puppy_id, puppy.name AS puppy_name, puppy.gender AS puppy_g ender, puppy."dateOfBirth" AS "puppy_dateOfBirth", puppy.pic ture AS puppy_picture, puppy.shelter_id AS puppy_shelter_id, puppy.weight AS puppy_weight \nFROM puppy']
>>>
My Code for database_setup_puppy.py as used in the above shell import is this :-
from sqlalchemy import Column, ForeignKey, Integer, String, Date, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Shelter(Base):
__tablename__ = 'shelter'
id = Column(Integer, primary_key = True)
name =Column(String(80), nullable = False)
address = Column(String(250))
city = Column(String(80))
state = Column(String(20))
zipCode = Column(String(10))
website = Column(String)
class Puppy(Base):
__tablename__ = 'puppy'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
gender = Column(String(6), nullable = False)
dateOfBirth = Column(Date)
picture = Column(String)
shelter_id = Column(Integer, ForeignKey('shelter.id'))
shelter = relationship(Shelter)
weight = Column(Numeric(10))
And the puppy populator module is this :-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from puppies import Base, Shelter, Puppy
#from flask.ext.sqlalchemy import SQLAlchemy
from random import randint
import datetime
import random
engine = create_engine('sqlite:///puppyshelter.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
#Add Shelters
shelter1 = Shelter(name = "Oakland Animal Services", address = "1101 29th Ave", city = "Oakland", state = "California", zipCode = "94601", website = "oaklandanimalservices.org")
session.add(shelter1)
shelter2 = Shelter(name = "San Francisco SPCA Mission Adoption Center", address="250 Florida St", city="San Francisco", state="California", zipCode = "94103", website = "sfspca.org")
session.add(shelter2)
shelter3 = Shelter(name = "Wonder Dog Rescue", address= "2926 16th Street", city = "San Francisco", state = "California" , zipCode = "94103", website = "http://wonderdogrescue.org")
session.add(shelter3)
shelter4 = Shelter(name = "Humane Society of Alameda", address = "PO Box 1571" ,city = "Alameda" ,state = "California", zipCode = "94501", website = "hsalameda.org")
session.add(shelter4)
shelter5 = Shelter(name = "Palo Alto Humane Society" ,address = "1149 Chestnut St." ,city = "Menlo Park", state = "California" ,zipCode = "94025", website = "paloaltohumane.org")
session.add(shelter5)
#Add Puppies
male_names = ["Bailey", "Max", "Charlie", "Buddy","Rocky","Jake", "Jack", "Toby", "Cody", "Buster", "Duke", "Cooper", "Riley", "Harley", "Bear", "Tucker", "Murphy", "Lucky", "Oliver", "Sam", "Oscar", "Teddy", "Winston", "Sammy", "Rusty", "Shadow", "Gizmo", "Bentley", "Zeus", "Jackson", "Baxter", "Bandit", "Gus", "Samson", "Milo", "Rudy", "Louie", "Hunter", "Casey", "Rocco", "Sparky", "Joey", "Bruno", "Beau", "Dakota", "Maximus", "Romeo", "Boomer", "Luke", "Henry"]
female_names = ['Bella', 'Lucy', 'Molly', 'Daisy', 'Maggie', 'Sophie', 'Sadie', 'Chloe', 'Bailey', 'Lola', 'Zoe', 'Abby', 'Ginger', 'Roxy', 'Gracie', 'Coco', 'Sasha', 'Lily', 'Angel', 'Princess','Emma', 'Annie', 'Rosie', 'Ruby', 'Lady', 'Missy', 'Lilly', 'Mia', 'Katie', 'Zoey', 'Madison', 'Stella', 'Penny', 'Belle', 'Casey', 'Samantha', 'Holly', 'Lexi', 'Lulu', 'Brandy', 'Jasmine', 'Shelby', 'Sandy', 'Roxie', 'Pepper', 'Heidi', 'Luna', 'Dixie', 'Honey', 'Dakota']
puppy_images = ["http://pixabay.com/get/da0c8c7e4aa09ba3a353/1433170694/dog-785193_1280.jpg?direct", "http://pixabay.com/get/6540c0052781e8d21783/1433170742/dog-280332_1280.jpg?direct","http://pixabay.com/get/8f62ce526ed56cd16e57/1433170768/pug-690566_1280.jpg?direct","http://pixabay.com/get/be6ebb661e44f929e04e/1433170798/pet-423398_1280.jpg?direct","http://pixabay.com/static/uploads/photo/2010/12/13/10/20/beagle-puppy-2681_640.jpg","http://pixabay.com/get/4b1799cb4e3f03684b69/1433170894/dog-589002_1280.jpg?direct","http://pixabay.com/get/3157a0395f9959b7a000/1433170921/puppy-384647_1280.jpg?direct","http://pixabay.com/get/2a11ff73f38324166ac6/1433170950/puppy-742620_1280.jpg?direct","http://pixabay.com/get/7dcd78e779f8110ca876/1433170979/dog-710013_1280.jpg?direct","http://pixabay.com/get/31d494632fa1c64a7225/1433171005/dog-668940_1280.jpg?direct"]
#This method will make a random age for each puppy between 0-18 months(approx.) old from the day the algorithm was run.
def CreateRandomAge():
today = datetime.date.today()
days_old = randint(0,540)
birthday = today - datetime.timedelta(days = days_old)
return birthday
#This method will create a random weight between 1.0-40.0 pounds (or whatever unit of measure you prefer)
def CreateRandomWeight():
return random.uniform(1.0, 40.0)
for i,x in enumerate(male_names):
new_puppy = Puppy(name = x, gender = "male", dateOfBirth = CreateRandomAge(),picture=random.choice(puppy_images) ,shelter_id=randint(1,5), weight= CreateRandomWeight())
session.add(new_puppy)
session.commit()
for i,x in enumerate(female_names):
new_puppy = Puppy(name = x, gender = "female", dateOfBirth = CreateRandomAge(),picture=random.choice(puppy_images),shelter_id=randint(1,5), weight= CreateRandomWeight())
session.add(new_puppy)
session.commit()
I am new to the programming world and all this is very unusually tough for me. I just cannot find where I am going wrong. Thank You for your time going through such long codes. Any help is deeply appreciated.
Related
I'm currently using mysqlalchemy, kivy, installer and main to take user input from a GUI and store it in an sql database. When trying to add data from my 'adding_data_for people'. This error occurs. I know the error is not in kivy but I bet it has something to do with the installer. Also I just want to store the data, nothing else. Sorry for the long and messy code pieces in advance.
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
File "/usr/lib/python3.6/site-packages/mysql/connector/cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python3.6/site-packages/mysql/connector/connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python3.6/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1364 (HY000): Field 'school_id' doesn't have a default value
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/cse/git/soft_161_homework/milestone_1/main.py", line 215, in <module>
app.run()
File "/usr/lib64/python3.6/site-packages/kivy/app.py", line 855, in run
runTouchApp()
File "/usr/lib64/python3.6/site-packages/kivy/base.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "/usr/lib64/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 747, in mainloop
self._mainloop()
File "/usr/lib64/python3.6/site-packages/kivy/core/window/window_sdl2.py", line 479, in _mainloop
EventLoop.idle()
File "/usr/lib64/python3.6/site-packages/kivy/base.py", line 342, in idle
self.dispatch_input()
File "/usr/lib64/python3.6/site-packages/kivy/base.py", line 327, in dispatch_input
post_dispatch_input(*pop(0))
File "/usr/lib64/python3.6/site-packages/kivy/base.py", line 233, in post_dispatch_input
listener.dispatch('on_motion', etype, me)
File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "/usr/lib64/python3.6/site-packages/kivy/core/window/__init__.py", line 1402, in on_motion
self.dispatch('on_touch_down', me)
File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "/usr/lib64/python3.6/site-packages/kivy/core/window/__init__.py", line 1418, in on_touch_down
if w.dispatch('on_touch_down', touch):
File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "/usr/lib64/python3.6/site-packages/kivy/uix/screenmanager.py", line 1191, in on_touch_down
return super(ScreenManager, self).on_touch_down(touch)
File "/usr/lib64/python3.6/site-packages/kivy/uix/widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "/usr/lib64/python3.6/site-packages/kivy/uix/relativelayout.py", line 288, in on_touch_down
ret = super(RelativeLayout, self).on_touch_down(touch)
File "/usr/lib64/python3.6/site-packages/kivy/uix/widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "/usr/lib64/python3.6/site-packages/kivy/uix/behaviors/button.py", line 151, in on_touch_down
self.dispatch('on_press')
File "kivy/_event.pyx", line 703, in kivy._event.EventDispatcher.dispatch
File "kivy/_event.pyx", line 1214, in kivy._event.EventObservers.dispatch
File "kivy/_event.pyx", line 1098, in kivy._event.EventObservers._dispatch
File "/usr/lib64/python3.6/site-packages/kivy/lang/builder.py", line 64, in custom_callback
exec(__kvlang__.co_value, idmap)
File "/home/cse/git/soft_161_homework/milestone_1/schooltracking.kv", line 525, in <module>
app.adding_data_for_people()
File "/home/cse/git/soft_161_homework/milestone_1/main.py", line 184, in adding_data_for_people
session.commit()
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 1036, in commit
self.transaction.commit()
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 503, in commit
self._prepare_impl()
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 482, in _prepare_impl
self.session.flush()
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 2479, in flush
self._flush(objects)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 2617, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/util/compat.py", line 153, in reraise
raise value
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/session.py", line 2577, in _flush
flush_context.execute()
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 245, in save_obj
insert,
File "/usr/lib64/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 1137, in _emit_insert_statements
statement, params
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 982, in execute
return meth(self, multiparams, params)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1101, in _execute_clauseelement
distilled_params,
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1250, in _execute_context
e, statement, parameters, cursor, context
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1476, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
File "/usr/lib/python3.6/site-packages/mysql/connector/cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python3.6/site-packages/mysql/connector/connection.py", line 488, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python3.6/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 1364 (HY000): Field 'school_id' doesn't have a default value
[SQL: INSERT INTO person (home_id, name, grade_level) VALUES (%(home_id)s, %(name)s, %(grade_level)s)]
[parameters: {'home_id': 1, 'name': 'qwd', 'grade_level': 8}]
(Background on this error at: http://sqlalche.me/e/4xp6)
main.py
from kivy.app import App
from kivy.uix.label import Label
from kivy.modules import inspector # For inspection
from kivy.core.window import Window # For inspection
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from sys import stderr
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.exc import ProgrammingError
from schooltracking import SchoolTrackingDatabase, School, Home, Person
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from sqlalchemy.orm import sessionmaker
class SchoolTrackingApp(App):
def build(self):
inspector.create_inspector(Window, self)
def __init__(self, **kwargs):
super(SchoolTrackingApp, self).__init__(**kwargs)
url = SchoolTrackingDatabase.construct_mysql_url('localhost', 3306, 'schooltracking', 'root', 'cse')
self.schooltracking = SchoolTrackingDatabase(url)
self.session = self.schooltracking.create_session()
def database_entries(self):
query = self.session.query(School.names).all()
query2 = self.session.query(School.district).all()
text = self.root.ids.input_screen.text
text2 = self.root.ids.input_screen2.text
list_name = []
for i in query:
list_name.append(i[0])
list_district = []
for i in query2:
list_district.append(i[0])
for names in list_name:
if text == names:
for districts in list_district:
if text2 == districts:
popup = Popup(title='School and District already in database',
content=Label(text=' Sorry, but it looks like that name and \ndistrict are already in our datbase. \nPlease create a new one.'),
size_hint=(None, None), size=(400, 400))
popup.open()
break
def blank_entries(self):
text = self.root.ids.input_screen.text
text2 = self.root.ids.input_screen2.text
text3 = self.root.ids.input_screen3.text
text4 = self.root.ids.input_screen4.text
text5 = self.root.ids.input_screen5.text
text6 = self.root.ids.input_screen6.text
text7 = self.root.ids.input_screen7.text
text8 = self.root.ids.input_screen8.text
text9 = self.root.ids.input_screen9.text
text10 = self.root.ids.input_screen10.text
text11 = self.root.ids.input_screen.text
text12 = self.root.ids.input_screen2.text
text13 = self.root.ids.input_screen3.text
text14 = self.root.ids.input_screen4.text
text15 = self.root.ids.input_screen5.text
text16 = self.root.ids.input_screen5.text
text17 = self.root.ids.input_screen6.text
text18 = self.root.ids.input_screen7.text
text19 = self.root.ids.input_screen8.text
text20 = self.root.ids.input_screen8.text
text21 = self.root.ids.input_screen.text
text22 = self.root.ids.input_screen2.text
text23 = self.root.ids.input_screen3.text
text24 = self.root.ids.input_screen4.text
text25 = self.root.ids.input_screen4.text
if text or text2 or text3 or text4 or text5 or text6 or text7 or text8 or text9 or text10 or text11 or text12 or text13 or text14 or text15 or text16 or text17 or text18 or text19 or text20 or text21 or text22 or text23 or text24 or text25== '':
popup = Popup(title='No input given',
content=Label(text=' The text boxes cannot be left blank!'),
size_hint=(None, None), size=(400, 400))
popup.open()
def NA_entry(self):
text9 = self.root.ids.input_screen9.text
if text9 != 'N/A':
popup = Popup(title='Not N/A',
content=Label(text=' The text box has to be N/A!'),
size_hint=(None, None), size=(400, 400))
popup.open()
def check_no_school_represents_child(self):
query3 = self.session.query(Person.grade_level).all()
query4 = self.session.query(Person.name).all()
text10 = self.root.ids.input_screen10.text
list_grade_levels = []
for i in query3:
list_grade_levels.append(i[0])
list_names = []
for i in query4:
list_names.append(i[0])
for names in list_names:
for grade_level in list_grade_levels:
if grade_level == None:
popup = Popup(title='No school representing child',
content=Label(text=' There is no school representing ' + names + ' in this home'),
size_hint=(None, None), size=(400, 400))
popup.open()
break
def adding_data_for_school(self):
url = SchoolTrackingDatabase.construct_mysql_url('localhost', 3306, 'schooltracking', 'root', 'cse')
schooltracking = SchoolTrackingDatabase(url)
schooltracking.ensure_tables_exist()
session = schooltracking.create_session()
add_data(session)
session.commit()
text = self.root.ids.input_screen.text
text2 = self.root.ids.input_screen2.text
text3 = self.root.ids.input_screen3.text
schools = School(names=text, district=text2, education_level=text3)
session.add(schools)
session.commit()
def adding_data_for_home(self):
url = SchoolTrackingDatabase.construct_mysql_url('localhost', 3306, 'schooltracking', 'root', 'cse')
schooltracking = SchoolTrackingDatabase(url)
schooltracking.ensure_tables_exist()
session = schooltracking.create_session()
add_data(session)
session.commit()
text4 = self.root.ids.input_screen4.text
text20 = self.root.ids.input_screen20.text
text21 = self.root.ids.input_screen21.text
text22 = self.root.ids.input_screen22.text
text23 = self.root.ids.input_screen23.text
text24 = self.root.ids.input_screen24.text
address = Home(school_id=1,first_address=text4, second_address=text20, city=text21, state_or_province=text22, postal_code=68118, country=text24)
session.add(address)
session.commit()
def adding_data_for_people(self):
url = SchoolTrackingDatabase.construct_mysql_url('localhost', 3306, 'schooltracking', 'root', 'cse')
schooltracking = SchoolTrackingDatabase(url)
schooltracking.ensure_tables_exist()
session = schooltracking.create_session()
add_data(session)
session.commit()
text5 = self.root.ids.input_screen5.text
text6 = self.root.ids.input_screen6.text
text7 = self.root.ids.input_screen7.text
text8 = self.root.ids.input_screen8.text
text9 = self.root.ids.input_screen9.text
person = Person(home_id=1, name=text5, grade_level=8)
session.add(person)
session.commit()
def add_data(session):
pass (This will add the data to the database do notneed to worry about this)
def main():
try:
url = SchoolTrackingDatabase.construct_mysql_url('localhost', 3306, 'schooltracking', 'root', 'cse')
schooltracking = SchoolTrackingDatabase(url)
schooltracking.ensure_tables_exist()
print('Tables created.')
session = schooltracking.create_session()
add_data(session)
session.commit()
print('Records created.')
print('Your database has been successfully created!')
except (SQLAlchemyError) as exception:
print('Database setup failed', file=stderr)
print(f'Cause: {exception}', file=stderr)
#if ProgrammingError:
#print('Your credentials are incorrect with those matching to the database.' )
exit(1)
if __name__ == '__main__':
main()
app = SchoolTrackingApp()
app.run()
Installer
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKfrom
sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
Persisted = declarative_base()
class School(Persisted):
__tablename__ = 'schools'
school_id = Column(Integer, primary_key=True)
names = Column(String(256), nullable=False)
district = Column(String(256), nullable=False)
education_level = Column(String(256), nullable=False)
homes = relationship('Home', uselist=True, back_populates='school')
class Home(Persisted):
__tablename__ = 'homes'
home_id = Column(Integer, primary_key=True)
school_id = Column(Integer, ForeignKey('schools.school_id', ondelete='CASCADE'), nullable=False)
first_address = Column(String(256), nullable=False)
second_address = Column(String(256), nullable=True)
city = Column(String(256), nullable=False)
state_or_province = Column(String(256), nullable=False)
postal_code = Column(String(256), nullable=False)
country = Column(String(256), nullable=False)
school = relationship('School', back_populates='homes')
person = relationship('Person', back_populates='homes')
class Person(Persisted):
__tablename__ = 'person'
person_id = Column(Integer, primary_key=True)
home_id = Column(Integer, ForeignKey('homes.home_id', ondelete='CASCADE'), nullable=False)
name = Column(String(256), nullable=False)
grade_level = Column(Integer, nullable=False)
homes = relationship('Home', back_populates='person')
class SchoolTrackingDatabase(object):
#staticmethod
def construct_mysql_url(authority, port, database, username, password):
return f'mysql+mysqlconnector://{username}:{password}#{authority}:{port}/{database}'
#staticmethod
def construct_in_memory_url():
return 'sqlite:///'
def __init__(self, url):
self.engine = create_engine(url) # an engine is like an endpoint, something to connect to
self.Session = sessionmaker() # create a class for connections to that endpoint / pylint:
disable=invalid-name
self.Session.configure(bind=self.engine) # associate the class with the endpoint
def ensure_tables_exist(self):
Persisted.metadata.create_all(self.engine) # create tables for all subclasses of Persisted
def create_session(self):
return self.Session() # create a new session, which is like a connection to the database
If the kivy file is needed please tell me :)
sqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 1364 (HY000): Field 'school_id' doesn't have a default value
[SQL: INSERT INTO person (home_id, name, grade_level) VALUES (%(home_id)s, %(name)s, %(grade_level)s)]
[parameters: {'home_id': 1, 'name': 'qwd', 'grade_level': 8}]
As the error says, you're trying to insert data in to a table without specifying school_id, which doesn't have a default value. You have two options:
When doing an insert, specify school_id.
Set a default value for school_id in the database.
I always get an excessive traceback error, when querying the database finds no result. Why does this query not simply return None?
userExpireDate = session.query(PayingUser.expireDate).filter(PayingUser.mail == mailaddress).first()
This gives this horror error message when the mailaddress can't be found:
Traceback (most recent call last):
File "/Volumes/Mac HD/Benutzer/oliver/PycharmProjects/ErsterTest/Praeprocessor.py", line 274, in <module>
main()
File "/Volumes/Mac HD/Benutzer/oliver/PycharmProjects/ErsterTest/Praeprocessor.py", line 263, in main
userExpireDate = checkUser(mail)
File "/Volumes/Mac HD/Benutzer/oliver/PycharmProjects/ErsterTest/Praeprocessor.py", line 57, in checkUser
userExpireDate = session.query(PayingUser.expireDate).filter(PayingUser.mail == sender).first()
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3240, in first
ret = list(self[0:1])
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3018, in __getitem__
return list(res)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3341, in __iter__
self.session._autoflush()
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1588, in _autoflush
util.raise_from_cause(e)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 153, in reraise
raise value
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1577, in _autoflush
self.flush()
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2470, in flush
self._flush(objects)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2608, in _flush
transaction.rollback(_capture_exception=True)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 153, in reraise
raise value
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2568, in _flush
flush_context.execute()
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 245, in save_obj
insert,
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 1137, in _emit_insert_statements
statement, params
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
distilled_params,
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
e, statement, parameters, cursor, context
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "/Volumes/Mac HD/Benutzer/oliver/ErsterTest/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely)
(sqlite3.OperationalError) no such table: mails
[SQL: INSERT INTO mails (sender, subject, received, answer, text, html, category, count, danger) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: ('anemailaddress#gmx.at', 'An subject', '2019-10-15 23:59:11.219968', 2, '\r\n\r\n> Anfang der weitergeleiteten Nachricht:\r\n>\r\n> Von: Name <anemailaddress#gmx.at>\r\n> Betreff: An subject (87 characters truncated) ... > Kopie: MrX <anemailaddress#gmx.at>\r\n> Antwort an: MrX <anemailaddress#gmx.at>\r\n>\r\n> Ein weiteres Mail\r\n\r\n', '<html><head><meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space ... (2865 characters truncated) ... ass=""></span></div><br class=""><div class=""><div class="">Ein weiteres Mail<br class=""></div></div></blockquote></div><br class=""></body></html>', '', 0, 0)]
(Background on this error at: http://sqlalche.me/e/e3q8)
Why?
Interestingly enough it gives no Error when I do this:
for userExpireDate in session.query(PayingUser.expireDate).filter(PayingUser.mail == sender):
But I'd like to detect if there was no result. And if I try it this way (I know that's not elegant but nevertheless):
i = 0
for userExpireDate in session.query(PayingUser.expireDate).filter(PayingUser.mail == sender):
i += 1
...
if i == 0:
print('No user in database')
then I again get a horribly long traceback error.
Here is the model definition in another file called: payingUser.py
from sqlalchemy import Column, String, Integer, DateTime
from base import Base
from datetime import datetime
class PayingUser(Base):
__tablename__ = 'payingUsers'
mailaddress = Column(String, primary_key=True, unique=True)
firstName = Column(String)
lastName = Column(String)
expireDate = Column(DateTime)
def __init__(self, mailaddress, firstName, lastName):
self.mailaddress = mailaddress
self.firstName = firstName
self.lastName = lastName
self.expireDate = datetime.now()
What's happening here? Can anybody help? Yes, I'm new to sqlalchemy.
There is another table that's not used in this query, but kind of seems to appear in the traceback.
from sqlalchemy import Column, String, Integer, DateTime, Text, Table
from datetime import datetime
from base import Base
class Mail(Base):
__tablename__ = 'mails'
mail_id = Column(Integer, primary_key=True)
sender = Column(String(100))
subject = Column(String)
received = Column(DateTime, nullable=True)
answer = Column(Integer)
text = Column(Text)
html = Column(Text)
def __init__(self):
self.sender = ''
self.subject = ''
self.received = 0
self.answer = 0
self.text = ''
self.html = ''
Thanks!!
I am an idiot!
The reason for my error was, that I had the model definitions in separated files and I imported one of them AFTER the create_all(engine) statement. So I practically did this:
from testingUser import TestingUser
Base.metadata.create_all(engine)
session = Session()
from mail import Mail
Making it correct solved all my problems.
from testingUser import TestingUser
from mail import Mail
Base.metadata.create_all(engine)
session = Session()
Me butthead!!! This took me 3 days. Arghh.
I have a Flask application with sqlalchemy in it. Running manage db init, manage db migrate and manage db upgrade worked perfectly. So the tables are created on db2 without any problems. When i try to do an insert, i get all kinds of errors.
Traceback (most recent call last):
File "*path*/lib/python3.6/site-packages/ibm_db_dbi.py", line 1258, in _execute_helper
return_value = ibm_db.execute(self.stmt_handler, parameters)
Exception: Binding Error:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
context)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_sa/ibm_db.py", line 107, in do_execute
cursor.execute(statement, parameters)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_dbi.py", line 1356, in execute
self._execute_helper(parameters)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_dbi.py", line 1268, in _execute_helper
raise self.messages[len(self.messages) - 1]
ibm_db_dbi.DatabaseError: ibm_db_dbi::DatabaseError: Binding Error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/flask_restplus/api.py", line 319, in wrapper
resp = resource(*args, **kwargs)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/flask/views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/flask_restplus/resource.py", line 44, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api/app/api.py", line 37, in get
snp.sensor_info()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api/app/network.py", line 123, in sensor_info
db_session.commit()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 943, in commit
self.transaction.commit()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 467, in commit
self._prepare_impl()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 447, in _prepare_impl
self.session.flush()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2254, in flush
self._flush(objects)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2380, in _flush
transaction.rollback(_capture_exception=True)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2344, in _flush
flush_context.execute()
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 391, in execute
rec.execute(self)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 556, in execute
uow
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 181, in save_obj
mapper, table, insert)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 830, in _emit_insert_statements
execute(statement, multiparams)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 948, in execute
return meth(self, multiparams, params)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
context)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
exc_info
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
context)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_sa/ibm_db.py", line 107, in do_execute
cursor.execute(statement, parameters)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_dbi.py", line 1356, in execute
self._execute_helper(parameters)
File "/Users/sebastianlindblom/Documents/GrowSmarter/metrolive-api-env/lib/python3.6/site-packages/ibm_db_dbi.py", line 1268, in _execute_helper
raise self.messages[len(self.messages) - 1]
sqlalchemy.exc.DatabaseError: (ibm_db_dbi.DatabaseError) ibm_db_dbi::DatabaseError: Binding Error: [SQL: 'INSERT INTO "schema"."table" (sensor_id, code, lat, lon, x, y) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: (2855, 30, 59.291658, 18.077241, 411.59730406100783, 769.5522643844229)] (Background on this error at: http://sqlalche.me/e/4xp6)
The model looks like:
class Sensor(Base):
__tablename__ = 'table'
__table_args__ = {'schema':'schema'}
sensor_id = db.Column(db.Integer, primary_key=True)
code = db.Column(db.Integer, unique=True, nullable=False)
lat = db.Column(db.Float, unique=True, nullable=False)
lon = db.Column(db.Float, unique=True, nullable=False)
x = db.Column(db.Float, unique=True, nullable=False)
y = db.Column(db.Float, unique=True, nullable=False)
def __repr__(self):
return '<Sensor %r, x=%r, y=%r>' % self.code % self.x % self.y
The insert code looks like:
from .models import Sensor
from .database import db_session
ins = Sensor(sensor_id = sensor_coords['sensor_code'][0],
code = sensor_coords['sensor'][0],
lat = sensor_coords['lat'][0],
lon = sensor_coords['long'][0],
x = sensor_coords['x'][0],
y = sensor_coords['y'][0])
db_session.add(ins)
db_session.commit()
Looking at the error message, this is how it's trying to bind the sql statement:
[SQL: 'INSERT INTO "schema"."table" (sensor_id, code, lat, lon, x, y) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: (2855, 30, 59.291658, 18.077241, 411.59730406100783, 769.5522643844229)]
which looks correct? (schema and table names are replaced).
My database.py looks like:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import ibm_db_sa
from app.api import app
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
Base.metadata.create_all(bind=engine)
I can't figure out whats wrong.. The insert format looks correct?
Appreciate all the help I can get. Thanks!
Got it to work!
Had to cast the types in the insert code as:
ins = Sensor(sensor_id = int(sensor_coords['sensor_code'][0]),
code = int(sensor_coords['sensor'][0]),
lat = float(sensor_coords['lat'][0]),
lon = float(sensor_coords['long'][0]),
x = float(sensor_coords['x'][0]),
y = float(sensor_coords['y'][0]))
Didn't realize numpy used its own int and float types...
I have the following models to describe my database schema:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
import sqlalchemy.dialects.mysql as mysql
Base = declarative_base()
class Country(Base):
__tablename__ = 'countries'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.TINYINT(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
competitions = relationship('Competition', backref='country')
class Competition(Base):
__tablename__ = 'competitions'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.INTEGER(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
country_id = Column(mysql.TINYINT(unsigned=True), ForeignKey('countries.id'))
teams = relationship('Team', backref("competition") )
class Team(Base):
__tablename__ = 'teams'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.INTEGER(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
competition_id = Column(mysql.INTEGER(unsigned=True), ForeignKey('competitions.id'), nullable=False)
and when I try to create a Team like:
team = Team()
I get the following traceback after the command above:
Traceback (most recent call last):
File "/home/giorgos/apps/Aptana_Studio_3/plugins/org.python.pydev_2.6.0.2012062121/pysrc/pydevd.py", line 1392, in <module>
debugger.run(setup['file'], None, None)
File "/home/giorgos/apps/Aptana_Studio_3/plugins/org.python.pydev_2.6.0.2012062121/pysrc/pydevd.py", line 1085, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "/home/giorgos/Documents/Aptana Studio 3 Workspace/BetPick/tests/insert_models.py", line 21, in <module>
team = Team()
File "<string>", line 2, in __init__
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 309, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 485, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 157, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/event.py", line 291, in __call__
fn(*args, **kw)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2342, in _event_on_first_init
configure_mappers()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2258, in configure_mappers
mapper._post_configure_properties()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1167, in _post_configure_properties
prop.init()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 128, in init
self.do_init()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 911, in do_init
self._determine_joins()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 1034, in _determine_joins
self.secondary)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 1028, in _search_for_join
a_subset=mapper.local_table)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/util.py", line 262, in join_condition
b.foreign_keys,
AttributeError: 'tuple' object has no attribute 'foreign_keys'
what I am doing wrong ?
backref should be a keyword argument in your declaration of Competition.teams:
class Competition(Base):
# ...
teams = relationship('Team', backref="competition")
See the documentation on relationship. You can use a backref callable to configure the back reference explicitly, but you'd have to still use the backref keyword:
class Competition(Base):
# ...
teams = relationship('Team', backref=backref("competition", ... additional keywords ...))
I'm trying to work my way through the example given in the sqlalchemy tutorial but I'm getting errors. As far as I can tell I'm following the example to the letter. Here's the code that I have from it so far. It fails when I .first() after I query the DB.
I'm on version 0.7.5 and python 2.7
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
engine.execute("select 1").scalar() # works fine
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
jeff_user = User("jeff", "Jeff", "foo")
session.add(jeff_user)
our_user = session.query(User).filter_by(name='jeff').first() # fails here
jeff_user.password = "foobar"
session.add_all([
User('wendy', 'Wendy Williams', 'foobar'),
User('mary', 'Mary Contrary', 'xxg527'),
User('fred', 'Fred Flinstone', 'blah')])
session.dirty # shows nothing as dirty
session.new # shows nothing as new
Here is the error message
2012-02-25 17:48:33,879 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
2012-02-25 17:48:33,886 INFO sqlalchemy.engine.base.Engine ('jeff', 'Jeff', 'foo')
2012-02-25 17:48:33,887 INFO sqlalchemy.engine.base.Engine ROLLBACK
Traceback (most recent call last):
File "learning_sql.py", line 35, in <module>
our_user = session.query(User).filter_by(name='ed').first() # fails here
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2024, in first
ret = list(self[0:1])
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1918, in __getitem__
return list(res)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2092, in __iter__
self.session._autoflush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 983, in _autoflush
self.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1559, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1630, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 331, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 475, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/mapper.py", line 2291, in _save_obj
execute(statement, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1405, in execute
params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1538, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1646, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1639, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 330, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (OperationalError) no such table: users u'INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)' ('jeff', 'Jeff', 'foo')
The expected print out is this
>>> our_user = session.query(User).filter_by(name='ed').first()
BEGIN (implicit)
INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
('ed', 'Ed Jones', 'edspassword')
SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password
FROM users
WHERE users.name = ?
LIMIT 1 OFFSET 0
('ed',)
>>> our_user
<User('ed','Ed Jones', 'edspassword')>
For some reason my code is causing a ROLLBACK when it should be SELECT.
You are getting this error because database is missing the table structure (you apparently missed this line in the tutorial, it's in the Declare Mapping subsection). Create the schema by adding following just after your table/model definitions:
Class User(Base)
...
# Initialize database schema (create tables)
Base.metadata.create_all(engine)