SQLAlchemy Automap not loading table

2024/10/8 0:27:18

I am using SQLAlchemy version 2.0.19 (latest public release).

I am trying to map existing tables as documented in https://docs.sqlalchemy.org/en/20/orm/extensions/automap.html#basic-use

I created a SQLite table called user:

sqlite3 /tmp/mydatabase.db
SQLite version 3.39.5 2022-10-14 20:58:05
Enter ".help" for usage hints.
sqlite> 
sqlite> .schema user
CREATE TABLE user (id int, a int);
sqlite> 

I am trying to automap this table using SQLAlchemy but the table is not available in Base.classes as documented:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engineBase = automap_base()# engine
engine = create_engine("sqlite:////tmp/mydatabase.db")# reflect the tables
Base.prepare(autoload_with=engine)print(Base.classes.keys())# mapped classes are now created with names by default
# matching that of the table name.
User = Base.classes.user

print(Base.classes.keys()) returns [].

User = Base.classes.user shows the table not mapped:

Traceback (most recent call last):File "/***/venv/lib/python3.10/site-packages/sqlalchemy/util/_collections.py", line 186, in __getattr__return self._data[key]
KeyError: 'user'During handling of the above exception, another exception occurred:Traceback (most recent call last):File "/***/test.py", line 17, in <module>User = Base.classes.userFile "/***/venv/lib/python3.10/site-packages/sqlalchemy/util/_collections.py", line 188, in __getattr__raise AttributeError(key)
AttributeError: user

I am a little confused because the example is pretty straightforward and nonetheless it does not appear to work.

Answer

For SQLAlchemy's reflection to detect the table, the table needs to have a primary key.

CREATE TABLE user (id INT PRIMARY KEY, -- modify this!a INT
);

Running reflection with Automap:

from sqlalchemy import create_engine
from sqlalchemy.ext.automap import AutomapBase, automap_baseengine = create_engine(DATABASE_URL) # note: 4 slashes for an absolute path "////"
Base = automap_base()
Base.prepare(autoload_with=engine)
print("keys", Base.classes.keys())

Will give us:

keys ['user']
https://en.xdnf.cn/q/118755.html

Related Q&A

Create a base 12 calculator with different limits at diferent digits with python

I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits.Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,"A","B&q…

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: ")) x=0 y=0 z=0while(n>0):x=n%10y=x**3z=z+yn=n//10print (z) #The z here is the same value which I enter, yet it doesnt work. #If I enter 407 as n, z becomes (4…

Python(Scrapy) unpredictable mistake with import load_entry_point

I have such problem, I did nothing with Python or Scrapy, but when I started today my computer I got such error. I have found many different posts and tried some tips and advices, unfortunately, they a…

Debugging RadioButtons program in Python

from Tkinter import *class Application (Frame):def __init__(self, master):Frame.__init__(self, master)self.grid()self.create_widgets()def create_widgets(self):Label(self, text = "Select the last b…

Why am I getting an Internal Server error

My python script runs just fine on the Apache server locally set up on my computer, however, on importing the json2html library I am getting an internal server errorThe moment I comment the import stat…

Save pixel data in txt format in PIL

My program is to extract the pixel from an image and to save the pixel data in the text file for analysis. My picture is a binary image that gives only 255 and 0 sHere is the program:from PIL import Im…

ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value

Ive been given the python script where matplotlib is used , when running the script it opens the window and display graph. its working perfectly on my laptop. But this error occurs when I upload the fi…

Python win32com Outlook Stores not iterable

Trying to list all Outllook stores (and finally all e-mails in those stores):import win32com.clientoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") sto…

Using a users input to search dictionary keys and print that keys matching value

I am working with tkinter, as I have my gui set up with and entry, label, and button. Im trying to search my dictionarys keys with the users input from the entry, and print the value of the key that wa…

How to write CSV into the next column

I have output that I can write into a CSV. However, because of how i setup my XML to text, the output iterates itself incorrectly. Ive tried a lot to fix my XML output, but I dont see any way to fix it…