Skip to content

Commit

Permalink
Added env loader, changed datetime issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Niepawowsky committed Jan 13, 2024
1 parent c1c445e commit 2283be7
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 85 deletions.
55 changes: 38 additions & 17 deletions database/db_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ class DataBaseService():
def __init__(self, connection):
self.connection = connection

def create_database(self, connection):
with DbManager(connection) as database:

def create_connection(self):
pass
def create_database(self):
with DbManager(self.connection) as database:
database.cursor.execute('''CREATE TABLE IF NOT EXISTS borrowed_books(
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT,
Expand All @@ -46,6 +49,16 @@ def create_database(self, connection):
author TEXT NOT NULL,
return_at DATE)'''
)
def _execute_query(self, query, params):

with DbManager(connection=self.connection) as database:
cursor = database.cursor
if params:
cursor.execute(query, params)
else:
cursor.execute(query)

return cursor.fetchall()

def get_borrowed_books_by_today(self):

Expand All @@ -60,20 +73,22 @@ def get_borrowed_books_by_today(self):
today = datetime.today()
borrower = namedtuple('Borrower', 'name email title return_at')
borrower_list = []
with DbManager(connection=self.connection) as database:
database.cursor.execute('''SELECT
query = '''SELECT
name,
email,
title,
return_at
FROM borrowed_books
WHERE return_at > ?''', (today,))
WHERE return_at > ?'''

result = self._execute_query(query, (today,))

for name, email, title, return_at in database.cursor.fetchall():
return_date = datetime.strptime(return_at, '%Y-%m-%d %H:%M:%S')
borrower_list.append(borrower(name, email, title, return_date))
for name, email, title, return_at in result:
return_date = datetime.strptime(return_at, '%Y-%m-%d %H:%M:%S')
return_date.strftime('%Y-%m-%d')
borrower_list.append(borrower(name, email, title, return_date))

return borrower_list
return borrower_list

def get_borrowed_history(self):
"""
Expand All @@ -88,17 +103,23 @@ def get_borrowed_history(self):
# today = datetime.today()
borrower = namedtuple('Borrower', 'name email title return_at')
borrower_list = []
with DbManager(connection=self.connection) as database:
database.cursor.execute('''SELECT
query = '''SELECT
name,
email,
title,
return_at
FROM borrowed_books''')
FROM borrowed_books'''

result = self._execute_query(query, None)

for name, email, title, return_at in result:
return_date = datetime.strptime(return_at, '%Y-%m-%d %H:%M:%S')
return_date.strftime('%Y-%m-%d')
borrower_list.append(borrower(name, email, title, return_date))

return borrower_list


for name, email, title, return_at in database.cursor.fetchall():
return_date = datetime.strptime(return_at, '%Y-%m-%d %H:%M:%S')
print(return_date)
borrower_list.append(borrower(name, email, title, return_date))
def add_record(self):
pass

return borrower_list
98 changes: 98 additions & 0 deletions mail_sender.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import datetime
import smtplib, ssl
from dotenv import load_dotenv
from os import environ, getenv
from string import Template

from templates.template_render import EmailTemplates


class MailSender():
@staticmethod
# def send_data(func):
# def wrapper(*args, **kwargs):
# smtp_server = getenv('SMTP_SERVER')
# port = 465#('PORT')
# sender_email = getenv('EMAIL')
# password = getenv('PASSWORD')
#
# context = ssl.create_default_context()
#
# result = func(*args,
# smtp_server=smtp_server,
# port=port,
# sender_email=sender_email,
# password=password,
# context=context
# )
#
# return result
#
# return wrapper

@staticmethod
def send_data(func):
def wrapper(*args, **kwargs):
load_dotenv()
smtp_server = getenv('SMTP_SERVER')
port = 465 # or int(getenv('PORT'))
sender_email = getenv('EMAIL')
password = getenv('PASSWORD')

context = ssl.create_default_context()

# # If the wrapped function already has these arguments, use them
# if 'smtp_server' in kwargs:
# smtp_server = kwargs['smtp_server']
# if 'port' in kwargs:
# port = kwargs['port']
# if 'sender_email' in kwargs:
# sender_email = kwargs['sender_email']
# if 'password' in kwargs:
# password = kwargs['password']
# if 'context' in kwargs:
# context = kwargs['context']

kwargs.update({
'smtp_server': smtp_server,
'port': port,
'sender_email': sender_email,
'password': password,
'context': context

})
result = func(*args, **kwargs)
return result

return wrapper

def __init__(self, borrowers: list, template: EmailTemplates):
self.borrowers = borrowers
self.template = template

def __str__(self):
print(self.borrowers)

@send_data
def send_passed_return_date(self, *args, **kwargs): # smtp_server, port, sender_email, password, context):
print('Before connected to SMTP server')
try:
print('connected to SMTP server')
#
with smtplib.SMTP_SSL(host=kwargs['smtp_server'], port=kwargs["port"], context=kwargs['context']) as server:
for borrower in self.borrowers:
today = datetime.datetime.today()
today.strftime('%Y-%m-%d')
result = borrower.return_at - today
print(type(borrower.return_at))
mail = self.template.send_reminder_nearby().substitute(name=borrower.name, title=borrower.title,
return_at=borrower.return_at, result=str(result))
#@TODO wysyla pustego maila
print('To jest mail:', mail)
print('Iterating threw self.borrowers')
server.login(kwargs['sender_email'], kwargs['password'])
print('logged in')
server.sendmail(kwargs['sender_email'], borrower.email, mail)

except Exception as e:
print(f'Error: {e}')
54 changes: 10 additions & 44 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,16 @@
from collections import namedtuple
from datetime import datetime
from database.db_service import DbManager, DataBaseService
from database.db_service import DbManager
import smtplib, ssl
from os import environ, getenv
import sqlite3

from mail_sender import MailSender
from database.db_service import DbManager, DataBaseService
from templates.template_render import EmailTemplates

connection = sqlite3.connect('database/sample_books.db') #być może trzeba będzie to zostawić

db = DataBaseService(connection)

# print(db.get_borrowed_books_by_today())
print(db.get_borrowed_books_by_today())



class MailSender():
@staticmethod
def send_data(func):
def wrapper(*args, **kwargs):
#TODO create funcion that sends email using data from .env, than in different methods, sends emails with specific message
smtp_server = getenv('SMTP_SERVER')
port = getenv('PORT')
sender_email = getenv('EMAIL')
password = getenv('PASSWORD')

context = ssl.create_default_context()

result = func(*args, smtp_server = smtp_server, port = port, sender_email = sender_email, password = password, context = context)

return result

return wrapper

def __init__(self, user: namedtuple):
self.user = user

@send_data
def send_passed_return_date(self, smtp_server, port, sender_email, password, context, receiver_email, msg):
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg=msg)



connection = sqlite3.connect('database/sample_books.db')

data = DataBaseService(connection)
templates = EmailTemplates()
borrowers_list = data.get_borrowed_books_by_today()
print(borrowers_list)

email = MailSender(borrowers_list, templates)
email.send_passed_return_date()

15 changes: 15 additions & 0 deletions templates/template_render.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from string import Template


class EmailTemplates():

@staticmethod
def send_reminder_overdue():
mssg = Template('$name, You have borrowed $title and return date passed $return_at\n Please return it imidietly\nBest Regards\nPawel')
return mssg

@staticmethod
def send_reminder_nearby():
mssg = Template('$name, You have borrowed $title and the return day is $return_at. Its about @result days from today.Please try not to overdue this dateBest Regards'
'Pawel')
return mssg
55 changes: 31 additions & 24 deletions test_db_service.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,46 @@
import pytest

from database.db_service import DbManager, DataBaseService
from database.db_service import DataBaseService
import sqlite3
import datetime
import unittest
from freezegun import freeze_time


@pytest.fixture
def create_database():
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
cursor.execute('''CREATE TABLE borrowed_books(
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT,
name TEXT,
title TEXT NOT NULL,
author TEXT NOT NULL,
return_at DATE)'''
)
def create_connection():
with sqlite3.connect(':memory:') as connection:
return connection


@freeze_time('2024-01-08 00:00:00')
def test_get_borrowed_books_for_today_reminder_purpose(create_connection, monkeypatch):
db = DataBaseService(create_connection)
db.create_database()
query = 'INSERT INTO borrowed_books VALUES(?,?,?,?,?,?)'
sample_data = [
(6, '[email protected]', 'John Smith', 'Lalka', 'Bolesław Prus', '2024-12-27 13:30:30'),
(7, '[email protected]', 'Luiza Acante', 'Engine Manual for Smartasses', 'Mario Bro', '2023-12-27 13:30:30')
]
cursor.executemany('INSERT INTO borrowed_books VALUES(?,?,?,?,?,?)', sample_data)
return cursor
]
for data in sample_data:
db._execute_query(query, data)

list_of_borrowers = db.get_borrowed_books_by_today()

def test_get_borrowed_books_for_today_reminder_purpose(create_database):
db = DataBaseService
cursor = create_database
list_of_borrowers = db.get_borrowed_books_by_today(cursor)
assert len(list_of_borrowers) == 1

def test_get_borrowed_books_for_today_amount_of_records(create_database):
db = DataBaseService
cursor = create_database
list_of_borrowers = db.get_borrowed_history(cursor)
assert len(list_of_borrowers) == 2

@freeze_time('2024-01-08 00:00:00')
def test_get_borrowed_books_for_today_amount_of_records(create_connection):
db = DataBaseService(create_connection)
db.create_database()
query = 'INSERT INTO borrowed_books VALUES(?,?,?,?,?,?)'
sample_data = [
(6, '[email protected]', 'John Smith', 'Lalka', 'Bolesław Prus', '2024-12-27 13:30:30'),
(7, '[email protected]', 'Luiza Acante', 'Engine Manual for Smartasses', 'Mario Bro', '2023-12-27 13:30:30')
]
for data in sample_data:
db._execute_query(query, data)

list_of_borrowers = db.get_borrowed_history()
assert len(list_of_borrowers) == 2
13 changes: 13 additions & 0 deletions test_mail_sender.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import pytest
from string import Template
from templates.template_render import EmailTemplates
from mail_sender import MailSender
from database.db_service import DbManager, DataBaseService
import sqlite3


def test_email_send():
mssg = Template('This is test message')



0 comments on commit 2283be7

Please sign in to comment.