当运行命令docker-compose up时,我在日志Traceback(最后一次调用)中得到一条消息:test_assigned-print_data-1| test_assigned-print_data-1中的文件“/project/print_data.py”,第3行|connect = psycopg2.connect(test_assigned-print_data-1| ^^|文件“/usr/local/lib/python3.11/site-packages/psycopg 2/init.py”,第122行,连接test_assigned-print_data-1| conn = _connect(dsn,connection_factory=connection_factory,**kwasync)test_assigned-print_data-1| ^^|psycopg2.OperationalError:连接到服务器“localhost”(127.0.0.1),端口5432失败:连接拒绝test_assigned-print_data-1|服务器是否在该主机上运行并接受TCP/IP连接?test_assigned-print_data-1|连接到服务器“localhost”(::1),端口5432失败:无法分配请求的地址test_assigned-print_data-1|服务器是否在该主机上运行并接受TCP/IP连接?
Docker-compose文件
version: '3.9'
services:
db:
container_name: db
image: postgres:latest
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_HOST: localhost
get_data:
build: .
command: python3 get_data.py
depends_on:
- db
print_data:
build: .
command: python3 print_data.py
depends_on:
- db
字符串
Python文件
import psycopg2
connect = psycopg2.connect(
dbname="postgres",
user="postgres",
password="postgres",
host="localhost",
port="5432"
)
cur = connect.cursor()
# Execute an SQL query to aggregate the data by region
cur.execute("""
SELECT region,
SUM(population) AS total_population,
MAX(country) FILTER (WHERE population = max_pop) AS largest_country,
MAX(population) AS largest_population,
MIN(country) FILTER (WHERE population = min_pop) AS smallest_country,
MIN(population) AS smallest_population
FROM (
SELECT region, country, population,
MAX(population) OVER (PARTITION BY region) AS max_pop,
MIN(population) OVER (PARTITION BY region) AS min_pop
FROM population_data
) subquery
GROUP BY region
""")
# Fetch the results and print
results = cur.fetchall()
for row in results:
region, total_population, largest_country, largest_population, smallest_country, smallest_population = row
print(f"Region name{region}")
print(f"Total population: {total_population:,}")
print(f"Largest country: {largest_country:,}")
print(f"Population of a largest country{largest_population:,}")
print(f"Smallest country: {smallest_country:,}")
print(f"Population of a smallest country{smallest_population:,}")
型
我正在尝试更改端口,配置postgres. conf的“listening_address”行。尝试在MacOS上的终端中执行一些命令
1条答案
按热度按时间ifsvaxew1#
也许更改pg_hba.conf文件中的设置会对您有所帮助。
试试这样的改变:
字符串