added sql stuff

This commit is contained in:
2022-11-25 12:55:49 +01:00
parent aea7c693d6
commit 0c233cdce8
11 changed files with 365 additions and 0 deletions

Binary file not shown.

Binary file not shown.

28
Freitag/db_con.py Normal file
View File

@@ -0,0 +1,28 @@
#! /usr/bin/env python3
#
#Benötigt python3-pymysql
# mysql -h notebook14 -u python -pvilla inventory
import sys
import pymysql
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
# Passwort aus Konfigiruationsdaten lesen
credentials = dict(
host = 'notebook14',
user = 'python',
password = 'villa',
database = 'inventory'
)
#Connection
def main():
db = db_connect(credentials)
db.close()
hide_exception(main)

63
Freitag/db_insert.py Normal file
View File

@@ -0,0 +1,63 @@
#! /usr/bin/env python3
#
#Benötigt python3-pymysql
# mysql -h notebook14 -u python -pvilla inventory
import sys
import pymysql
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
# Passwort aus Konfigiruationsdaten lesen
credentials = dict(
host = 'notebook14',
user = 'python',
password = 'villa',
database = 'inventory'
)
def list_hosts(connection):
cursor = connection.cursor()
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#ermittlung cursor.fetchone() eine Zeile cursor.fetchmany() gibt vile in einer Zeile
# cursor ist Iterator
#test = [row for row in cursor]
for row in cursor:
print("{0:20} {2:15} {2}".format(*row))
def add_host(connection, args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# oder mit .format(**args) {name} usw
cursor.execute(sql,args)
connection.commit()
#Connection
def main():
db = db_connect(credentials)
#list_hosts(db)
row = dict(
name='notebook999',
domain='linuxhotel.de',
address='192.168.1.254',
db = 'hosts'
)
add_host(db, row)
db.close()
hide_exception(main)

45
Freitag/db_select.py Normal file
View File

@@ -0,0 +1,45 @@
#! /usr/bin/env python3
#
#Benötigt python3-pymysql
# mysql -h notebook14 -u python -pvilla inventory
import sys
import pymysql
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
# Passwort aus Konfigiruationsdaten lesen
credentials = dict(
host = 'notebook14',
user = 'python',
password = 'villa',
database = 'inventory'
)
def list_hosts(connection):
cursor = connection.cursor()
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#ermittlung cursor.fetchone() eine Zeile cursor.fetchmany() gibt vile in einer Zeile
# cursor ist Iterator
#test = [row for row in cursor]
for row in cursor:
print("{0:20} {2:23} {1:15}".format(*row))
#Connection
def main():
db = db_connect(credentials)
list_hosts(db)
db.close()
hide_exception(main)

33
Freitag/decorators.py Normal file
View File

@@ -0,0 +1,33 @@
#!/usr/bin/env python3
def counter(func):
def counting(*args, **kwargs):
counting.callcount += 1
return func(*args, **kwargs)
counting.callcount = 0
return counting
def get_counter(func):
try:
return func.callcount
except:
return None
def reset_counter(func):
try:
func.callcount
func.callcount = 0
except:
return None
def trace(func):
def tracing(*args, **kwargs):
tracing.level += 1
print(' '*(tracing.level*4) + "BEGIN function", func.__name__)
result = func(*args, **kwargs)
print(' '*(tracing.level*4) + "End function", func.__name__)
tracing.level -= 1
return result
tracing.level = 0
return tracing

24
Freitag/ext_ip.py Normal file
View File

@@ -0,0 +1,24 @@
#! /usr/bin/env python3
import requests
#import json
#localdata = json.loads(json_string) # erzeugt Python-Datemstruktur
#jsonstring = json.dumps(data) # erzeugt eni Json-String der Daten
#http://ip.jsontest.com
#https://luonnotar.infodrom.org/json
def get_external_ip():
url = 'https://luonnotar.infodrom.org/json'
response = requests.get(url)
if response.status_code != 200:
raise Exception("HTTP Status is " + str(response.status_code))
#text = response.content.decode()
#print("Content-type der Antwort:", response.headers['Content-Type'])
data = response.json()
if 'application/json' not in response.headers['Content-Type']:
raise Exception ("Content-Type is not application/json")
ip = data['ip']['remote']
return ip
ip = get_external_ip()
print("Aktuelle externe IP-Addresse: ", ip)

22
Freitag/fakultät.py Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python3
from decorators import counter, get_counter, trace
@counter
def fak(n):
if type(n) is not int or n < 0:
raise TypeError("Illegal type")
if n == 0:
return 1
return n * fak(n-1)
print("6! =", fak(6))
print("Anzahl Aufrufe:", get_counter(fak))
@trace
def fak(n):
if n == 0:
return 1
return n * fak(n-1)
print(fak(4))

37
Freitag/fibonacci.py Normal file
View File

@@ -0,0 +1,37 @@
#! /usr/bin/env python3
def fibonacci(n):
if n == 1 or n == 2:
return 1
#Rekursiver Funktionsaufruf
#return fibonacci(n - 1) + fibonacci(n - 2)
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
return fn_1
def fibonacci_folge(n):
if n >= 1:
#print("yield 1 (fib(1))")
yield 1
if n >=2:
#print("yield 1 (fib(2))")
yield 1
#Rekursiver Funktionsaufruf
#return fibonacci(n - 1) + fibonacci(n - 2)
fn_1, fn_2 = 1, 1
for i in range(n-2):
fn_1, fn_2 = fn_1 + fn_2, fn_1
#print("yield {} (fib({}))".format(fn_1, i+3))
yield fn_1
#print("fib(5) =", fibonacci(5))
#
# print("fib(40) =", fibonacci(400))
for nr, fib in enumerate(fibonacci_folge(30)):
print(nr+1, fib, sep=' -> ')
#print(list(fibonacci_folge(30)))
#print([i for i in fibonacci_folge(10)])

86
Freitag/insert_all.py Normal file
View File

@@ -0,0 +1,86 @@
#! /usr/bin/env python3
#
#Benötigt python3-pymysql
# mysql -h notebook14 -u python -pvilla inventory
import sys
import pymysql
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
# Passwort aus Konfigiruationsdaten lesen
def list_hosts(connection):
cursor = connection.cursor()
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#ermittlung cursor.fetchone() eine Zeile cursor.fetchmany() gibt vile in einer Zeile
# cursor ist Iterator
#test = [row for row in cursor]
for row in cursor:
print("{0:20} {2:15} {2}".format(*row))
def add_host(connection, args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# oder mit .format(**args) {name} usw
cursor.execute(sql,args)
connection.commit()
def db_insert_into(connection, table, data):
columns = []
values = []
for col in data.keys():
col = col.replace("'", '')
columns.append(col)
values.append('%('+col+')s')
sql = """
INSERT INTO {table}
({columns})
VALUES ({placeholder})
""".format(
table=table,
columns=','.join(columns),
placeholder=','.join(values),
)
print(sql)
with connection as cursor:
cursor.execute(sql, data)
#Connection
def main():
credentials = dict(
host = 'notebook14',
user = 'python',
password = 'villa',
database = 'inventory'
)
db = db_connect(credentials)
#list_hosts(db)
row = dict(
name='notebook999',
domain='linuxhotel.example',
address='192.168.1.254',
)
db_insert_into(db, 'hosts', row )
db.close()
hide_exception(main)

27
Freitag/utilities.py Normal file
View File

@@ -0,0 +1,27 @@
"""
Miscellaneous utilities
"""
import sys
from traceback import format_tb
def hide_exception(func):
try:
return func()
except Exception as e:
name = type(e).__name__
text = str(e)
traceback = ''.join(format_tb(e.__traceback__))
if '-V' in sys.argv:
print("Entwickler_Mode: wip")
#Für Faule Leute einfacher weiterleiten mit raise
#raise
print("{name}: {text}".format(name=name, text=text), file=sys.stderr)
print("Traceback:\n", traceback, sep='', file=sys.stderr)
else:
print("Interner Fehler,", e)
if __name__ == '__main__':
print("from uitlities import hide_exception")
print("hide_exception(main)")