From a06b4c535c63fb3bc0cb3185797267faf93f4add Mon Sep 17 00:00:00 2001 From: TurboFen Date: Sat, 25 Apr 2020 22:52:29 +0300 Subject: [PATCH 1/6] =?UTF-8?q?1=20=D0=B7=D0=B0=D0=BB=D0=B8=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homework/Info.txt | 0 homework/config.py | 15 +-- homework/mistakes.txt | 0 homework/patient.py | 239 ++++++++++++++++++++++++++++++++++++++++-- tests/Info.txt | 0 tests/mistakes.txt | 0 tests/patiens.csv | 1 + 7 files changed, 239 insertions(+), 16 deletions(-) create mode 100644 homework/Info.txt create mode 100644 homework/mistakes.txt create mode 100644 tests/Info.txt create mode 100644 tests/mistakes.txt create mode 100644 tests/patiens.csv diff --git a/homework/Info.txt b/homework/Info.txt new file mode 100644 index 0000000..e69de29 diff --git a/homework/config.py b/homework/config.py index 955b991..f3e83ef 100644 --- a/homework/config.py +++ b/homework/config.py @@ -1,13 +1,14 @@ -GOOD_LOG_FILE = "good_log.txt" -ERROR_LOG_FILE = "error_log.txt" -CSV_PATH = "csv.csv" -PHONE_FORMAT = "79160000000" # Здесь запишите телефон +7-916-000-00-00 в том формате, в котором вы храните телефоны +# -*- coding: utf-8 -*- +GOOD_LOG_FILE = "Info.txt" +ERROR_LOG_FILE = "mistakes.txt" +CSV_PATH = "patiens.csv" +PHONE_FORMAT = "89032027936" # Здесь запишите телефон +7-916-000-00-00 в том формате, в котором вы храните телефоны PASSPORT_TYPE = "паспорт" # тип документа, когда он паспорт -PASSPORT_FORMAT = "0000 000000" # Здесь запишите номер парспорта 0000 000000 в том формате, в котором вы его храните +PASSPORT_FORMAT = "0000000000" # Здесь запишите номер парспорта 0000 000000 в том формате, в котором вы его храните INTERNATIONAL_PASSPORT_TYPE = "заграничный паспорт" # тип документа, если это загран -INTERNATIONAL_PASSPORT_FORMAT = "00 0000000" # формат хранения заграна для номера 00 0000000 +INTERNATIONAL_PASSPORT_FORMAT = "000000000" # формат хранения заграна для номера 00 0000000 DRIVER_LICENSE_TYPE = "водительское удостоверение" # тип документа, если это водительское удостоверение -DRIVER_LICENSE_FORMAT = "00 00 000000" # формат хранения номера ВУ +DRIVER_LICENSE_FORMAT = "0000000000" # формат хранения номера ВУ diff --git a/homework/mistakes.txt b/homework/mistakes.txt new file mode 100644 index 0000000..e69de29 diff --git a/homework/patient.py b/homework/patient.py index dad2526..c7e1aaf 100644 --- a/homework/patient.py +++ b/homework/patient.py @@ -1,17 +1,238 @@ +import logging +import csv +import os.path + + + +class CheckName: + + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + + if instance.created: + instance.loggerE.error("This Patient is created") + raise AttributeError + if type(value) != str: + instance.loggerE.error("wrong type") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count > 0: + instance.loggerE.error("Name contain numbers") + raise ValueError() + instance.__dict__[self.name] = value + + def __set_name__(self, owner, name): + self.name = name + + +class СheckBday: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if type(value) != str: + instance.loggerE.error("wrong type") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count != 8: + instance.loggerE.error("wrong type") + raise ValueError("Bad number") + year = "" + value[0:4] + # if 1920 > int(year) or int(year) > 2020: + # instance.loggerE.error("Your patient >100 years old?") + month = "" + for a in value[4:len(value) - 2]: + if not (a == "-") and not (a == " ") and not (a == "."): + month = month + a + day = "" + value[len(value) - 2:len(value)] + # if 0 > int(day) or int(day) > 31: + # instance.loggerE.error("max day in month - 31") + + year = year + "-" + month + "-" + day + if instance.created: + instance.loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = year + + def __set_name__(self, owner, name): + self.name = name + + +class CheckPhone: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if type(value) != str: + instance.loggerE.error("wrong type") + if value is not None: + str1 = "" + flag = False + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count < 11 or count > 11: + instance.loggerE.error("Check your number again") + raise ValueError("error numbers") + if value[0] == "+": + str1 = str1 + "8" + flag = True + else: + str1 = str1 + "8" + if value[0] != "8" and value[0] != "7" and value[0:2] != "+7": + instance.loggerE.error("number starts with (8) or (7)") + raise ValueError() + if flag: + for a in range(2, len(value)): + if 58 > ord(value[a]) > 47: + str1 = str1 + value[a] + else: + for a in range(1, len(value)): + if 58 > ord(value[a]) > 47: + str1 = str1 + value[a] + instance.__dict__[self.name] = str1 + if instance.created: + instance.loggerI.info("Данные успешно обновлены") + + def __set_name__(self, owner, name): + self.name = name + + +class Checkdoctype: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if value is not None: + if type(value) != str: + instance.loggerE.error("wrong type2") + if len(value) < 7: + instance.loggerE.error("small name of type") + if value != "паспорт" and value != "заграничный паспорт" and value != "водительское удостоверение": + instance.loggerE.error("Не опознанный тип") + raise ValueError("not") + if instance.created: + instance.loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = value + + def __set_name__(self, owner, name): + self.name = name + + +class Checkdocnumber: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if value is not None: + if type(value) != str: + instance.loggerE.error("wrong type3") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count != 9 and count != 10: + instance.loggerE.error("wrong type") + raise ValueError("Bad number") + if value is not None: + str1 = "" + for a in value: + if a != " " and a != "-" and a != "/": + str1 = str1 + a + if instance.created: + instance.loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = str1 + + def __set_name__(self, owner, name): + self.name = name + + class Patient: - def __init__(self, *args, **kwargs): - pass + created = False + first_name = CheckName() + last_name = CheckName() + birth_date = СheckBday() + phone = CheckPhone() + document_type = Checkdoctype() + document_id = Checkdocnumber() + loggerE = logging.getLogger("Errors") + loggerE.setLevel(logging.ERROR) + handler1 = logging.FileHandler('mistakes.txt', 'a', 'utf-8') + formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") + handler1.setFormatter(formatter) + loggerE.addHandler(handler1) + + loggerI = logging.getLogger("Info") + loggerI.setLevel(logging.INFO) + handler2 = logging.FileHandler('Info.txt', 'a', 'utf-8') + formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") + handler2.setFormatter(formatter) + loggerI.addHandler(handler2) + + def __init__(self, first_name=None, last_name=None, birth_date=None, phone=None, document_type=None, + document_id=None): + self.first_name = first_name + self.last_name = last_name + self.birth_date = birth_date + self.phone = phone + self.document_type = document_type + self.document_id = document_id + self.loggerI.info("you create a new Patient") + self.created = True + self._saved = False - def create(*args, **kwargs): - raise NotImplementedError() + @staticmethod + def create(*args): + return Patient(*args) def save(self): - pass + if not self._saved: + patient = [self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, + self.document_id] + FILENAME = "patiens.csv" + with open(FILENAME, "a", newline="",encoding='utf-8') as file: + writer = csv.writer(file) + # for a in self.patient: + writer.writerow(patient) + self._saved = True + self.loggerI.info("Patient succesfully created") + + def __str__(self): + return f"Patient: {self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id}" + + def __del__(self): + # self.handler2.removeFilter(self.formatter) + # self.handler1.removeFilter(self.formatter) + self.handler2.close() + self.handler1.close() + self.loggerI.removeHandler(self.handler2) + self.loggerE.removeHandler(self.handler1) class PatientCollection: - def __init__(self, log_file): - pass + value1 = 0 + islim = False + + def __init__(self, path_to_file): + if not os.path.exists(path_to_file): + raise ValueError("this file doesnt exist") + + def __iter__(self): + with open('patiens.csv','r',encoding='utf-8') as File: + reader = csv.reader(File) + for row in reader: + if self.value1 > 0 or self.islim == False: + a = Patient(*row) + self.value1 = self.value1 - 1 + yield a - def limit(self, n): - raise NotImplementedError() + def limit(self, value): + self.islim = True + self.value1 = value + return self.__iter__() diff --git a/tests/Info.txt b/tests/Info.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/mistakes.txt b/tests/mistakes.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/patiens.csv b/tests/patiens.csv new file mode 100644 index 0000000..c0ac33f --- /dev/null +++ b/tests/patiens.csv @@ -0,0 +1 @@ +Кондрат,Коловрат,1978-01-31,89032027936,водительское удостоверение,0000000000 From fbf68395dcd9ec0f4cd05568f59bac3faf1e3074 Mon Sep 17 00:00:00 2001 From: TurboFen <47735879+TurboFen@users.noreply.github.com> Date: Sun, 26 Apr 2020 00:33:14 +0300 Subject: [PATCH 2/6] Delete patient.py --- homework/patient.py | 238 -------------------------------------------- 1 file changed, 238 deletions(-) delete mode 100644 homework/patient.py diff --git a/homework/patient.py b/homework/patient.py deleted file mode 100644 index c7e1aaf..0000000 --- a/homework/patient.py +++ /dev/null @@ -1,238 +0,0 @@ -import logging -import csv -import os.path - - - -class CheckName: - - def __get__(self, instance, owner): - return instance.__dict__[self.name] - - def __set__(self, instance, value): - - if instance.created: - instance.loggerE.error("This Patient is created") - raise AttributeError - if type(value) != str: - instance.loggerE.error("wrong type") - count = 0 - for a in value: - if 47 < ord(a) < 58: - count = count + 1 - if count > 0: - instance.loggerE.error("Name contain numbers") - raise ValueError() - instance.__dict__[self.name] = value - - def __set_name__(self, owner, name): - self.name = name - - -class СheckBday: - def __get__(self, instance, owner): - return instance.__dict__[self.name] - - def __set__(self, instance, value): - if type(value) != str: - instance.loggerE.error("wrong type") - count = 0 - for a in value: - if 47 < ord(a) < 58: - count = count + 1 - if count != 8: - instance.loggerE.error("wrong type") - raise ValueError("Bad number") - year = "" + value[0:4] - # if 1920 > int(year) or int(year) > 2020: - # instance.loggerE.error("Your patient >100 years old?") - month = "" - for a in value[4:len(value) - 2]: - if not (a == "-") and not (a == " ") and not (a == "."): - month = month + a - day = "" + value[len(value) - 2:len(value)] - # if 0 > int(day) or int(day) > 31: - # instance.loggerE.error("max day in month - 31") - - year = year + "-" + month + "-" + day - if instance.created: - instance.loggerI.info("Данные успешно обновлены") - instance.__dict__[self.name] = year - - def __set_name__(self, owner, name): - self.name = name - - -class CheckPhone: - def __get__(self, instance, owner): - return instance.__dict__[self.name] - - def __set__(self, instance, value): - if type(value) != str: - instance.loggerE.error("wrong type") - if value is not None: - str1 = "" - flag = False - count = 0 - for a in value: - if 47 < ord(a) < 58: - count = count + 1 - if count < 11 or count > 11: - instance.loggerE.error("Check your number again") - raise ValueError("error numbers") - if value[0] == "+": - str1 = str1 + "8" - flag = True - else: - str1 = str1 + "8" - if value[0] != "8" and value[0] != "7" and value[0:2] != "+7": - instance.loggerE.error("number starts with (8) or (7)") - raise ValueError() - if flag: - for a in range(2, len(value)): - if 58 > ord(value[a]) > 47: - str1 = str1 + value[a] - else: - for a in range(1, len(value)): - if 58 > ord(value[a]) > 47: - str1 = str1 + value[a] - instance.__dict__[self.name] = str1 - if instance.created: - instance.loggerI.info("Данные успешно обновлены") - - def __set_name__(self, owner, name): - self.name = name - - -class Checkdoctype: - def __get__(self, instance, owner): - return instance.__dict__[self.name] - - def __set__(self, instance, value): - if value is not None: - if type(value) != str: - instance.loggerE.error("wrong type2") - if len(value) < 7: - instance.loggerE.error("small name of type") - if value != "паспорт" and value != "заграничный паспорт" and value != "водительское удостоверение": - instance.loggerE.error("Не опознанный тип") - raise ValueError("not") - if instance.created: - instance.loggerI.info("Данные успешно обновлены") - instance.__dict__[self.name] = value - - def __set_name__(self, owner, name): - self.name = name - - -class Checkdocnumber: - def __get__(self, instance, owner): - return instance.__dict__[self.name] - - def __set__(self, instance, value): - if value is not None: - if type(value) != str: - instance.loggerE.error("wrong type3") - count = 0 - for a in value: - if 47 < ord(a) < 58: - count = count + 1 - if count != 9 and count != 10: - instance.loggerE.error("wrong type") - raise ValueError("Bad number") - if value is not None: - str1 = "" - for a in value: - if a != " " and a != "-" and a != "/": - str1 = str1 + a - if instance.created: - instance.loggerI.info("Данные успешно обновлены") - instance.__dict__[self.name] = str1 - - def __set_name__(self, owner, name): - self.name = name - - -class Patient: - created = False - first_name = CheckName() - last_name = CheckName() - birth_date = СheckBday() - phone = CheckPhone() - document_type = Checkdoctype() - document_id = Checkdocnumber() - loggerE = logging.getLogger("Errors") - loggerE.setLevel(logging.ERROR) - handler1 = logging.FileHandler('mistakes.txt', 'a', 'utf-8') - formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") - handler1.setFormatter(formatter) - loggerE.addHandler(handler1) - - loggerI = logging.getLogger("Info") - loggerI.setLevel(logging.INFO) - handler2 = logging.FileHandler('Info.txt', 'a', 'utf-8') - formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") - handler2.setFormatter(formatter) - loggerI.addHandler(handler2) - - def __init__(self, first_name=None, last_name=None, birth_date=None, phone=None, document_type=None, - document_id=None): - self.first_name = first_name - self.last_name = last_name - self.birth_date = birth_date - self.phone = phone - self.document_type = document_type - self.document_id = document_id - self.loggerI.info("you create a new Patient") - self.created = True - self._saved = False - - @staticmethod - def create(*args): - return Patient(*args) - - def save(self): - if not self._saved: - patient = [self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, - self.document_id] - FILENAME = "patiens.csv" - with open(FILENAME, "a", newline="",encoding='utf-8') as file: - writer = csv.writer(file) - # for a in self.patient: - writer.writerow(patient) - self._saved = True - self.loggerI.info("Patient succesfully created") - - def __str__(self): - return f"Patient: {self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id}" - - def __del__(self): - # self.handler2.removeFilter(self.formatter) - # self.handler1.removeFilter(self.formatter) - self.handler2.close() - self.handler1.close() - self.loggerI.removeHandler(self.handler2) - self.loggerE.removeHandler(self.handler1) - - -class PatientCollection: - value1 = 0 - islim = False - - def __init__(self, path_to_file): - if not os.path.exists(path_to_file): - raise ValueError("this file doesnt exist") - - def __iter__(self): - with open('patiens.csv','r',encoding='utf-8') as File: - reader = csv.reader(File) - for row in reader: - if self.value1 > 0 or self.islim == False: - a = Patient(*row) - self.value1 = self.value1 - 1 - yield a - - def limit(self, value): - self.islim = True - self.value1 = value - return self.__iter__() From 5775cb9877526e196883ee885efc4e5a9bb917a0 Mon Sep 17 00:00:00 2001 From: TurboFen <47735879+TurboFen@users.noreply.github.com> Date: Sun, 26 Apr 2020 00:33:36 +0300 Subject: [PATCH 3/6] =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5=20=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homework/forlog.py | 7 ++ homework/patient.py | 224 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 231 insertions(+) create mode 100644 homework/forlog.py create mode 100644 homework/patient.py diff --git a/homework/forlog.py b/homework/forlog.py new file mode 100644 index 0000000..142a9e5 --- /dev/null +++ b/homework/forlog.py @@ -0,0 +1,7 @@ +import logging + +loggerE = logging.getLogger("Errors") +loggerE.setLevel(logging.ERROR) +formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") +loggerI = logging.getLogger("Info") +loggerI.setLevel(logging.INFO) diff --git a/homework/patient.py b/homework/patient.py new file mode 100644 index 0000000..a340ddb --- /dev/null +++ b/homework/patient.py @@ -0,0 +1,224 @@ +import logging +import csv +import os.path +from homework.forlog import loggerE, loggerI, formatter + + +class CheckName: + + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + + if instance.created: + loggerE.error("This Patient is created") + raise AttributeError + if type(value) != str: + loggerE.error("wrong type") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count > 0: + loggerE.error("Name contain numbers") + raise ValueError() + instance.__dict__[self.name] = value + + def __set_name__(self, owner, name): + self.name = name + + +class СheckBday: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if type(value) != str: + loggerE.error("wrong type") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count != 8: + loggerE.error("wrong type") + raise ValueError("Bad number") + year = "" + value[0:4] + + month = "" + for a in value[4:len(value) - 2]: + if not (a == "-") and not (a == " ") and not (a == "."): + month = month + a + day = "" + value[len(value) - 2:len(value)] + + year = year + "-" + month + "-" + day + if instance.created: + loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = year + + def __set_name__(self, owner, name): + self.name = name + + +class CheckPhone: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if type(value) != str: + loggerE.error("wrong type") + if value is not None: + str1 = "" + flag = False + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count < 11 or count > 11: + loggerE.error("Check your number again") + raise ValueError("error numbers") + if value[0] == "+": + str1 = str1 + "8" + flag = True + else: + str1 = str1 + "8" + if value[0] != "8" and value[0] != "7" and value[0:2] != "+7": + loggerE.error("number starts with (8) or (7)") + raise ValueError() + if flag: + for a in range(2, len(value)): + if 58 > ord(value[a]) > 47: + str1 = str1 + value[a] + else: + for a in range(1, len(value)): + if 58 > ord(value[a]) > 47: + str1 = str1 + value[a] + instance.__dict__[self.name] = str1 + if instance.created: + loggerI.info("Данные успешно обновлены") + + def __set_name__(self, owner, name): + self.name = name + + +class Checkdoctype: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if value is not None: + if type(value) != str: + loggerE.error("wrong type2") + if len(value) < 7: + loggerE.error("small name of type") + if value != "паспорт" and value != "заграничный паспорт" and value != "водительское удостоверение": + loggerE.error("Не опознанный тип") + raise ValueError("not") + if instance.created: + loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = value + + def __set_name__(self, owner, name): + self.name = name + + +class Checkdocnumber: + def __get__(self, instance, owner): + return instance.__dict__[self.name] + + def __set__(self, instance, value): + if value is not None: + if type(value) != str: + loggerE.error("wrong type3") + count = 0 + for a in value: + if 47 < ord(a) < 58: + count = count + 1 + if count != 9 and count != 10: + loggerE.error("wrong type") + raise ValueError("Bad number") + if value is not None: + str1 = "" + for a in value: + if a != " " and a != "-" and a != "/": + str1 = str1 + a + if instance.created: + loggerI.info("Данные успешно обновлены") + instance.__dict__[self.name] = str1 + + def __set_name__(self, owner, name): + self.name = name + + +class Patient: + created = False + first_name = CheckName() + last_name = CheckName() + birth_date = СheckBday() + phone = CheckPhone() + document_type = Checkdoctype() + document_id = Checkdocnumber() + handler1 = logging.FileHandler('mistakes.txt', 'a', 'utf-8') + handler1.setFormatter(formatter) + loggerE.addHandler(handler1) + handler2 = logging.FileHandler('Info.txt', 'a', 'utf-8') + handler2.setFormatter(formatter) + loggerI.addHandler(handler2) + + def __init__(self, first_name=None, last_name=None, birth_date=None, phone=None, document_type=None, + document_id=None): + self.first_name = first_name + self.last_name = last_name + self.birth_date = birth_date + self.phone = phone + self.document_type = document_type + self.document_id = document_id + loggerI.info("you create a new Patient") + self.created = True + self._saved = False + + @staticmethod + def create(*args): + return Patient(*args) + + def save(self): + if not self._saved: + patient = [self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, + self.document_id] + FILENAME = "patiens.csv" + with open(FILENAME, "a", newline="", encoding='utf-8') as file: + writer = csv.writer(file) + # for a in self.patient: + writer.writerow(patient) + self._saved = True + loggerI.info("Patient succesfully created") + + def __str__(self): + return f"Patient: {self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id}" + + def __del__(self): + self.handler2.close() + self.handler1.close() + + +class PatientCollection: + value1 = 0 + islim = False + + def __init__(self, path_to_file): + if not os.path.exists(path_to_file): + raise ValueError("this file doesnt exist") + + def __iter__(self): + with open('patiens.csv', 'r', encoding='utf-8') as File: + reader = csv.reader(File) + for row in reader: + if self.value1 > 0 or self.islim == False: + a = Patient(*row) + self.value1 = self.value1 - 1 + yield a + + def limit(self, value): + self.islim = True + self.value1 = value + return self.__iter__() From 725ed1855085d5705e7e088b4817114cb1308135 Mon Sep 17 00:00:00 2001 From: Alexander Novak <47735879+TurboFen@users.noreply.github.com> Date: Fri, 1 May 2020 08:17:11 +0300 Subject: [PATCH 4/6] =?UTF-8?q?=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D0=B5=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_patient.py | 390 +++++++++++++++++++++--------------------- 1 file changed, 195 insertions(+), 195 deletions(-) diff --git a/tests/test_patient.py b/tests/test_patient.py index 125bd59..813a3af 100644 --- a/tests/test_patient.py +++ b/tests/test_patient.py @@ -1,195 +1,195 @@ -import functools -import os -from datetime import datetime -import itertools - -import pytest - -from homework.config import GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH, PHONE_FORMAT, PASSPORT_TYPE, PASSPORT_FORMAT, \ - INTERNATIONAL_PASSPORT_FORMAT, INTERNATIONAL_PASSPORT_TYPE, DRIVER_LICENSE_TYPE, DRIVER_LICENSE_FORMAT -from homework.patient import Patient -from tests.constants import GOOD_PARAMS, OTHER_GOOD_PARAMS, WRONG_PARAMS, PATIENT_FIELDS - - -def get_len(file): - with open(file, encoding='utf-8') as f: - return len(f.readlines()) - - -def check_log_size(log, increased=False): - def deco(func): - log_map = {"error": ERROR_LOG_FILE, "good": GOOD_LOG_FILE, "csv": CSV_PATH} - log_path = log_map.get(log, log) - @functools.wraps(func) - def wrapper(*args, **kwargs): - log_len = get_len(log_path) - result = func(*args, **kwargs) - new_len = get_len(log_path) - assert new_len > log_len if increased else new_len == log_len, f"Wrong {log} file length" - return result - return wrapper - return deco - - -def setup(): - for file in [GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH]: - with open(file, 'w', encoding='utf-8') as f: - f.write('') - - -def teardown(): - for file in [GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH]: - os.remove(file) - - -@check_log_size("error") -@check_log_size("good", increased=True) -def test_creation_all_good_params(): - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, PASSPORT_TYPE, PASSPORT_FORMAT) - assert patient.first_name == "Кондрат", "Wrong attribute first_name" - assert patient.last_name == "Коловрат", "Wrong attribute last_name" - assert patient.birth_date == "1978-01-31" or patient.birth_date == datetime(1978, 1, 31), \ - "Wrong attribute birth_date" - assert patient.phone == PHONE_FORMAT, "Wrong attribute phone" - assert patient.document_type == PASSPORT_TYPE, "Wrong attribute document_type" - assert patient.document_id == PASSPORT_FORMAT, "Wrong attribute document_id" - - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, INTERNATIONAL_PASSPORT_TYPE, - INTERNATIONAL_PASSPORT_FORMAT) - assert patient.document_type == INTERNATIONAL_PASSPORT_TYPE, "Wrong attribute document_type" - assert patient.document_id == INTERNATIONAL_PASSPORT_FORMAT, "Wrong attribute document_id" - - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, DRIVER_LICENSE_TYPE, DRIVER_LICENSE_FORMAT) - assert patient.document_type == DRIVER_LICENSE_TYPE, "Wrong attribute document_type" - assert patient.document_id == DRIVER_LICENSE_FORMAT, "Wrong attribute document_id" - - -@pytest.mark.parametrize('default,new', itertools.permutations(["(916)", "916", "-916-"], 2)) -@check_log_size("error") -@check_log_size("good", increased=True) -def test_creation_acceptable_phone(default, new): - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT.replace(default, new), - PASSPORT_TYPE, PASSPORT_FORMAT) - assert patient.phone == PHONE_FORMAT, "Wrong attribute phone" - - -@pytest.mark.parametrize('passport', ("00 00 000 000", "0000-000000", "0 0 0 0 0 0 0 0 0 0", "0000/000-000")) -@check_log_size("error") -@check_log_size("good", increased=True) -def test_creation_acceptable_passport(passport): - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, PASSPORT_TYPE, passport) - assert patient.document_id == PASSPORT_FORMAT, "Wrong attribute document_id" - - -@pytest.mark.parametrize('passport', ("00 0000000", "00-0000000", "0 0 0 0 0 0 0 0 0", "00/000-0000")) -@check_log_size("error") -@check_log_size("good", increased=True) -def test_creation_acceptable_international_passport(passport): - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, INTERNATIONAL_PASSPORT_TYPE, passport) - assert patient.document_id == INTERNATIONAL_PASSPORT_FORMAT, "Wrong attribute document_id" - - -@pytest.mark.parametrize('driver_license', ("00 00 000 000", "0000-000000", "0 0 0 0 0 0 0 0 0 0", "0000/000000")) -@check_log_size("error") -@check_log_size("good", increased=True) -def test_creation_acceptable_driver_license(driver_license): - patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, DRIVER_LICENSE_TYPE, driver_license) - assert patient.document_id == DRIVER_LICENSE_FORMAT, "Wrong attribute document_id" - - -# неверный тип -@pytest.mark.parametrize("i", list(range(len(GOOD_PARAMS)))) -@check_log_size("error", increased=True) -@check_log_size("good") -def test_creation_wrong_type_params(i): - try: - Patient(*GOOD_PARAMS[:i], 1.8, *GOOD_PARAMS[i+1:]) - assert False, f"TypeError for {PATIENT_FIELDS[i]} not invoked" - except TypeError: - assert True - - -# неверные значения -@pytest.mark.parametrize("i", list(range(len(GOOD_PARAMS)))) -@check_log_size("error", increased=True) -@check_log_size("good") -def test_creation_wrong_params(i): - try: - Patient(*GOOD_PARAMS[:i], WRONG_PARAMS[i], *GOOD_PARAMS[i+1:]) - assert False, f"ValueError for {PATIENT_FIELDS[i]} not invoked" - except ValueError: - assert True - - -# метод create -@check_log_size("error") -@check_log_size("good", increased=True) -def test_create_method_good_params(): - patient = Patient.create(*GOOD_PARAMS) - for param, field in zip(GOOD_PARAMS, PATIENT_FIELDS): - assert getattr(patient, field) in (param, datetime(1978, 1, 31)), f"Wrong attribute {field}" - - -# обновление параметров -@pytest.mark.parametrize("patient,field,param", zip( - [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[:2]), - PATIENT_FIELDS[:2], - GOOD_PARAMS[:2] -)) -@check_log_size("error", increased=True) -@check_log_size("good") -def test_names_assignment(patient, field, param): - try: - setattr(patient, field, param) - assert False, f"Attribute error should be invoked for {field} changing" - except AttributeError: - assert True - - -@pytest.mark.parametrize("patient,field,param", zip( - [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), - PATIENT_FIELDS[2:], - GOOD_PARAMS[2:] -)) -@check_log_size("error") -@check_log_size("good", increased=True) -def test_good_params_assignment(patient, field, param): - setattr(patient, field, param) - assert getattr(patient, field) == param, f"Attribute {field} did not change" - - -@pytest.mark.parametrize("patient,field,param", zip( - [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), - PATIENT_FIELDS[2:], - [1.4] * len(PATIENT_FIELDS[2:]) -)) -@check_log_size("error", increased=True) -@check_log_size("good") -def test_wrong_type_assignment(patient, field, param): - try: - setattr(patient, field, param) - assert False, f"TypeError for {field} assignment not invoked" - except TypeError: - assert True - - -@pytest.mark.parametrize("patient,field,param", zip( - [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), - PATIENT_FIELDS[2:], - WRONG_PARAMS[2:] -)) -@check_log_size("error", increased=True) -@check_log_size("good") -def test_wrong_type_assignment(patient, field, param): - try: - setattr(patient, field, param) - assert False, f"ValueError for {field} assignment not invoked" - except ValueError: - assert True - - -# метод save -@check_log_size("csv", increased=True) -def test_save(): - patient = Patient(*GOOD_PARAMS) - patient.save() +import functools +import os +from datetime import datetime +import itertools + +import pytest + +from homework.config import GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH, PHONE_FORMAT, PASSPORT_TYPE, PASSPORT_FORMAT, \ + INTERNATIONAL_PASSPORT_FORMAT, INTERNATIONAL_PASSPORT_TYPE, DRIVER_LICENSE_TYPE, DRIVER_LICENSE_FORMAT +from homework.patient import Patient +from tests.constants import GOOD_PARAMS, OTHER_GOOD_PARAMS, WRONG_PARAMS, PATIENT_FIELDS + + +def get_len(file): + with open(file, encoding='utf-8') as f: + return len(f.readlines()) + + +def check_log_size(log, increased=False): + def deco(func): + log_map = {"error": ERROR_LOG_FILE, "good": GOOD_LOG_FILE, "csv": CSV_PATH} + log_path = log_map.get(log, log) + @functools.wraps(func) + def wrapper(*args, **kwargs): + log_len = get_len(log_path) + result = func(*args, **kwargs) + new_len = get_len(log_path) + assert new_len > log_len if increased else new_len == log_len, f"Wrong {log} file length" + return result + return wrapper + return deco + + +def setup_module(__main__): + for file in [GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH]: + with open(file, 'w', encoding='utf-8') as f: + f.write('') + + +def teardown_module(__name__): + for file in [GOOD_LOG_FILE, ERROR_LOG_FILE, CSV_PATH]: + os.remove(file) + + +@check_log_size("error") +@check_log_size("good", increased=True) +def test_creation_all_good_params(): + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, PASSPORT_TYPE, PASSPORT_FORMAT) + assert patient.first_name == "Кондрат", "Wrong attribute first_name" + assert patient.last_name == "Коловрат", "Wrong attribute last_name" + assert patient.birth_date == "1978-01-31" or patient.birth_date == datetime(1978, 1, 31), \ + "Wrong attribute birth_date" + assert patient.phone == PHONE_FORMAT, "Wrong attribute phone" + assert patient.document_type == PASSPORT_TYPE, "Wrong attribute document_type" + assert patient.document_id == PASSPORT_FORMAT, "Wrong attribute document_id" + + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, INTERNATIONAL_PASSPORT_TYPE, + INTERNATIONAL_PASSPORT_FORMAT) + assert patient.document_type == INTERNATIONAL_PASSPORT_TYPE, "Wrong attribute document_type" + assert patient.document_id == INTERNATIONAL_PASSPORT_FORMAT, "Wrong attribute document_id" + + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, DRIVER_LICENSE_TYPE, DRIVER_LICENSE_FORMAT) + assert patient.document_type == DRIVER_LICENSE_TYPE, "Wrong attribute document_type" + assert patient.document_id == DRIVER_LICENSE_FORMAT, "Wrong attribute document_id" + + +@pytest.mark.parametrize('default,new', itertools.permutations(["(916)", "916", "-916-"], 2)) +@check_log_size("error") +@check_log_size("good", increased=True) +def test_creation_acceptable_phone(default, new): + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT.replace(default, new), + PASSPORT_TYPE, PASSPORT_FORMAT) + assert patient.phone == PHONE_FORMAT, "Wrong attribute phone" + + +@pytest.mark.parametrize('passport', ("00 00 000 000", "0000-000000", "0 0 0 0 0 0 0 0 0 0", "0000/000-000")) +@check_log_size("error") +@check_log_size("good", increased=True) +def test_creation_acceptable_passport(passport): + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, PASSPORT_TYPE, passport) + assert patient.document_id == PASSPORT_FORMAT, "Wrong attribute document_id" + + +@pytest.mark.parametrize('passport', ("00 0000000", "00-0000000", "0 0 0 0 0 0 0 0 0", "00/000-0000")) +@check_log_size("error") +@check_log_size("good", increased=True) +def test_creation_acceptable_international_passport(passport): + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, INTERNATIONAL_PASSPORT_TYPE, passport) + assert patient.document_id == INTERNATIONAL_PASSPORT_FORMAT, "Wrong attribute document_id" + + +@pytest.mark.parametrize('driver_license', ("00 00 000 000", "0000-000000", "0 0 0 0 0 0 0 0 0 0", "0000/000000")) +@check_log_size("error") +@check_log_size("good", increased=True) +def test_creation_acceptable_driver_license(driver_license): + patient = Patient("Кондрат", "Коловрат", "1978-01-31", PHONE_FORMAT, DRIVER_LICENSE_TYPE, driver_license) + assert patient.document_id == DRIVER_LICENSE_FORMAT, "Wrong attribute document_id" + + +# неверный тип +@pytest.mark.parametrize("i", list(range(len(GOOD_PARAMS)))) +@check_log_size("error", increased=True) +@check_log_size("good") +def test_creation_wrong_type_params(i): + try: + Patient(*GOOD_PARAMS[:i], 1.8, *GOOD_PARAMS[i+1:]) + assert False, f"TypeError for {PATIENT_FIELDS[i]} not invoked" + except TypeError: + assert True + + +# неверные значения +@pytest.mark.parametrize("i", list(range(len(GOOD_PARAMS)))) +@check_log_size("error", increased=True) +@check_log_size("good") +def test_creation_wrong_params(i): + try: + Patient(*GOOD_PARAMS[:i], WRONG_PARAMS[i], *GOOD_PARAMS[i+1:]) + assert False, f"ValueError for {PATIENT_FIELDS[i]} not invoked" + except ValueError: + assert True + + +# метод create +@check_log_size("error") +@check_log_size("good", increased=True) +def test_create_method_good_params(): + patient = Patient.create(*GOOD_PARAMS) + for param, field in zip(GOOD_PARAMS, PATIENT_FIELDS): + assert getattr(patient, field) in (param, datetime(1978, 1, 31)), f"Wrong attribute {field}" + + +# обновление параметров +@pytest.mark.parametrize("patient,field,param", zip( + [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[:2]), + PATIENT_FIELDS[:2], + GOOD_PARAMS[:2] +)) +@check_log_size("error", increased=True) +@check_log_size("good") +def test_names_assignment(patient, field, param): + try: + setattr(patient, field, param) + assert False, f"Attribute error should be invoked for {field} changing" + except AttributeError: + assert True + + +@pytest.mark.parametrize("patient,field,param", zip( + [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), + PATIENT_FIELDS[2:], + GOOD_PARAMS[2:] +)) +@check_log_size("error") +@check_log_size("good", increased=True) +def test_good_params_assignment(patient, field, param): + setattr(patient, field, param) + assert getattr(patient, field) == param, f"Attribute {field} did not change" + + +@pytest.mark.parametrize("patient,field,param", zip( + [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), + PATIENT_FIELDS[2:], + [1.4] * len(PATIENT_FIELDS[2:]) +)) +@check_log_size("error", increased=True) +@check_log_size("good") +def test_wrong_type_assignment(patient, field, param): + try: + setattr(patient, field, param) + assert False, f"TypeError for {field} assignment not invoked" + except TypeError: + assert True + + +@pytest.mark.parametrize("patient,field,param", zip( + [Patient(*OTHER_GOOD_PARAMS)] * len(PATIENT_FIELDS[2:]), + PATIENT_FIELDS[2:], + WRONG_PARAMS[2:] +)) +@check_log_size("error", increased=True) +@check_log_size("good") +def test_wrong_value_assignment(patient, field, param): + try: + setattr(patient, field, param) + assert False, f"ValueError for {field} assignment not invoked" + except ValueError: + assert True + + +# метод save +@check_log_size("csv", increased=True) +def test_save(): + patient = Patient(*GOOD_PARAMS) + patient.save() From 1cca6a07b2ecd1849974c32840e1664a865e5d5e Mon Sep 17 00:00:00 2001 From: TurboFen Date: Sun, 10 May 2020 18:32:47 +0300 Subject: [PATCH 5/6] DZ3 --- homework/check.py | 13 ++++ homework/cli.py | 48 ++++++++++++++ homework/config.py | 1 - homework/patient.py | 150 +++++++++++++++++++++++++++----------------- 4 files changed, 154 insertions(+), 58 deletions(-) create mode 100644 homework/check.py create mode 100644 homework/cli.py diff --git a/homework/check.py b/homework/check.py new file mode 100644 index 0000000..77e4163 --- /dev/null +++ b/homework/check.py @@ -0,0 +1,13 @@ +import logging + +loggerE = logging.getLogger("Errors") +loggerE.setLevel(logging.ERROR) +formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") +loggerI = logging.getLogger("Info") +loggerI.setLevel(logging.INFO) +handler1 = logging.FileHandler('mistakes.txt', 'a', 'utf-8') +handler1.setFormatter(formatter) +loggerE.addHandler(handler1) +handler2 = logging.FileHandler('Info.txt', 'a', 'utf-8') +handler2.setFormatter(formatter) +loggerI.addHandler(handler2) \ No newline at end of file diff --git a/homework/cli.py b/homework/cli.py new file mode 100644 index 0000000..351d431 --- /dev/null +++ b/homework/cli.py @@ -0,0 +1,48 @@ +import click +from homework.patient import * + +@click.group() +def cli(): + pass + + +@cli.command() +@click.argument('first_name') +@click.argument('last_name') +@click.option('--birth_date', '-a') +@click.option('--phone', '-a') +@click.option('--document_type', '-a') +@click.option('--document_id', '-a') +def create(first_name, last_name, birth_date, phone, document_type, document_id): + test = Patient(first_name, last_name, birth_date, phone, document_type, document_id) + test.save() + click.echo("Создан новый пациент") + + +@cli.command() +@click.argument('value' , default = 10 ) +def show(value): + collection = PatientCollection() + if value == 10: + for patient in collection.limit(value): + click.echo(patient) + else: + for patient in collection.limit(value): + click.echo(patient) + +@cli.command() +def count(): + count = 0 + var = pymysql.connect(host='localhost', port=3306, user='root', passwd='passwd', + db='forpat') + conn = var.cursor(pymysql.cursors.DictCursor) + conn.execute("SELECT * FROM patiens") + rows = conn.fetchall() + for row in rows: + count = count + 1 + conn.close() + var.close() + click.echo(count) + +if __name__ == '__main__': + cli() \ No newline at end of file diff --git a/homework/config.py b/homework/config.py index f3e83ef..49a7af5 100644 --- a/homework/config.py +++ b/homework/config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- GOOD_LOG_FILE = "Info.txt" ERROR_LOG_FILE = "mistakes.txt" CSV_PATH = "patiens.csv" diff --git a/homework/patient.py b/homework/patient.py index a340ddb..2b55caf 100644 --- a/homework/patient.py +++ b/homework/patient.py @@ -1,7 +1,43 @@ import logging import csv import os.path -from homework.forlog import loggerE, loggerI, formatter +import pymysql +from homework.check import loggerE, loggerI, formatter, handler1, handler2 + + +def my_logging_decorator(func): + def wrapper(self, instance, value): + try: + func(self, instance, value) + except ValueError: + loggerE.error("Error") + raise ValueError + except AssertionError: + loggerE.error("Error") + raise AssertionError + else: + if instance.created: + loggerI.info("Данные успешно обновлены") + + return wrapper + + +def my_logging_decorator_patient(func): + def wrapper(self, first_name, last_name, birth_date, phone, document_type, document_id): + func(self, first_name, last_name, birth_date, phone, document_type, document_id) + loggerI.info(self.logi) + self.logi = "" + + return wrapper + + +def my_logging_decorator_save(func): + def wrapper(self): + func(self) + loggerI.info(self.logi) + self.logi = "" + + return wrapper class CheckName: @@ -9,19 +45,19 @@ class CheckName: def __get__(self, instance, owner): return instance.__dict__[self.name] + @my_logging_decorator def __set__(self, instance, value): if instance.created: - loggerE.error("This Patient is created") raise AttributeError if type(value) != str: - loggerE.error("wrong type") + raise ValueError() count = 0 for a in value: if 47 < ord(a) < 58: count = count + 1 if count > 0: - loggerE.error("Name contain numbers") + instance.loge = "Name contain numbers" raise ValueError() instance.__dict__[self.name] = value @@ -33,15 +69,15 @@ class СheckBday: def __get__(self, instance, owner): return instance.__dict__[self.name] + @my_logging_decorator def __set__(self, instance, value): if type(value) != str: - loggerE.error("wrong type") + raise ValueError() count = 0 for a in value: if 47 < ord(a) < 58: count = count + 1 if count != 8: - loggerE.error("wrong type") raise ValueError("Bad number") year = "" + value[0:4] @@ -53,7 +89,7 @@ def __set__(self, instance, value): year = year + "-" + month + "-" + day if instance.created: - loggerI.info("Данные успешно обновлены") + instance.logi = "Данные успешно обновлены" instance.__dict__[self.name] = year def __set_name__(self, owner, name): @@ -64,9 +100,10 @@ class CheckPhone: def __get__(self, instance, owner): return instance.__dict__[self.name] + @my_logging_decorator def __set__(self, instance, value): if type(value) != str: - loggerE.error("wrong type") + raise ValueError if value is not None: str1 = "" flag = False @@ -75,16 +112,14 @@ def __set__(self, instance, value): if 47 < ord(a) < 58: count = count + 1 if count < 11 or count > 11: - loggerE.error("Check your number again") - raise ValueError("error numbers") + raise ValueError if value[0] == "+": str1 = str1 + "8" flag = True else: str1 = str1 + "8" if value[0] != "8" and value[0] != "7" and value[0:2] != "+7": - loggerE.error("number starts with (8) or (7)") - raise ValueError() + raise ValueError if flag: for a in range(2, len(value)): if 58 > ord(value[a]) > 47: @@ -95,7 +130,7 @@ def __set__(self, instance, value): str1 = str1 + value[a] instance.__dict__[self.name] = str1 if instance.created: - loggerI.info("Данные успешно обновлены") + instance.logi = "Данные успешно обновлены" def __set_name__(self, owner, name): self.name = name @@ -105,17 +140,17 @@ class Checkdoctype: def __get__(self, instance, owner): return instance.__dict__[self.name] + @my_logging_decorator def __set__(self, instance, value): if value is not None: if type(value) != str: - loggerE.error("wrong type2") + instance.loge = "wrong type2" if len(value) < 7: - loggerE.error("small name of type") + instance.loge = "small name of type" if value != "паспорт" and value != "заграничный паспорт" and value != "водительское удостоверение": - loggerE.error("Не опознанный тип") - raise ValueError("not") + raise ValueError if instance.created: - loggerI.info("Данные успешно обновлены") + instance.logi = "Данные успешно обновлены" instance.__dict__[self.name] = value def __set_name__(self, owner, name): @@ -126,24 +161,24 @@ class Checkdocnumber: def __get__(self, instance, owner): return instance.__dict__[self.name] + @my_logging_decorator def __set__(self, instance, value): if value is not None: if type(value) != str: - loggerE.error("wrong type3") + instance.loge = "wrong type3" count = 0 for a in value: if 47 < ord(a) < 58: count = count + 1 if count != 9 and count != 10: - loggerE.error("wrong type") - raise ValueError("Bad number") + raise ValueError if value is not None: str1 = "" for a in value: if a != " " and a != "-" and a != "/": str1 = str1 + a if instance.created: - loggerI.info("Данные успешно обновлены") + instance.logi = "Данные успешно обновлены" instance.__dict__[self.name] = str1 def __set_name__(self, owner, name): @@ -152,71 +187,72 @@ def __set_name__(self, owner, name): class Patient: created = False + first_name = CheckName() last_name = CheckName() birth_date = СheckBday() phone = CheckPhone() document_type = Checkdoctype() document_id = Checkdocnumber() - handler1 = logging.FileHandler('mistakes.txt', 'a', 'utf-8') - handler1.setFormatter(formatter) - loggerE.addHandler(handler1) - handler2 = logging.FileHandler('Info.txt', 'a', 'utf-8') - handler2.setFormatter(formatter) - loggerI.addHandler(handler2) - - def __init__(self, first_name=None, last_name=None, birth_date=None, phone=None, document_type=None, - document_id=None): + logi = "" + loge = "" + + @my_logging_decorator_patient + def __init__(self, first_name, last_name, birth_date, phone, document_type, document_id): self.first_name = first_name self.last_name = last_name self.birth_date = birth_date self.phone = phone self.document_type = document_type self.document_id = document_id - loggerI.info("you create a new Patient") + self.logi = "you create a new Patient" self.created = True self._saved = False @staticmethod - def create(*args): - return Patient(*args) + def create(first_name, last_name, birth_date, phone, document_type, document_id): + return Patient(first_name, last_name, birth_date, phone, document_type, document_id) + @my_logging_decorator_save def save(self): if not self._saved: - patient = [self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, - self.document_id] - FILENAME = "patiens.csv" - with open(FILENAME, "a", newline="", encoding='utf-8') as file: - writer = csv.writer(file) - # for a in self.patient: - writer.writerow(patient) - self._saved = True - loggerI.info("Patient succesfully created") + var = pymysql.connect(host='localhost', port=3306, user='root', passwd='passwd', + db='forpat') + conn = var.cursor(pymysql.cursors.DictCursor) + sql = "INSERT INTO patiens (first_name, last_name, birth_date, phone, document_type, document_id) VALUES (%s, %s, %s, %s, %s, %s)" + val = (self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id) + conn.execute(sql, val) + self._saved = True + self.logi = "Patient succesfully saved" + var.commit() + conn.close() + var.close() def __str__(self): return f"Patient: {self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id}" - def __del__(self): - self.handler2.close() - self.handler1.close() - class PatientCollection: value1 = 0 islim = False - def __init__(self, path_to_file): - if not os.path.exists(path_to_file): - raise ValueError("this file doesnt exist") + def __init__(self): + pass def __iter__(self): - with open('patiens.csv', 'r', encoding='utf-8') as File: - reader = csv.reader(File) - for row in reader: - if self.value1 > 0 or self.islim == False: - a = Patient(*row) - self.value1 = self.value1 - 1 - yield a + var = pymysql.connect(host='localhost', port=3306, user='root', passwd='Vfkmdbyfb 0 or self.islim == False: + var.commit() + a = Patient(**row) + self.value1 = self.value1 - 1 + yield a + conn.close() + var.close() def limit(self, value): self.islim = True From d215c5653f0a4ea017531b25eefdd4a3f1aefe2b Mon Sep 17 00:00:00 2001 From: TurboFen Date: Sun, 10 May 2020 18:39:55 +0300 Subject: [PATCH 6/6] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homework/forlog.py | 7 ------- homework/patient.py | 8 +++----- 2 files changed, 3 insertions(+), 12 deletions(-) delete mode 100644 homework/forlog.py diff --git a/homework/forlog.py b/homework/forlog.py deleted file mode 100644 index 142a9e5..0000000 --- a/homework/forlog.py +++ /dev/null @@ -1,7 +0,0 @@ -import logging - -loggerE = logging.getLogger("Errors") -loggerE.setLevel(logging.ERROR) -formatter = logging.Formatter("%(filename)s %(name)s %(funcName)s [%(asctime)s] %(message)s") -loggerI = logging.getLogger("Info") -loggerI.setLevel(logging.INFO) diff --git a/homework/patient.py b/homework/patient.py index 2b55caf..a1a77e4 100644 --- a/homework/patient.py +++ b/homework/patient.py @@ -57,7 +57,6 @@ def __set__(self, instance, value): if 47 < ord(a) < 58: count = count + 1 if count > 0: - instance.loge = "Name contain numbers" raise ValueError() instance.__dict__[self.name] = value @@ -144,9 +143,9 @@ def __get__(self, instance, owner): def __set__(self, instance, value): if value is not None: if type(value) != str: - instance.loge = "wrong type2" + raise ValueError if len(value) < 7: - instance.loge = "small name of type" + raise ValueError if value != "паспорт" and value != "заграничный паспорт" and value != "водительское удостоверение": raise ValueError if instance.created: @@ -165,7 +164,7 @@ def __get__(self, instance, owner): def __set__(self, instance, value): if value is not None: if type(value) != str: - instance.loge = "wrong type3" + raise ValueError count = 0 for a in value: if 47 < ord(a) < 58: @@ -195,7 +194,6 @@ class Patient: document_type = Checkdoctype() document_id = Checkdocnumber() logi = "" - loge = "" @my_logging_decorator_patient def __init__(self, first_name, last_name, birth_date, phone, document_type, document_id):