File tree 4 files changed +69
-0
lines changed
4 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ services :
2
+ postgres_db :
3
+ image : postgres:17
4
+ ports :
5
+ - " 5439:5432"
6
+ volumes :
7
+ - postgres:/var/lib/postgresql/data
8
+ environment :
9
+ POSTGRES_PASSWORD : password
10
+ POSTGRES_USER : postgres
11
+ POSTGRES_DB : products
12
+
13
+ volumes :
14
+ postgres:
Original file line number Diff line number Diff line change
1
+ import asyncpg
2
+ from asyncpg import Pool , Record
3
+ from starlette .applications import Starlette
4
+ from starlette .routing import Route
5
+ from starlette .requests import Request
6
+ from starlette .responses import Response , JSONResponse
7
+
8
+
9
+ async def create_database_pool () -> None :
10
+ pool : Pool = await asyncpg .create_pool (
11
+ host = '127.0.0.1' ,
12
+ port = 5439 ,
13
+ user = 'postgres' ,
14
+ password = 'password' ,
15
+ database = 'products' ,
16
+ min_size = 6 ,
17
+ max_size = 6
18
+ )
19
+
20
+ app .state .DB = pool
21
+
22
+
23
+ async def destroy_database_pool () -> None :
24
+ await app .state .close ()
25
+
26
+
27
+ async def brands (request : Request ) -> Response :
28
+ connection : Pool = request .app .state .DB
29
+ query = 'SELECT brand_id, brand_name FROM brand;'
30
+ results : list [Record ] = await connection .fetch (query )
31
+ result_as_dict : list [dict ] = [dict (brand ) for brand in results ]
32
+ return JSONResponse (result_as_dict )
33
+
34
+
35
+ app = Starlette (
36
+ routes = [Route ('/brands' , brands )],
37
+ on_startup = [create_database_pool ],
38
+ on_shutdown = [destroy_database_pool ]
39
+ )
Original file line number Diff line number Diff line change
1
+ from flask import Flask , jsonify
2
+ import psycopg2
3
+
4
+ app = Flask (__name__ )
5
+
6
+ conn_info = "dbname=products user=postgres password=password host=127.0.0.1 port=5439"
7
+ db = psycopg2 .connect (conn_info )
8
+
9
+
10
+ @app .route ('/brands' )
11
+ def brands ():
12
+ cur = db .cursor ()
13
+ cur .execute ('SELECT brand_id, brand_name FROM brand' )
14
+ rows = cur .fetchall ()
15
+ cur .close ()
16
+ return jsonify ([{'brand_id' : row [0 ], 'brand_name' : row [1 ]} for row in rows ])
You can’t perform that action at this time.
0 commit comments