From 0c233cdce835d4f1ff40d4ce764080e8a45728aa Mon Sep 17 00:00:00 2001 From: JonnyBravo Date: Fri, 25 Nov 2022 12:55:49 +0100 Subject: [PATCH] added sql stuff --- Freitag/__pycache__/decorators.cpython-39.pyc | Bin 0 -> 1148 bytes Freitag/__pycache__/utilities.cpython-39.pyc | Bin 0 -> 845 bytes Freitag/db_con.py | 28 ++++++ Freitag/db_insert.py | 63 +++++++++++++ Freitag/db_select.py | 45 +++++++++ Freitag/decorators.py | 33 +++++++ Freitag/ext_ip.py | 24 +++++ Freitag/fakultät.py | 22 +++++ Freitag/fibonacci.py | 37 ++++++++ Freitag/insert_all.py | 86 ++++++++++++++++++ Freitag/utilities.py | 27 ++++++ 11 files changed, 365 insertions(+) create mode 100644 Freitag/__pycache__/decorators.cpython-39.pyc create mode 100644 Freitag/__pycache__/utilities.cpython-39.pyc create mode 100644 Freitag/db_con.py create mode 100644 Freitag/db_insert.py create mode 100644 Freitag/db_select.py create mode 100644 Freitag/decorators.py create mode 100644 Freitag/ext_ip.py create mode 100644 Freitag/fakultät.py create mode 100644 Freitag/fibonacci.py create mode 100644 Freitag/insert_all.py create mode 100644 Freitag/utilities.py diff --git a/Freitag/__pycache__/decorators.cpython-39.pyc b/Freitag/__pycache__/decorators.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf5888cf151a5c079afdbd3e0864d98e1ec665c0 GIT binary patch literal 1148 zcmZ`&&ubG=5PtLa*Gt=k3bj=c?7_<(Yy<^8lp;zM5%!Wpv6ry!drea}yXC!IrAq|C zLgU51!b|?8y?V;oTTjlsCQY!-hM9S@Z)U#PnJ;m(xx(=IaP~d<%NhGa&fzAdTr&Tg6`wAtI4VN57Q(|3$P2Xq#sJW>r*budk(`53B< z1sxys8lG+pk?!B1*jZF!h_g7rv4Q=4#MN}zQ>#OWET~?^=qpHzYav&As_0H(Y4L`x z7;q4Pz)d_a2POto>jVtAh9NHDfMu;)8sL$p+RM9WYGvkqtYfUPEW|#1SfNf@w{^0d zM}Ry6BE?M}QPMS!KA|&$MIIGM#1SB`oDH_Yq`QSYJK;Y#pq(@98~-oPTZo(1due$& z__p_oF-EI~SRJR*C zn!49iqxNxTWm=56rBWRfI!=(tR|}@y>P=Mi4>QCc;^u>?RGSp6<_w+X($GWDchD@b yt;YC(Bg; literal 0 HcmV?d00001 diff --git a/Freitag/__pycache__/utilities.cpython-39.pyc b/Freitag/__pycache__/utilities.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5090f647dba090b2d5bc9d14b482a6a16beb594c GIT binary patch literal 845 zcmY*XK~EGh6mC16+1UX$#GvAB4j$YDT@pMPLX3%l!~K$ztpP-<6rRP>mmf2^m~2ZYrnqsy<}-ALNGpj`IP=92>o)-?ExHm1+&@$ z;An_A<|M;I4A#p??hQSRIOYClG^E1k!3ohXM8G>Uj1kz-Sx)v*zuP>Dc4d`{EK8Iq z>ME{{%%qW`ivEB&+UsN6Jt}mb7-kMr?708K2kY{D4YT?N(1cSoLkDOdQDo5MD@HBc z)0`SS#WOr6Eis;3wI0Xcsqv?H9L(?!+)_?VXB?g)eQvtkbJ>BV<7i5z9``R@bb$w# zWX^Y{l;b%QUQ&!y1be%n3(*7g9{!`nAF+zA>^fQp23{KNS=5lH@0yiuWzJ-Jk_pXr z3obU}Gg&sh3zg)e-Hb1cI5%ydSn3E%oeO_Jk7OpAg||9M#bJ`3Y(}uft3;^-_wwa8 z$_TB5j(5Zel-K%;w!3|viqgnJfy$&5He}3cG6n~Ywsc%brClxU5@Y6Cc^;lrmL~f6 z)cU2C%Gltl1U9G)7h3myNT^n+#X?gM(5@D?d!z9a=?B34T^o#wTntog8lj(W4EEDe zoz?1iu%m@E$?@Q(+Rw^~?TsWCOk8K(0foxRAWU$GdpH7ICV<{5ULkrFBJNFjA{ArJ z<0D<k literal 0 HcmV?d00001 diff --git a/Freitag/db_con.py b/Freitag/db_con.py new file mode 100644 index 0000000..2688c19 --- /dev/null +++ b/Freitag/db_con.py @@ -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) \ No newline at end of file diff --git a/Freitag/db_insert.py b/Freitag/db_insert.py new file mode 100644 index 0000000..629ce22 --- /dev/null +++ b/Freitag/db_insert.py @@ -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) \ No newline at end of file diff --git a/Freitag/db_select.py b/Freitag/db_select.py new file mode 100644 index 0000000..b410161 --- /dev/null +++ b/Freitag/db_select.py @@ -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) \ No newline at end of file diff --git a/Freitag/decorators.py b/Freitag/decorators.py new file mode 100644 index 0000000..1a45fe8 --- /dev/null +++ b/Freitag/decorators.py @@ -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 \ No newline at end of file diff --git a/Freitag/ext_ip.py b/Freitag/ext_ip.py new file mode 100644 index 0000000..ab5a64f --- /dev/null +++ b/Freitag/ext_ip.py @@ -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) \ No newline at end of file diff --git a/Freitag/fakultät.py b/Freitag/fakultät.py new file mode 100644 index 0000000..79a496c --- /dev/null +++ b/Freitag/fakultät.py @@ -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)) \ No newline at end of file diff --git a/Freitag/fibonacci.py b/Freitag/fibonacci.py new file mode 100644 index 0000000..28d0ac8 --- /dev/null +++ b/Freitag/fibonacci.py @@ -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)]) + \ No newline at end of file diff --git a/Freitag/insert_all.py b/Freitag/insert_all.py new file mode 100644 index 0000000..167d321 --- /dev/null +++ b/Freitag/insert_all.py @@ -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) \ No newline at end of file diff --git a/Freitag/utilities.py b/Freitag/utilities.py new file mode 100644 index 0000000..da32006 --- /dev/null +++ b/Freitag/utilities.py @@ -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)") \ No newline at end of file