-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_sql_licenses.py
More file actions
85 lines (72 loc) · 3.03 KB
/
Copy pathpython_sql_licenses.py
File metadata and controls
85 lines (72 loc) · 3.03 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from typing import Union
import psycopg2 as ps
identifiants = {'database': 'license',
'user': 'postgres',
'password': 'bonjour',
'host': 'localhost',
'port': 5432}
def log(message: str) -> bool:
try:
with open("log.txt", "a", encoding="utf-8") as file:
file.write(f'\n{message}')
return True
except:
return False
def format_sql(data: Union[str, int, list[str], list[int], bool]) -> str:
if type(data) == str:
return f"'{data}'"
if type(data) == list:
if len(data) == 0:
return
return f'ARRAY[{", ".join([format_sql(x) for x in data])}]'
return str(data)
def get(tables: list[str], variable: str = "", valeur: str = "", identifiants: dict[str, str] = identifiants) -> list[
tuple]:
with ps.connect(**identifiants) as connector:
with connector.cursor() as cursor:
if len(tables) >= 3:
return [('Erreur')]
commande = f'select * from public."{tables[0]}"'
if len(tables) == 2:
commande += f' inner join public."{tables[1]}" on public."{tables[0]}".{tables[1]}_id = public."{tables[1]}".id'
if variable:
commande += f" where {variable} = '{valeur}'"
cursor.execute(commande)
return cursor.fetchall()
def post(table: str, data: dict[str, str], identifiants: dict[str, str] = identifiants) -> bool:
try:
with ps.connect(**identifiants) as connector:
with connector.cursor() as cursor:
"""insert into public."IP_address" values (2, '192.168.11.4', 24, True, False)"""
cursor.execute(f"""
insert into public."{table}" values ({", ".join([format_sql(x) for x in data.values()])})
""")
connector.commit()
return True
except:
return False
def delete(table: str, id: int, identifiants: dict[str, str] = identifiants) -> bool:
try:
with ps.connect(**identifiants) as connector:
with connector.cursor() as cursor:
cursor.execute(f"""
delete from public."{table}" where id = {id}
""")
connector.commit()
return cursor.rowcount > 0
except:
return False
if __name__ == '__main__':
"""User guide de la librairie"""
print(get(["IP_address"]))
print(get(["group"], 'name', 'Vannes'))
print(post(table="IP_address", data={'id': 6, 'address': "10.4.2.1"}))
print(delete("group", 1))
print(delete("group", 3))
print(post("subnet", {'id': 5, 'first@': '10.0.0.2', 'gp_id': 1}))
print(post("group", {'id': 3,
'name': 'Brest',
'p_id': 1,
'c_ids': [1, 4, 6],
'r_r': ['dl', 'sa'],
'w_r': ['sa']}))