Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 28 additions & 0 deletions students/swietczak_monika/lesson_12_debugging/coin_toss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import random
import logging

logging.basicConfig(level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s- %(message)s')

guess = ''

toss_int = random.randint(0, 1) # 0 is tails, 1 is heads
if toss_int == 0:
Copy link
Collaborator

Choose a reason for hiding this comment

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

There is a short form for that toss = 'tails' if toss_int else 'heads'

toss = "heads"
else:
toss = "tails"

logging.debug("toss = " + str(toss))

while guess not in ('heads', 'tails'):
print('Guess the coin toss! Enter heads or tails:')
guess = input()
if toss == guess:
print('You got it!')
else:
print('Nope! Guess again!')
guess = input()
Copy link
Collaborator

Choose a reason for hiding this comment

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

You don't check the validity of input here. To avoid repeating the code you could enclose the while in a function.

if toss == guess:
print('You got it!')
else:
print('Nope. You are really bad at this game.')
34 changes: 34 additions & 0 deletions students/swietczak_monika/lesson_12_debugging/regex_validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import re


def email_validator(some_email):
email_regex = re.compile(r"[^@]+@[^@]+\.[^@]+")
Copy link
Collaborator

@adziu adziu Jul 20, 2018

Choose a reason for hiding this comment

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

It's more complicated than that. Not all the symbols are allowed. In real life you should search Google for "regex library" and get a comprehensive checker or use some library checker (Django for example has a field for that). In less real life situations you should take care that you accept a reasonable subset with _ . etc., but certainly not too much.

You accept too much. The input you accepted could cause some trouble. For example didn't put $ at the end, so the potential attacker could put something in the content of the mail message you are sending. You also accept spaces/inequality characters, semicolons, all rather dangerous, somebody could destroy your CSV file. [\w\d_.-]+ [a-z0-9_.-]+ would be much better than [^@]+ here. In other cases the [^ construct is the best way to go and good that you know it.

result = email_regex.match(some_email)
if result is None:
return False
else:
return True


def phone_number_validator(some_number):
phone_regex = re.compile(r"^\d{3}[- ]?\d{3}[- ]?\d{3}$")
if phone_regex.match(some_number) is None:
return False
else:
return True


def postal_code_validator(some_postal_code):
postal_code_regex = re.compile(r"^\d\d-\d\d\d$")
if postal_code_regex.match(some_postal_code) is None:
return False
else:
return True


def pass_checker(some_password):
if re.match(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$',
Copy link
Collaborator

Choose a reason for hiding this comment

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

That's an interesting solution! In all the other reviews multiple regular expressions were used. 👍

some_password) is None:
return False
else:
return True
1 change: 1 addition & 0 deletions students/swietczak_monika/lesson_12_debugging/test.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[email protected],pAssw0rd#,126-222-544,[email protected],pAssw0rd#,127-222-544,12-222
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import sys
import regex_validators
import logging
import csv
import argparse

logging.basicConfig(format=' %(asctime)s - %(levelname)s- %(message)s')


def combined_validator(email_addr, phone_nr, postal_code, passwd):
if not regex_validators.email_validator(email_addr):
raise Exception("Incorrect email")
if not regex_validators.phone_number_validator(phone_nr):
raise Exception("Incorrect phone number")
if not regex_validators.postal_code_validator(postal_code):
raise Exception("Incorrect postal code")
if not regex_validators.pass_checker(passwd):
raise Exception("Strong password required")


def set_verbose_level(verbose_level):
logger = logging.getLogger()
if verbose_level == "info":
logger.setLevel(logging.INFO)
elif verbose_level == "warning":
logger.setLevel(logging.WARNING)
else:
logger.disabled = True


def check_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--email",
help="email",
required=True)
parser.add_argument("-p", "--password",
help="password",
required=True)
parser.add_argument("-n", "--number",
help="phone number",
required=True)
parser.add_argument("-c", "--code",
help="postal code",
required=True)
parser.add_argument("-v", "--verbose",
help="verbose level",
choices=['disabled', 'warning', 'info'],
default="warning")
res = parser.parse_args(args)
return res.email, res.password, res.number, res.code, res.verbose


email, password, number, code, verbose = check_args(sys.argv[1:])
user_data = {"email": email, "password": password, "number": number,
"code": code}


def write_csv(write_file, read_file):
with open(write_file, 'a') as csv_write_file, open(read_file,
'r') as csv_read_file:
fieldnames = ['email', 'password', 'number', 'code']
reader = csv.DictReader(csv_read_file, fieldnames=fieldnames)
writer = csv.DictWriter(csv_write_file, fieldnames=fieldnames)
email_exists = False
for i in reader:
logging.info("Data stored in file: {}".format(i))
if i['email'] == user_data['email']:
logging.info("email {} exists. Replacing user's data".format(
i['email']))
email_exists = True
if not email_exists:
writer.writerow(user_data)
logging.info("User doesn't exists, adding new user's data.")
logging.info("Added user data: {}".format(user_data))


if __name__ == '__main__':
level = verbose
set_verbose_level(level)
combined_validator(email, number, code, password)
write_csv("test.csv", "test.csv")
57 changes: 57 additions & 0 deletions students/swietczak_monika/lesson_12_debugging/verbose_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import os
import re
import argparse
import logging

logging.basicConfig(format=' %(asctime)s - %(levelname)s- %(message)s')


def check_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--regex",
help="regex",
default=".*")
parser.add_argument("-d", "--directory",
help="directory",
default=r"C:\Python36\files")
parser.add_argument("-v", "--verbose",
help="verbose level",
choices=['disabled', 'warning', 'info'],
default="warning")
results = parser.parse_args(args)
return results.regex, results.directory, results.verbose


def set_verbose_level(verbose_level):
logger = logging.getLogger()
if verbose_level == "info":
logger.setLevel(logging.INFO)
elif verbose_level == "warning":
logger.setLevel(logging.WARNING)
else:
logger.disabled = True


def regex_search(reg, folder):
regex_text = re.compile(reg)
logging.info("Regex = {}".format(regex_text))
files_list = os.listdir(folder)
logging.info("Files: {}".format(files_list))
Copy link
Collaborator

Choose a reason for hiding this comment

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

It's good to use logger that knows where you are. That is logger = logging.getLogger(__name__) at the beginning of the file and then logger.info(blah).

for file in files_list:
if file.endswith('.txt'):
logging.info("Textfile found: {}".format(file))
with open(os.path.join(folder, file)) as textfile:
for line in textfile:
if regex_text.match(line):
print("Regex found " + line)
logging.info("Regex found " + line)
else:
logging.warning("Regex not found" + line)
else:
logging.warning("File {} is not a text file".format(file))


if __name__ == '__main__':
regex, directory, level = check_args()
set_verbose_level(level)
regex_search(regex, directory)