Browse files

caught up on commits

  • Loading branch information...
roberto cortes
roberto cortes committed Feb 13, 2020
1 parent e6f87fe commit 5d454535b5666502684c1ca3fc2e4d9257c806fc
Showing with 260 additions and 6 deletions.
  1. +30 −2
  2. BIN dogs.sqlite
  3. +29 −2
  4. +5 −0 requirements.txt
  5. +31 −2 resources/
  6. +165 −0 resources/
@@ -11,9 +11,13 @@
from flask_cors import CORS

# login manager is the main tool for cooardinating session/login stuff in our app
from flask_login import LoginManager

from resources.dogs import dogs # import blueprint from ./resources/dogs

from resources.users import users

# in python you import a file and you get everything in the "global scope"
# of that file
# so this statement imports all variables and methods from that file as
@@ -29,7 +33,31 @@
# instantiating the Flask class
app = Flask(__name__)

# according to this -
# you need to import and config login manager

# 1. we need to setup a secret key
app.secret_key = 'AlsakdlkaskdlaskVery:sld. asklkSecrets;lda;lsaWoah'

# 2. instantiate to get a login_manager
login_manager = LoginManager()

# 3. actually connect app with lom


# in reg and login we did login_user(user that was found or created)
# that puts the ID of the user in session
# to use the user object whose is that is, you must define a cb
# for user_loader (part of login manger) tou use
def load_user(user_id):
return models.User.get( == user_id)
except models.DoesNotExist:
return None
# CORS = Cross Origin Resource Sharing
# a web domain is an "origin"
# This app is localhost:8000, that's an origin
@@ -44,7 +72,7 @@
# third arg -- lets us accept requests with cookies attached, this allows us
# to use sessions for authentication
CORS(dogs, origins=['http://localhost:3000'], supports_credentials=True)

CORS(users, origins=['http://localhost:3000'], supports_credentials=True)

# we are using blueprints tio make "controllers"
# "use this blueprint (component/piece/section of the app) to handle dogs stuff"
@@ -53,7 +81,7 @@
# a different url prefix, and let your old API remain intact so that you don't
# break a bunch of apps already built on top of your old API with the old URLS
app.register_blueprint(dogs, url_prefix='/api/v1/dogs')

app.register_blueprint(users, url_prefix='/api/v1/users')

# we don't want to hog up the SQL connection pool
# so we should connect to the DB before every request
BIN +16 KB (300%) dogs.sqlite
Binary file not shown.
@@ -18,6 +18,25 @@
DATABASE = SqliteDatabase('dogs.sqlite')
# analogous to MONGO_DB_URL = 'mongodb://localhost/dogs', {...}

# we will use this module to setup user model, sessions, logins, auth
# require auth for certain things
from flask_login import UserMixin

# to behave correctly in flask-login's session/login/etc functionality
# the User class must have some methods and properties that model from peewee
# it doesn't have
# we could write these ourselves, and/or we could also have our User class
# inheirt from UserMixin (in addition to peewees model class), which
# will provide/implement them for us

class User(UserMixin, Model):
username = CharField(unique=True)
email = CharField(unique=True) # in sql unique is a constraint
password = CharField()

class Meta:
database = DATABASE

# defining our Dog model
@@ -27,7 +46,15 @@
class Dog(Model):
name = CharField() # string
owner = CharField() # string for now, later we will implement a relation

# we will need a foreign key

owner = ForeignKeyField(User, backref='dogs') # string for now, later we will implement a relation
# if we had a dog model in a variable called some dog, the backref
# 'some_dog.owner' to get the owner
# and if we had the user model in a var called some_user, the backref
# will allow us to go some_user.dogs to get a list of dog instances

breed = CharField()
# this is how you specify default values
created_at = DateTimeField(
@@ -49,7 +76,7 @@ def initialize(): # NOTE we are making this name up
# create_tables first arg is list of tables to create
# second argument -- safe=True -- this means create tables only if it
# doesn't already exist
DATABASE.create_tables([Dog], safe=True)
DATABASE.create_tables([User, Dog], safe=True)
print("Connected to DB and created tables if they weren't already there")

# with SQL, don't leave DB connection open, we don't want to hog up space
@@ -1,10 +1,15 @@
@@ -8,7 +8,7 @@

# this is some useful extra tools that come with peewee
from playhouse.shortcuts import model_to_dict

from flask_login import current_user
# blueprint is a way to modularize apps, and group related functionality
# we are using blueprints to make something analogous to a controller
@@ -58,7 +58,10 @@ def create_dog():
print(payload) # you should now see request data on terminal

# use our peewee model to add something to database
dog = models.Dog.create(name=payload['name'], owner=payload['owner'], breed=payload['breed'])
dog = models.Dog.create(
name=payload['name'],, # this only works with .id

print(dog) # just prints the ID -- check in sqlite3 on the command line
# run sqlite3 dogs.sqlite to open a CLI that lets you enter SQL queries
@@ -76,6 +79,8 @@ def create_dog():



# notice you can add 201 to the return and you will send a proper HTTP status code
return jsonify(
@@ -121,3 +126,27 @@ def update_dog(id):
), 200

@dogs.route('/<owner_id>', methods=['POST'])
def create_dog_with_owner(owner_id):
payload = request.get_json()

dog = models.Dog.create(

dog_dict = model_to_dict(dog)

# remove password from the owner

return jsonify(
message='Successfully created a dog with a owner {}'.format(dog_dict),
), 201
@@ -0,0 +1,165 @@
# like a user controller or auth controller in unit 2
import models

from flask import Blueprint, request, jsonify
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_login import login_user, current_user, logout_user

# login_user is a function that will do the session stuff
# we manually had to do in express

from playhouse.shortcuts import model_to_dict
# make this a blueprint
users = Blueprint('users', 'users')

@users.route('/', methods=['GET'])
def test_user_resources():
return 'we have user resource'

@users.route('/register', methods=['POST'])
def register():
payload = request.get_json()

# since emails are case insensitive in the world..

payload['email'] = payload['email'].lower()
payload['username'] = payload['username'].lower()
# print(payload)

# see if user exists
# if they do then we do not want to create the user
# returning a msg that they cant
models.User.get( == payload['email'] and models.User.username == payload['username'])
# this will throw an error [models.DoesNotExist 'exception'] if they do not exist
# if that query doesn't cause that error
# which in our case means we can go ahead and register them
return jsonify(
message=f'A user with that email already exists',
), 401

# but if we get the error then the user is not found (does not exist)
# then we can register this user
except models.DoesNotExist:# is like catch in JS

# in this except we are safe to create user

created_user = models.User.create(

# this is where actually use flask
# this logs in the user and starts the session

# we can jsonify password and there is no reason to
# send this back to user
#In Python 3, you need to use decode(‘utf-8’) on generate_password_hash(), like below:
#pw_hash = bcrypt.generate_password_hash(‘hunter2’).decode(‘utf-8’)
# print(f' here is that new users with hashed pw {model_to_dict(created_user)}')
user_dict = model_to_dict(created_user)
return jsonify(
message=f'Succesfully created a user! Email is {user_dict}',
), 400

@users.route('/login', methods=['POST'])
def login():

payload = request.get_json()

payload['email'] = payload['email'].lower()
payload['username'] = payload['username'].lower()

user = models.User.get( == payload['email'] or models.User.username == payload['username'])
# look up user by email
# if we didn't cause a models
#does not exist, then lets check their password
user_dict = model_to_dict(user)

### check user password hash with bcrypt ###
# you are checking the encrytped password you looked up and the second
# one is the one that was typed by the user
password_is_good = check_password_hash(user_dict['password'], payload['password'])
if password_is_good:
# if true the user should be logged in
# this is how you do log user in


return jsonify(
message='Succesfully logged in as {}'.format(user_dict['email'])
), 200
print('password is invalid')
return jsonify(
message='Email or password is incorrect',
), 401

except models.DoesNotExist: # it mean user not found
print('username is no good')
return jsonify(
message='Email or password is incorrect',
), 401
@users.route('/all', methods=['GET'])
def get_user_index():
users =

user_dicts = [model_to_dict(u) for u in users]

# delete passwords
# excuse how map works in python
# define a callback to be run on every dict in user dicts
def remove_password(u):
return u

user_dicts_without_pw = map(remove_password, user_dicts)

return jsonify(data=list(user_dicts_without_pw)), 200

# route that will take an id and let us create a dog associated
# with the owner that has that id

# teaching to tool -- route to show which user is logged in
# demo on how to use current_user, this required user_loader
# to be set up in

@users.route('/logged_in', methods=['GET'])
def get_logged_in_user():
print(current_user) # this is the user who is logged in
print(type(current_user)) # <class 'werkzeug.local.LocalProxy'>

user_dict = model_to_dict(current_user)
return jsonify(
message='This is who is logged in',
), 200

# user will still be logged in even after the server is restarted
@users.route('/logout', methods=['GET'])
def logout():
return jsonify(
message='You are succesfully logged out',
), 200

0 comments on commit 5d45453

Please sign in to comment.