Compare commits
6 Commits
d4165b0582
...
teil28
Author | SHA1 | Date | |
---|---|---|---|
![]() |
fec0969d7f | ||
![]() |
af36c44e66 | ||
b913b2cb01 | |||
![]() |
37cbae2683 | ||
![]() |
14d3064309 | ||
![]() |
fd50a8628c |
@@ -31,5 +31,6 @@ CC-BY-SA Olli Graf
|
||||
|24 | match|
|
||||
|25 | reguläre Ausdrücke|
|
||||
|26 | lambda Funktionen|
|
||||
|27 | __getattr__()|
|
||||
|27 | logging.config|
|
||||
|28 | Decorators|
|
||||
|
||||
|
@@ -1,20 +0,0 @@
|
||||
from math import pi as pi
|
||||
|
||||
|
||||
class Kreis_gettattr:
|
||||
def __init__(self, radius):
|
||||
self.radius = radius
|
||||
self.operators ={
|
||||
'durchmesser': lambda x: self.radius * 2
|
||||
'umfang': lambda x: self.durchmesser * pi
|
||||
'flaeche': lambda: x: self.radius**2 *pi
|
||||
}
|
||||
|
||||
def __getattr(self, name):
|
||||
if name not in self.operators:
|
||||
raise TypeError(f'unbekannte Operation {name}')
|
||||
|
||||
return {
|
||||
} [name]
|
||||
|
||||
|
2
teil13/.gitignore
vendored
2
teil13/.gitignore
vendored
@@ -1,2 +1,2 @@
|
||||
./__pycache__
|
||||
__pycache__
|
||||
./network/__pycache__/*
|
||||
|
@@ -1,3 +1,6 @@
|
||||
example.py
|
||||
ex2.py
|
||||
*.log
|
||||
__pycache__
|
||||
db.ini
|
||||
|
10
teil27/JSONFormatter.py
Normal file
10
teil27/JSONFormatter.py
Normal file
@@ -0,0 +1,10 @@
|
||||
import logging
|
||||
import logging.config
|
||||
import json
|
||||
ATTR_TO_JSON = ['created', 'filename', 'funcName', 'levelname', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName']
|
||||
class JsonFormatter:
|
||||
def format(self, record):
|
||||
obj = {attr: getattr(record, attr)
|
||||
for attr in ATTR_TO_JSON}
|
||||
return json.dumps(obj, indent=4)
|
||||
|
8
teil27/db.ini.sample
Normal file
8
teil27/db.ini.sample
Normal file
@@ -0,0 +1,8 @@
|
||||
[pidb]
|
||||
host=database
|
||||
user=piuser
|
||||
password=<passwort>
|
||||
database=pidb
|
||||
|
||||
|
||||
|
75
teil27/dbhandler.py
Normal file
75
teil27/dbhandler.py
Normal file
@@ -0,0 +1,75 @@
|
||||
# Datei dbhandler.py
|
||||
import mysql.connector
|
||||
import datetime
|
||||
import configparser
|
||||
import logging
|
||||
from logging import config
|
||||
import json
|
||||
|
||||
|
||||
|
||||
|
||||
class DBHandler(logging.Handler):
|
||||
def __init__(self):
|
||||
logging.Handler.__init__(self)
|
||||
# Datenbank Konfiguration lesen
|
||||
confparser = configparser.ConfigParser()
|
||||
confparser.read('db.ini')
|
||||
# Verbindung zur DB herstellen
|
||||
self.connection= mysql.connector.connect(host=confparser['pidb']['host'],user = confparser['pidb']['user'],password = confparser['pidb']['password'],database = confparser['pidb']['database'])
|
||||
# Tabelle anlegen, falls noch keine existiert.
|
||||
self.connection.cursor().execute('''CREATE TABLE IF NOT EXISTS logs (
|
||||
id INTEGER PRIMARY KEY AUTO_INCREMENT,
|
||||
zeit VARCHAR(50),
|
||||
level VARCHAR(8),
|
||||
message VARCHAR(40),
|
||||
logger_name VARCHAR(25),
|
||||
filename VARCHAR(60),
|
||||
line INTEGER)''')
|
||||
self.connection.commit()
|
||||
|
||||
# Bei Löschung der Klasseninstanz, Connection schliessen
|
||||
def __del__(self):
|
||||
if self.connection != None:
|
||||
self.connection.close()
|
||||
self.connection = None
|
||||
|
||||
# LogRecord in die DB schreiben
|
||||
def emit(self, record):
|
||||
try:
|
||||
# Log-Daten in ein Tupel extrahieren
|
||||
log_entry = (datetime.datetime.utcnow().isoformat(),
|
||||
record.levelname,
|
||||
record.getMessage(),
|
||||
record.name,
|
||||
record.pathname,
|
||||
record.lineno)
|
||||
|
||||
# Log in die Datenbank einfügen
|
||||
cursor = self.connection.cursor()
|
||||
cursor.execute('''INSERT INTO logs (zeit, level, message, logger_name, filename, line)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)''', log_entry)
|
||||
self.connection.commit()
|
||||
cursor.close()
|
||||
|
||||
except Exception as e:
|
||||
# im Fehlerfall den LogRecord nach "oben" weiterreichen.
|
||||
self.handleError(record)
|
||||
|
||||
# Config aus JSON Datei laden und setzen
|
||||
with open('handler_config.json') as file_config:
|
||||
config.dictConfig(json.load(file_config))
|
||||
# Logging testen
|
||||
def testlogging():
|
||||
print('testlogging() aufgerufen.')
|
||||
logging.debug('Diese Zeile wird ausgefiltert.')
|
||||
logging.debug('DEBUG/Druckdaten werden gesendet.')
|
||||
logging.info('INFO/Es werden 2 Seiten gedruckt')
|
||||
logging.debug('Diese Zeile wird auch ausgefiltert.')
|
||||
logging.warning('WARN/nicht genügend Papier im Drucker')
|
||||
logging.error('ERROR/Drucker nicht gefunden.')
|
||||
logging.critical('CRITICAL/Drucker brennt')
|
||||
|
||||
if __name__ == '__main__':
|
||||
testlogging()
|
||||
|
@@ -1,7 +1,19 @@
|
||||
#encoding: utf-8
|
||||
import logging
|
||||
from logging import config
|
||||
import json
|
||||
import random
|
||||
import JSONFormatter
|
||||
|
||||
#JSON Formatter
|
||||
ATTR_TO_JSON = ['created', 'filename', 'funcName', 'levelname', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'thread', 'threadName']
|
||||
class JsonFormatter:
|
||||
def format(self, record):
|
||||
obj = {attr: getattr(record, attr)
|
||||
for attr in ATTR_TO_JSON}
|
||||
return json.dumps(obj, indent=4)
|
||||
|
||||
#CustomFilter
|
||||
|
||||
class HalloweenFilter(logging.Filter):
|
||||
|
||||
@@ -14,7 +26,7 @@ class HalloweenFilter(logging.Filter):
|
||||
# Der Unsichtbare soll keine Spuren im Logfile hinterlassen.
|
||||
return record.getMessage().lower().find('unsichtbar') == -1
|
||||
|
||||
visitors = ['Werwolf','Gespenst','Hexe','Unsichtbarer','Vampir','Dämon','Gorilla','Hulk','Mumie']
|
||||
visitors = ['Werwolf','Gespenst','Hexe','Unsichtbarer','Vampir','Dämon','Gorilla','Monster','Mumie']
|
||||
|
||||
treats = ['Bonbons','Twinkies','Lollis','Schokoladen','Kuchen', 'Äpfel']
|
||||
|
@@ -9,6 +9,9 @@
|
||||
"std_out":{
|
||||
"format": "%(asctime)s : %(levelname)s : %(lineno)d : %(message)s",
|
||||
"datefmt":"%I:%M:%S %d.%m.%Y"
|
||||
},
|
||||
"json": {
|
||||
"()": "__main__.JsonFormatter"
|
||||
}
|
||||
},
|
||||
"handlers":{
|
||||
@@ -18,7 +21,7 @@
|
||||
"level": "DEBUG"
|
||||
},
|
||||
"file":{
|
||||
"formatter":"std_out",
|
||||
"formatter":"json",
|
||||
"class":"logging.FileHandler",
|
||||
"level":"DEBUG",
|
||||
"filename" : "halloween.log",
|
33
teil27/handler_config.json
Normal file
33
teil27/handler_config.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"version":1,
|
||||
"formatters":{
|
||||
"std_out":{
|
||||
"format": "%(asctime)s : %(levelname)s : %(module)s : %(funcName)s : %(lineno)d : (Process Details : (%(process)d, %(processName)s), Thread Details : (%(thread)d, %(threadName)s))\nLog : %(message)s",
|
||||
"datefmt":"%d-%m-%Y %I:%M:%S"
|
||||
}
|
||||
},
|
||||
"handlers":{
|
||||
"console":{
|
||||
"formatter": "std_out",
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "DEBUG"
|
||||
},
|
||||
"db":{
|
||||
"formatter": "std_out",
|
||||
"()": "__main__.DBHandler",
|
||||
"level": "DEBUG"
|
||||
},
|
||||
"file":{
|
||||
"formatter":"std_out",
|
||||
"class":"logging.FileHandler",
|
||||
"level":"DEBUG",
|
||||
"filename" : "raspithek.log"
|
||||
}
|
||||
},
|
||||
"root":{
|
||||
"handlers":["console","file","db"],
|
||||
"level": "DEBUG"
|
||||
}
|
||||
|
||||
}
|
||||
|
1
teil28/.gitignore
vendored
Normal file
1
teil28/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
__pycache__
|
25
teil28/classdecor.py
Normal file
25
teil28/classdecor.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Datei: classdecor.py
|
||||
|
||||
|
||||
def addrepr(cls):
|
||||
# Universelle __repr__ Methode
|
||||
def __repr__(self):
|
||||
return f"{cls.__name__}({self.__dict__})"
|
||||
cls.__repr__ = __repr__
|
||||
|
||||
return cls
|
||||
|
||||
@addrepr
|
||||
class Fahrzeug():
|
||||
def __init__(self,farbe,typ):
|
||||
self.typ = typ
|
||||
self.farbe = farbe
|
||||
|
||||
|
||||
f1 = Fahrzeug('grau','VW')
|
||||
f2 = Fahrzeug('rot','Ferrari')
|
||||
|
||||
print(f'{f1}')
|
||||
print(f'{f2}')
|
||||
|
||||
|
13
teil28/counter.py
Normal file
13
teil28/counter.py
Normal file
@@ -0,0 +1,13 @@
|
||||
#Datei: counter.py
|
||||
|
||||
def counter(func):
|
||||
func.count = 0
|
||||
def wrapper(*args, **kwargs):
|
||||
func.count = func.count +1
|
||||
print(f'{func.__name__} wurde {func.count}-mal aufgerufen.')
|
||||
result = func(*args,**kwargs)
|
||||
|
||||
return result
|
||||
wrapper.count = 0
|
||||
return wrapper
|
||||
|
16
teil28/fib.py
Normal file
16
teil28/fib.py
Normal file
@@ -0,0 +1,16 @@
|
||||
#Datei: fib.py
|
||||
|
||||
import functools
|
||||
import sys
|
||||
from counter import counter
|
||||
|
||||
#@functools.cache
|
||||
@counter
|
||||
def fib(n):
|
||||
if n in [0,1]:
|
||||
return n
|
||||
else:
|
||||
return fib(n-1) + fib(n-2)
|
||||
|
||||
|
||||
|
16
teil28/func_param.py
Normal file
16
teil28/func_param.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# Datei: func_param.py
|
||||
|
||||
def add(x, y):
|
||||
return x + y
|
||||
|
||||
def mul(x,y):
|
||||
return x * y
|
||||
|
||||
def calculate(func, x, y):
|
||||
return func(x, y)
|
||||
|
||||
result = calculate(add, 4, 6) # Aufruf von calculate mit add Funktion als Parameter
|
||||
print(result) # Ausgabe ist 10
|
||||
|
||||
result = calculate(mul, 4, 6) # Aufruf von calculate mit add Funktion als Parameter
|
||||
print(result) # Ausgabe ist 24
|
12
teil28/nested_function.py
Normal file
12
teil28/nested_function.py
Normal file
@@ -0,0 +1,12 @@
|
||||
#Datei: nested_function.py
|
||||
|
||||
def print_message(message):
|
||||
print('Umgebende Funktion')
|
||||
def inner_function():
|
||||
print('Eingebettete Funktion')
|
||||
print(message)
|
||||
|
||||
inner_function()
|
||||
|
||||
print_message("Irgendein Text")
|
||||
|
20
teil28/pass_func.py
Normal file
20
teil28/pass_func.py
Normal file
@@ -0,0 +1,20 @@
|
||||
def make_pretty(func):
|
||||
# define the inner function
|
||||
def inner():
|
||||
# add some additional behavior to decorated function
|
||||
print("Dies ist die innere Funktion.")
|
||||
|
||||
# call original function
|
||||
func()
|
||||
# return the inner function
|
||||
return inner
|
||||
|
||||
# define ordinary function
|
||||
def ordinary():
|
||||
print("Dies ist die ordinary() Funktion.")
|
||||
|
||||
# decorate the ordinary function
|
||||
decorated_func = make_pretty(ordinary)
|
||||
|
||||
# call the decorated function
|
||||
decorated_func()
|
17
teil28/reverse.py
Normal file
17
teil28/reverse.py
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
|
||||
def reverse_decorator(func):
|
||||
|
||||
def wrapper(text):
|
||||
make_reverse = "".join(reversed(text))
|
||||
return func(make_reverse)
|
||||
|
||||
return wrapper
|
||||
|
||||
@reverse_decorator
|
||||
def format_message(text):
|
||||
return f'Text: {text}'
|
||||
|
||||
print(format_message('Hallo'))
|
||||
|
||||
|
21
teil28/simpledecorator.py
Normal file
21
teil28/simpledecorator.py
Normal file
@@ -0,0 +1,21 @@
|
||||
def make_pretty(func):
|
||||
# define the inner function
|
||||
def inner():
|
||||
# add some additional behavior to decorated function
|
||||
print("I got decorated")
|
||||
|
||||
# call original function
|
||||
func()
|
||||
# return the inner function
|
||||
return inner
|
||||
|
||||
# define ordinary function
|
||||
@make_pretty
|
||||
def ordinary():
|
||||
print("I am ordinary")
|
||||
|
||||
# decorate the ordinary function
|
||||
decorated_func = make_pretty(ordinary)
|
||||
|
||||
# call the decorated function
|
||||
ordinary()
|
20
teil28/static.py
Normal file
20
teil28/static.py
Normal file
@@ -0,0 +1,20 @@
|
||||
# Datei static.py
|
||||
|
||||
class Math():
|
||||
|
||||
@staticmethod
|
||||
def add(x,y):
|
||||
return x+y
|
||||
|
||||
@staticmethod
|
||||
def sub(x,y):
|
||||
return x-y
|
||||
|
||||
@staticmethod
|
||||
def mul(x,y):
|
||||
return x*y
|
||||
|
||||
|
||||
print(f'Add: {Math.add(3,2)}')
|
||||
print(f'Sub: {Math.sub(3,2)}')
|
||||
print(f'Mul: {Math.mul(3,2)}')
|
28
teil28/timer.py
Normal file
28
teil28/timer.py
Normal file
@@ -0,0 +1,28 @@
|
||||
#Datei: timer.py
|
||||
|
||||
from fib import fib
|
||||
from counter import counter
|
||||
import time
|
||||
import sys
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
|
||||
result = func(*args,**kwargs)
|
||||
|
||||
end_time = time.time()
|
||||
print(f'Methode {func.__name__} - Laufzeit {end_time - start_time:.4f}s')
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
@timer
|
||||
def summe(n):
|
||||
return f"Summe: {sum(range(n))}"
|
||||
|
||||
@timer
|
||||
def calc_fib(n):
|
||||
return fib(n)
|
||||
|
||||
print(summe(1000000))
|
||||
print(calc_fib(int(sys.argv[1])))
|
Reference in New Issue
Block a user