asked on
/home/python/anaconda3/bin/python3.7 /home/python/Documents/int ro-to-data base/app.p y
Traceback (most recent call last):
File "/home/python/Documents/intro-to-dat abase/app. py", line 6, in <module>
my_user.save_to_db()
File "/home/python/Documents/intro-to-dat abase/user .py", line 18, in save_to_db
(self.email, self.first_name, self.last_name))
File "/home/python/Documents/intro-to-dat abase/data base.py", line 22, in __exit__
self.connection_pool.putconn(self.co nnection)
AttributeError: 'connectionFromPool' object has no attribute 'connection_pool'
from psycopg2 import pool
connection_pool = pool.SimpleConnectionPool(1,
1,
dbname="learning",
user="postgres",
password="postgres",
host="localhost",
port="5432")
class connectionFromPool:
def __init__(self):
self.connection = None
def __enter__(self):
self.connection = connection_pool.getconn()
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.commit()
self.connection_pool.putconn(self.connection)
===
from database import connectionFromPool
class User:
def __init__(self, first_name, email, last_name, id):
self.email = email
self.first_name = first_name
self.last_name = last_name
self.id = id
def __repr__(self):
return "<User {}>".format(self.email)
def save_to_db(self):
with connectionFromPool() as connection:
with connection.cursor() as cursor:
cursor.execute('INSERT INTO USERS(email,first_name,last_name) VALUES(%s,%s,%s)',
(self.email, self.first_name, self.last_name))
@classmethod
def load_from_db_by_email(cls, email):
with connectionFromPool() as connection:
with connection.cursor() as cursor:
cursor.execute('select * from users where email=%s', (email,))
user_data = cursor.fetchone()
return cls(user_data[1], user_data[2], user_data[3], user_data[0])
Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.
TRUSTED BY