Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions homework/DataIsValid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
from copy import deepcopy
from re import fullmatch, sub, search
# from homework.Log import validerr

def nameReal(name_):
pattern = "[0-9]"
name = sub(pattern, "", name_)
if len(name)==0:
return False
return name

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

логика объект/булево значение редко используется. Лучше либо True/False, либо объект/None




def dateIsReal(date):
year = int(date[:4])
if year < 1900 or year > 2020:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это всё проще сделать с помощью модуля datetime

# validerr.paterr.warning(["It should be: 1900<year<=2020. Your year: ", year])
return False

month = int(date[5:7])
if month < 0 or month > 12:
# validerr.paterr.warning(["It should be: 0<month<=12. Your month: ", month])
return False

day = int(date[8:])
if day < 1 or day > 31:
# validerr.paterr.warning(["It should be: 0<day<32. Your day: ", day])
return False

if month == 2 and day > 29:
# validerr.paterr.warning("In Feb only 28 or 29 days")
return False

if month == 2 and day == 29:
print("WOW!")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

воистину

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше всё-таки не велосипедить, потому что при такой логике 29 февраля может быть и в невисокосном годе

return date


def dateIsValid(date):
pattern1 = "\d{4}.\d{2}.\d{2}" # y-m-d
pattern2 = "\d{2}.\d{2}.\d{4}" # d-m-y
match1 = fullmatch(pattern1, date)
match2 = fullmatch(pattern2, date)
if match1:
return dateIsReal(date)
elif match2:
dateNew = deepcopy(date[len(date) - 4:])
dateNew = '-'.join([dateNew, date[len(date) - 7:len(date) - 5]])
dateNew = '-'.join([dateNew, date[:2]])
if dateIsReal(dateNew):
return dateNew
else:
return False
else:
return False

# print(dateIsReal("1978-01-05"))

def phoneIsValid( phone_):
pattern = "[^+,0,1,2,3,4,5,6,7,8,9]"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

\D

phone = sub(pattern, "", phone_)
if len(phone)<10:
return False
if phone[0] == '8' or phone[0]=='7':
phone = ''.join(['+7', phone[1:]])
elif not phone[0] == '+' or not phone[1] == '7':
# validerr.paterr.warning(["Only Russians numbers are valid. +7-xxx-xxx-xx-xx or 8-xxx-xxx-xx-xx. Your num: ", phone])
return False

if not len(phone) == 12:
# validerr.paterr.warning(["Only Russians numbers are valid. len !=12 . Your num: ", phone])
return False
if not (phone[2:5] == '495' or phone[2:5] == '499' or phone[2] == '9'):
# validerr.paterr.warning(["Only Russians numbers are valid. +7-499-... or +7-495-... or +7-9..-.... Your num: ", phone])
return False
return phone



def docTypeIsValid(doc_type):
if not isinstance(doc_type, str):
return False
doc_type = doc_type.lower()

passport = "паспорт"
passportruen = "gfcgjhn"
zPassport = "загран"
zpassportruen = "pfuhfy"
prav1 = "водительск"
prav1ruen = "djlbntkmcr"
prav2 = "права"
prav2ruen = "ghfdf"

if search(zPassport, doc_type) or search(zpassportruen, doc_type):
return "загран"
elif search(passport, doc_type) or search(passportruen, doc_type):
return "паспорт"
elif search(prav1, doc_type) or search(prav2, doc_type) or search(prav1ruen, doc_type) or search(prav2ruen,
doc_type):
return "права"

return False


def docIdIsValid(id, type=None):
pattern = "[^0,1,2,3,4,5,6,7,8,9]"
id = sub(pattern, "", id)
if len(id) == 10:
if type == "паспорт" or type == "права" or not type:
return id
else:
# validerr.paterr.warning(["Zpass - len ==9. In dr and pass-10. Your type: ", type, ". Your id: ", id])
return False
elif len(id) == 9 and (type == "загран" or not type):
# validerr.paterr.warning(["Zpass - len ==9. In dr and pass-10. Your type: ", type, ". Your id: ", id])
return id
else:
return False
126 changes: 126 additions & 0 deletions homework/Descriptor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
from homework.DataIsValid import *
# from homework.Log import validator,validerr

class Name:
def __get__(self, instance, owner):
return instance.__dict__[self.name]
# return instance.__dict__[self.name]

def __set__(self, instance, val):
if not isinstance(val, str):
instance.paterr.error('Invalid name.')
instance.paterr.error("Error. User was not created.")
raise TypeError("not str")
elif instance.created:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не думаю, что атрибут created должен быть обозначен как public

instance.paterr.error("You can't change name")
instance.paterr.error("Error. User was not created.")
raise AttributeError("can't change name")
# val = sub(" ", "-", val)
n = nameReal(val)
if not n:
instance.paterr.error("Wrong name")
instance.paterr.error("Error. User was not created.")
raise ValueError("wrong name")
instance.__dict__[self.name] = n
instance.patinfo.debug(["name is okey:", val])


def __set_name__(self, owner, name):
self.name = name



class Phone:
def __get__(self, instance, owner):
return instance.__dict__[self.name]

def __set__(self, instance, number):
if not isinstance(number, str):
instance.paterr.error('Invalid number.')
instance.paterr.error("Error. User was not created.")
raise TypeError("not str")
prov = phoneIsValid(number)
if not prov:
instance.paterr.error('Invalid number. +code-xxx-xxx-xx-xx')
instance.paterr.error("Error. User was not created.")
raise ValueError("phone error")
number = prov
instance.__dict__[self.name] = number
instance.patinfo.debug(["number is okey: ", number])
if instance.created:
instance.patinfo.info(["number is okey: ", number])

def __set_name__(self, owner, name):
self.name = name


class DocType():
def __get__(self, instance, owner):
return instance.__dict__[self.name]

def __set__(self, instance, type):
if not isinstance(type, str):
instance.paterr.error('Invalid type.')
instance.paterr.error("Error. User was not created.")
raise TypeError("not str")
prov = docTypeIsValid(type)
if not prov:
instance.paterr.error('Invalid doc type. паспорт, загран или права')
instance.paterr.error("Error. User was not created.")
raise ValueError("doctype error")
instance.__dict__[self.name] = prov
instance.patinfo.debug(["Doc type is okey:", prov])
if instance.created:
instance.patinfo.info(["Dov type is okey: ", prov])

def __set_name__(self, owner, name):
self.name = name


class DocId:
def __get__(self, instance, owner):
return instance.__dict__[self.name]

def __set__(self, instance,id):
if not isinstance(id, str):
instance.paterr.error('Invalid id.')
instance.paterr.error("Error. User was not created.")
raise TypeError("not str")
self.type = instance.document_type
prov = docIdIsValid(id, self.type)
if not prov:
instance.paterr.error('Invalid doc id. паспорт(10 цифр), загран(9 цифр) или права(10 цифр)')
instance.paterr.error("Error. User was not created.")
raise ValueError("docid error")
instance.__dict__[self.name] = prov
instance.patinfo.debug(["Doc id okey: ", prov])
if instance.created:
instance.patinfo.info(["Doc id is okey: ", prov])

def __set_name__(self, owner, name):
self.name = name
self.type = None


class Date:
def __get__(self, instance, owner):
return instance.__dict__[self.name]

def __set__(self, instance, date):
if not isinstance(date, str):
instance.paterr.error('Invalid name.')
instance.paterr.error("Error. User was not created.")
raise TypeError("not str")
prov = dateIsValid(date)
if not prov:
instance.paterr.error('Invalid date. year-month-day')
instance.paterr.error("Error. User was not created.")
raise ValueError("date error")
date = prov

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

излишне

instance.__dict__[self.name] = date
instance.patinfo.debug(["Date is okey: ", date])
if instance.created:
instance.patinfo.info(["Date is okey: ", date])

def __set_name__(self, owner, name):
self.name = name
46 changes: 46 additions & 0 deletions homework/Log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import logging

# u should uncomment lines, and comment 2 times 1 line line on comment and it'll start write logs in 2 files
# handler = logging.FileHandler('Logs.txt', 'a', 'utf-8')
handler = logging.FileHandler('/home/alexsun8/kib/ДЗ2/python_developer_hw2/homework/Good_Logs.txt', 'a', 'utf-8')
handler2 = logging.FileHandler('/home/alexsun8/kib/ДЗ2/python_developer_hw2/homework/Bad_Logs.txt', 'a', 'utf-8')
formatter = logging.Formatter("%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s")
handler.setFormatter(formatter)
# handlerbad = handler
handlerbad = handler2


# logs in Patient class
patinfo = logging.getLogger("Patient info")
patinfo.setLevel(logging.INFO)
patinfo.addHandler(handler)
paterr = logging.getLogger("Patient errors")
paterr.setLevel(logging.ERROR)
paterr.addHandler(handlerbad)

# logs in Pat. Colle
collectinfo = logging.getLogger("Collection info")
collectinfo.setLevel(logging.INFO)
collectinfo.addHandler(handler)
collecterr = logging.getLogger("Collection errors")
collecterr.setLevel(logging.ERROR)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно обойтись двумя логгерами

collecterr.addHandler(handlerbad)

# logs in Descriptors in data valid
validator = logging.getLogger("Validator")
validator.setLevel(logging.INFO)
validator.addHandler(handler)
validerr = logging.getLogger("Validator errors")
validerr.setLevel(logging.ERROR)
validerr.addHandler(handlerbad)

# for logging in console
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(formatter)

collectinfo.addHandler(consoleHandler)
collecterr.addHandler(consoleHandler)
patinfo.addHandler(consoleHandler)
paterr.addHandler(consoleHandler)
validator.addHandler(consoleHandler)
validerr.addHandler(consoleHandler)
5 changes: 5 additions & 0 deletions homework/PatienList.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Кондрат,Рюрик,1971-01-31,+79160000000,паспорт,0228000000
Евпатий,Коловрат,1972-01-31,+79160000001,паспорт,0228000001
Ада,Лавлейс,1978-01-21,+79160000002,паспорт,0228000002
Миртл,Плакса,1980-01-31,+79160000003,паспорт,0228000003
Евлампия,Фамилия,1999-01-31,+79160000004,паспорт,0228000004
97 changes: 97 additions & 0 deletions homework/Patient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
from homework.Descriptor import *
from homework.Log import patinfo, paterr


class Patient:
first_name = Name()
last_name = Name()
birth_date = Date()
phone = Phone()
document_type = DocType()
document_id = DocId()
created = False

def __init__(self, *args):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше аргументы явно объявлять

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и тогда код в init сократится в 4 раза)

if len(args) == 0:
self.created = False
patinfo.info("Empty Patient was created")
return
elif not len(args) == 6:
self.created = False
paterr.error(
"There shold be 6 args: first_name_, last_name_, birth_date_, phone_, document_type_, document_id_. Patient wasn't created")
return
try:
# self.created = False
self.first_name = args[0]
self.last_name = args[1]
self.birth_date = args[2]
self.phone = args[3]
self.document_type = args[4]
self.document_id = args[5]
self.created = True
if not (
self.first_name or self.last_name or self.birth_date or self.phone or self.document_type or self.document_id):
raise AttributeError
patinfo.info("User was created")
except:
self.created = False
paterr.error("Error. User was not created.")

def create(self, *args):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Patient.create(...) не сработает

if not len(args) == 6:
self.created = False
paterr.error(
"There shold be 6 args: first_name_, last_name_, birth_date_, phone_, document_type_, document_id_. Patient wasn't created")
return

try:
self.created = False
self.first_name = args[0]
self.last_name = args[1]
self.birth_date = args[2]
self.phone = args[3]
self.document_type = args[4]
self.document_id = args[5]
if not (
self.first_name or self.last_name or self.birth_date or self.phone or self.document_type or self.document_id):
raise AttributeError
self.created = True
patinfo.info("User was created")
except:
self.created = False
paterr.error("Error. User was not created.")

def save(self):
if not self.created:
paterr.warning("User is NONE, so it wasn't saved.")
try:
data = ' '.join(
[self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id,
'\n'])
filename = "PatientList.csv"
with open(filename, 'a+') as file:
file.write(data)
patinfo.info("User was saved.")
except:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

слишком общий except

paterr.error("User was not saved!")

def __str__(self):
if not self.created:
return ""
data = ' '.join(
[self.first_name, self.last_name, self.birth_date, self.phone, self.document_type, self.document_id])
return data


# pat = Patient("Alice", "asdasd", "2003-02-30", "89234445553", "pfuhfy", "627 78 99977")
# pat.save()
# pat.create("Alice", "as", "2003-02-26", "89234445553", "ghfdf", "627 78 99977")
# pat.save()
# pat.last_name = "Johnson"
# pat.birth_date = "01-02-1990"
# # print(pat)
#
# pat = Patient()
# pat.create("bob", "as", "2003-02-26", "89234445553", "gfcgjhn", "627 78 99977")
# pat.save()
Loading