Skip to content
This repository has been archived by the owner on May 2, 2024. It is now read-only.

Commit

Permalink
Merge branch 'day38'
Browse files Browse the repository at this point in the history
  • Loading branch information
tbrlpld committed Nov 24, 2019
2 parents 365d86d + e6390a6 commit 1dcda4a
Show file tree
Hide file tree
Showing 46 changed files with 737 additions and 115 deletions.
11 changes: 0 additions & 11 deletions work/036-pyramid-intro/billtracker/billtracker/__init__.py

This file was deleted.

3 changes: 0 additions & 3 deletions work/036-pyramid-intro/billtracker/billtracker/routes.py

This file was deleted.

62 changes: 0 additions & 62 deletions work/036-pyramid-intro/billtracker/billtracker/templates/base.pt

This file was deleted.

17 changes: 0 additions & 17 deletions work/036-pyramid-intro/billtracker/billtracker/templates/home.pt

This file was deleted.

20 changes: 0 additions & 20 deletions work/036-pyramid-intro/billtracker/billtracker/views/home.py

This file was deleted.

25 changes: 25 additions & 0 deletions work/037-pyramid-intro/billtracker/billtracker/__init__.py
@@ -0,0 +1,25 @@
# -*- conding: utf-8 -*-

"""App entry point."""

import os

from pyramid.config import Configurator

from billtracker.bin.load_base_data import load_starter_data
from billtracker.data.db_session import DbSession


def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
with Configurator(settings=settings) as config:
config.include("pyramid_chameleon")
config.include(".routes")
config.include(".security")
config.scan()

current_dir = os.path.dirname(os.path.abspath(__file__))
db_file = os.path.join(current_dir, "db/billtracker.sqlite3")
DbSession.global_init(db_file)
load_starter_data()
return config.make_wsgi_app()
@@ -0,0 +1,65 @@
import json
import os
import random
from typing import List

import dateutil.parser
from sqlalchemy.orm import Session

from billtracker.data.db_session import DbSession
from billtracker.data.models.bill import Bill
from billtracker.data.models.users import User


def load_starter_data():
print("Loading starter data...")
session = DbSession.create_session()
if session.query(Bill).count() > 0:
session.close()
print("Data already loaded...")
return

session.expire_on_commit = False

users = add_users(session)
add_bills(users)

session.commit()
session.close()


def add_users(session: Session) -> List[User]:
users = []
data_file = os.path.join(DbSession.db_folder, 'MOCK_USERS.json')
with open(data_file, 'r', encoding='utf-8') as fin:
data = json.load(fin)

for u in data:
user = User()
users.append(user)
user.email = u.get('email')
user.name = u.get('name')
user.created_date = dateutil.parser.parse(u.get('created_date'))
user.last_login = dateutil.parser.parse(u.get('last_login'))
user.last_login = dateutil.parser.parse(u.get('last_login'))
user.hashed_password = u.get('hashed_password')
session.add(user)

return users


def add_bills(users: List[User]):
data_file = os.path.join(DbSession.db_folder, 'MOCK_PAYMENTS.json')
with open(data_file, 'r', encoding='utf-8') as fin:
data = json.load(fin)

for p in data:
user = random.choice(users)

bill = Bill()
bill.created_date = dateutil.parser.parse(p.get('created_date'))
bill.description = p.get('description')
bill.total = int(p.get('total'))
bill.paid = min(bill.total, int(p.get('paid')))

user.bills.append(bill)
Expand Up @@ -20,3 +20,9 @@ class Bill(SqlAlchemyBase):
@property
def is_paid(self):
return self.total <= self.paid

@property
def open(self):
"""Return the open amount."""
return self.total - self.paid

Expand Up @@ -35,3 +35,13 @@ def total_owed(self) -> float:
@property
def total_paid_off(self) -> float:
return sum(b.total for b in self.paid_bills)

def check_password(self, password):
# Just a stub that accepts anything as the password.
print("Password to check: {0}".format(password))
print("Password to match: {0}".format(self.hashed_password))
if password == self.hashed_password:
print("Passwords match.")
return True
print("Passwords do not match.")
return False
Expand Up @@ -21,11 +21,26 @@ def get_user_by_id(user_id: int, include_bills=True) -> Optional[User]:
session.close()


def get_user_by_email(email: int, include_bills=False) -> Optional[User]:
session = DbSession.create_session()
try:
if not include_bills:
return session.query(User).filter(User.email == email).first()
else:
return session.query(User) \
.options(subqueryload(User.bills)) \
.filter(User.id == user_id) \
.first()
finally:
session.close()


def get_bill_by_id(bill_id: int) -> Optional[Bill]:
session = DbSession.create_session()
try:
return session.query(Bill) \
.filter(Bill.id == bill_id) \
.options(subqueryload(Bill.user)) \
.first()
finally:
session.close()
Expand Down
@@ -1,4 +1,4 @@
[{"id":1,"name":"Dannie Easom","email":"deasom0@macromedia.com","hashed_password":"86rV3X82LC6VFFxb3hRX98B66tTMOM7QPW73Yhx2p40C2A12fSPGLDCB6KOUep4m9HEQU","created_date":"2017-12-23T13:31:30Z","last_login":"2018-04-09T05:04:37Z"},
[{"id":1,"name":"Dannie Easom","email":"deasom0@macromedia.com","hashed_password":"test","created_date":"2017-12-23T13:31:30Z","last_login":"2018-04-09T05:04:37Z"},
{"id":2,"name":"Vicki Minchenton","email":"vminchenton1@behance.net","hashed_password":"15vZB1FH9AJUGHsr0mWKBLU72wVGGBYM54MXHnv1eZ4JXG45aXGGDWLETPCRum1y6ENV4","created_date":"2018-05-11T03:04:49Z","last_login":"2018-05-18T19:44:24Z"},
{"id":3,"name":"Jami Mayte","email":"jmayte2@liveinternet.ru","hashed_password":"37eG627P025U9Vbl3iEBZQS92fIOME80WRUZLty4cWS4HL88oDKAKR02M64Rlg4wW45CF","created_date":"2017-12-14T20:43:16Z","last_login":"2018-02-11T20:59:17Z"},
{"id":4,"name":"Dre Dunston","email":"ddunston3@etsy.com","hashed_password":"75xETKLMGHOVB4dy3b1UGY452lO1REVL6SI7Mfz4wD2NNW50bMJ7SPDKFEWKtr4l2LTQG","created_date":"2018-09-02T09:54:46Z","last_login":"2018-05-07T17:35:12Z"},
Expand Down
7 changes: 7 additions & 0 deletions work/037-pyramid-intro/billtracker/billtracker/routes.py
@@ -0,0 +1,7 @@
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('login', '/login')
config.add_route('logout', '/logout')
config.add_route('home', '/')
config.add_route('welcome', '/welcome')
config.add_route('bill_detail', '/bill/{bill_id}')
39 changes: 39 additions & 0 deletions work/037-pyramid-intro/billtracker/billtracker/security.py
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-

"""Defines the security functionality for the app."""

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy


from billtracker.data import repository


class MyAuthenticationPolicy(AuthTktAuthenticationPolicy):
"""Defines the auth policy for the app."""

def authenticated_user(self, request):
"""Return id of authenticated user from request."""
user = request.user
if user is not None:
return user.id


def get_user(request):
"""Return User object from database with given id."""
user_id = request.unauthenticated_userid
if user_id is not None:
user = repository.get_user_by_id(user_id)
return user


def includeme(config):
settings = config.get_settings()
authn_policy = MyAuthenticationPolicy(
settings["auth.secret"],
hashalg="sha512",
)
config.set_authentication_policy(authn_policy)
config.set_authorization_policy(ACLAuthorizationPolicy())
config.add_request_method(get_user, "user", reify=True)

0 comments on commit 1dcda4a

Please sign in to comment.