commit message from python script

This commit is contained in:
2023-04-11 17:21:48 +02:00
parent 5eb0811319
commit c0ae9cc93d
184 changed files with 3725 additions and 31 deletions

View File

@@ -0,0 +1,31 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
# Zum Testen in der Shell
# mysql -h notebook14 -u python -pvilla inventory
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def main():
db = db_connect(credentials)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,13 @@
#! /usr/bin/env python3
import datetime
strings = [
'2022-11-25 16:04:57',
'2022-11-25 10:10:00',
'2022-11-22 13:01:02',
'2022-10-26 14:02:05',
]
timestamp = datetime.datetime.fromisoformat(strings[0])
print(timestamp.timestamp())

View File

@@ -0,0 +1,46 @@
internal_counter_dict = {}
def counter(func):
def counting(*args, **kwargs):
counting.callcount += 1
return func(*args, **kwargs)
# counting ist "nur" ein Objekt, kann daher auch Attribute halten
counting.callcount = 0
# Alternativ: Funktionsreferenz als Dictionary-Key verwenden
internal_counter_dict[counting] = 0
return counting
def get_counter(func):
try:
return func.callcount
except:
return None
def reset_counter(func):
try:
# Folgende Zeile verhindert das Setzen bei nicht dekorierten Funcs
func.callcount
func.callcount = 0
except:
pass
def trace(func):
# In tracing steht Objekt func via Currying zur Verfuegung
# tracing = <funktionsobjekt>
def tracing(*args, **kwargs):
tracing.level += 1
print(' '*(tracing.level*4)+"BEGIN function", func.__name__, args[0])
result = func(*args, **kwargs)
print(' '*(tracing.level*4)+"END function", func.__name__, args[0])
tracing.level -= 1
return result
tracing.level = 0
return tracing

View File

@@ -0,0 +1,51 @@
#! /usr/bin/env python3
import requests
from pprint import pprint
# http://ip.jsontest.com/
# https://luonnotar.infodrom.org/json/
def get_external_ip():
url = 'https://luonnotar.infodrom.org/json/'
# .get = GET, .post = POST, .put = PUT, .delete = DELETE, .options = OPTIONS
response = requests.get(url)
# print(response)
# print(type(response))
# print(response.status_code)
if response.status_code != 200:
raise Exception("HTTP Status is " + str(response.status_code))
# print(response.content)
# print(type(response.content))
# print("Content-type der Antwort:", response.headers['Content-Type'])
# Konvertierung bytes nach str
#text = response.content.decode()
#print(text)
# Falls die Antwort ein Text ist:
#print(response.text)
# import json
# local_data = json.loads(json_string) # erzeugt Python-Datenstruktur
# json_string = json.dumps(data) # erzeugt JSON-String der Daten
if 'application/json' not in response.headers['content-type']:
raise Exception("Content-Type is not application/json")
# Falls der Content-Type application/json ist
data = response.json()
# Verschachtelte Struktur am Besten einmal mit Pretty-Printer ausgeben
# pprint(data)
return data['ip']['remote']
# data werden url-encoded key=value&key2=value2&key3=value3
# json wird automatisch in JSON kodiert
# response = requests.post(URL, data={...}, json={...}
ip = get_external_ip()
print("Aktuelle externe IP-Adresse:", ip)

14
Lehrer/pythonkurs/Freitag/fak Executable file
View File

@@ -0,0 +1,14 @@
#! /usr/bin/env python3
from decorators import trace
# Python erzeugt daraus
# fak = trace(fak)
@trace
def fak(n):
if n == 0:
return 1
return n * fak(n-1)
print(fak(6))

View File

@@ -0,0 +1,101 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(**data)
cursor.execute(sql)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,106 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%s, %s, %s)
"""
# Platzhalter %s erfordert Tupel mit passenden Werten
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, (data['name'], data['domain'], data['address']))
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name="'notebook99');DELETE FROM hosts; --",
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,106 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# Platzhalter %(name)s erfordert Dict mit passenden Keys
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, data)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
add_host(db, row)
# add_host(db, 'notebook99', 'linuxhotel.de', '192.168.1.299')
# add_host(db, name='notebook99', domain='linuxhotel.de', a='192.168.1.299')
# db_insert(db, 'hosts', row) # noch allgemeiner
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,126 @@
#! /usr/bin/env python3
import sys
import pymysql
# import sqlite3 as dbdriver
# import psycopg2 as dbdriver
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def add_host_variante_0_unvollstaendig(connection, name, domain, address):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(name, domain, address)
def add_host_variante_1_unvollstaendig(connection, *args):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES ('{0}', '{1}', '{2}')
""".format(*args)
# Achtung: https://xkcd.com/327/
def add_host(connection, data):
cursor = connection.cursor()
sql = """
INSERT INTO hosts
(name, domain, address)
VALUES (%(name)s, %(domain)s, %(address)s)
"""
# Platzhalter %(name)s erfordert Dict mit passenden Keys
# In der Datenbank-Schicht wird passend maskiert
cursor.execute(sql, data)
connection.commit()
def add_host_flexi(connection, data, table='hosts'):
cursor = connection.cursor()
sql = """
INSERT INTO {table}
(name, domain, address)
VALUES ('{name}', '{domain}', '{address}')
""".format(table=table, **data)
cursor.execute(sql)
connection.commit()
def db_insert_into(connection, table, data):
columns = []
values = []
for col in data.keys():
col = col.replace("'", '') # gegen SQL Injection
columns.append(col)
values.append('%('+col+')s')
# values.append('%({})s'.format(col))
sql = """
INSERT INTO {table}
({columns})
VALUES ({placeholder})
""".format(
table=table,
columns=','.join(columns),
placeholder=','.join(values))
# Beim Verlassen des Kontextes wird automatisch commit aufgerufen
with connection as cursor:
cursor.execute(sql, data)
def main():
db = db_connect(credentials)
# list_hosts(db)
row = dict(name='notebook99',
domain='linuxhotel.de',
address='192.168.1.299')
db_insert_into(db, 'hosts', row)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,52 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{0:20} {2:15} {1}".format(*row))
# for name, domain, address in cursor:
# pass
def main():
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
hide_exception(main)

View File

@@ -0,0 +1,59 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, length(name) AS namelen, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
#print(cursor.description)
# cursor ist Iterator
# Hausarbeit: Konvertierung von tupel zu dict als Funktion :-)
# for row in named(cursor):
for row in cursor:
#print(list(zip(cursor.description, row)))
#print(list(zip(map(lambda d:d[0], cursor.description), row)))
# Dictionary Comprehension
# mydict = { i: i**10 for i in range(10) }
# row = {k:v for k, v in zip(map(lambda d:d[0], cursor.description), row)}
#print(list(zip(map(lambda d:d[0], cursor.description), row)))
#print(tuple(zip(map(lambda d:d[0], cursor.description), row)))
row = dict(zip(map(lambda d:d[0], cursor.description), row))
print("{name:20} {address:15} {domain}".format(**row))
# for name, domain, address in cursor:
# pass
def main():
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory')
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
hide_exception(main)

View File

@@ -0,0 +1,53 @@
#! /usr/bin/env python3
import sys
import pymysql
sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception
def db_connect(credentials: dict):
connection = pymysql.connect(**credentials)
return connection
def list_hosts(connection):
cursor = connection.cursor()
# Simple: SELECT * FROM hosts
sql = """
SELECT name, length(name) AS namelen, domain, address
FROM hosts
ORDER BY name
"""
cursor.execute(sql)
# TODO: cursor.description enthaelt die Feldnamen
# cursor.fetchone()
# cursor.fetchall()
# cursor ist Iterator
for row in cursor:
print("{name:20} {address:15} {domain}".format(**row))
# for name, domain, address in cursor:
# pass
def main():
# Bitte aus Konfigurationsdatei lesen
credentials = dict(host='notebook14',
user='python',
password='villa',
database='inventory',
# DictCursor erzeugt als row ein Dict statt Tupel
cursorclass=pymysql.cursors.DictCursor)
db = db_connect(credentials)
list_hosts(db)
# Verbindung sauber trennen
db.close()
hide_exception(main)

View File

@@ -0,0 +1,17 @@
"""
Allgemeine Mathematische Funktionen
"""
__version__ = (1, 0, 2)
def fak(n):
"Berechnung der Fakultaet"
if type(n) is not int:
raise TypeError("Fakultaet ist nur fuer Ganzzahlen definiert")
if n < 0:
raise ValueError("Fakultaet fuer negative Zahlen nicht definiert")
if n == 0:
return 1
return n * fak(n-1)

View File

@@ -0,0 +1,49 @@
from unittest import TestCase, main, skip, skipIf, skipUnless
from mathematik import fak
class FacultyTester(TestCase):
def test_basic(self):
self.assertEqual(fak(0), 1)
self.assertEqual(fak(1), 1)
def test_basic2(self):
self.assertTrue(fak(0) == 1)
self.assertTrue(fak(1) == 1)
def test_basic3(self):
self.assertFalse(fak(0) == 0)
def test_greater(self):
for n in range(2,10):
self.assertGreater(fak(n), fak(n-1))
def test_invalid(self):
# Achtung: Funktion wird ausserhalb von assertRaises aufgerufen
# self.assertRaises(Exception, fak(-1))
# Jetzt ruft assertRaises das Callable=fak mit *args, **kwargs auf
self.assertRaises(Exception, fak, -1)
with self.assertRaises(Exception):
fak(-1)
with self.assertRaises(ValueError):
fak(-1)
# v1 + v2
def test_kaputt(self):
self.skipTest("Ist kaputt")
self.assertTrue(False)
@skip("darum")
def test_kaputt_auch_ist(self):
self.assertTrue(False)
# mathematik.__version__ / mathematik.VERSION
@skipUnless("1.0" > "3.0", "Modul zu alt")
def test_ab_version_3(self):
self.assertFalse(True)
if __name__ == '__main__':
main()