-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres.py
More file actions
55 lines (39 loc) · 1.37 KB
/
postgres.py
File metadata and controls
55 lines (39 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import psycopg2
from sqlalchemy import create_engine
from scraper import to_write
# postgres table creation
# use this to run locally using python3 server.py
#conn_string = 'postgresql://postgres:postgres@localhost:5432/postgres'
conn = psycopg2.connect(database = 'postgres', user = 'postgres', password = 'postgres', host = 'postgres')
cursor = conn.cursor()
table_schema = """
DROP TABLE IF EXISTS properties;
CREATE TABLE properties (
index int PRIMARY KEY,
name VARCHAR (255),
photo VARCHAR (255));
"""
cursor.execute(table_schema)
conn.commit()
# insert the data
db = create_engine(conn_string)
conn = db.connect()
to_write.to_sql('properties', con=conn, if_exists='replace',index=False)
conn.close()
# Define a function to fetch data from the PostgreSQL database
def fetch_data_from_postgres():
try:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
# Change this query to match your table structure
query = "SELECT * FROM properties"
cursor.execute(query)
# Fetch all rows as a list of dictionaries
rows = cursor.fetchall()
data = [{'index': row[0], 'title': row[1], 'link': row[2]} for row in rows]
cursor.close()
conn.close()
return data
except psycopg2.Error as e:
print("Error connecting to PostgreSQL:", e)
return []