Skip to content

Commit

Permalink
Add Changes to app.py file
Browse files Browse the repository at this point in the history
  • Loading branch information
Nehemiah60 committed Jul 25, 2022
1 parent 659eaa8 commit cab983c
Show file tree
Hide file tree
Showing 71 changed files with 28,632 additions and 0 deletions.
14 changes: 14 additions & 0 deletions starter_code/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
venv/
.vscode/
__pycache__/
test.db

# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
35 changes: 35 additions & 0 deletions starter_code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Coffee Shop Full Stack

## Full Stack Nano - IAM Final Project

Udacity has decided to open a new digitally enabled cafe for students to order drinks, socialize, and study hard. But they need help setting up their menu experience.

You have been called on to demonstrate your newly learned skills to create a full stack drink menu application. The application must:

1. Display graphics representing the ratios of ingredients in each drink.
2. Allow public users to view drink names and graphics.
3. Allow the shop baristas to see the recipe information.
4. Allow the shop managers to create new drinks and edit existing drinks.

## Tasks

There are `@TODO` comments throughout the project. We recommend tackling the sections in order. Start by reading the READMEs in:

1. [`./backend/`](./backend/README.md)
2. [`./frontend/`](./frontend/README.md)

## About the Stack

We started the full stack application for you. It is designed with some key functional areas:

### Backend

The `./backend` directory contains a partially completed Flask server with a pre-written SQLAlchemy module to simplify your data needs. You will need to complete the required endpoints, configure, and integrate Auth0 for authentication.

[View the README.md within ./backend for more details.](./backend/README.md)

### Frontend

The `./frontend` directory contains a complete Ionic frontend to consume the data from the Flask server. You will only need to update the environment variables found within (./frontend/src/environment/environment.ts) to reflect the Auth0 configuration details set up for the backend app.

[View the README.md within ./frontend for more details.](./frontend/README.md)
87 changes: 87 additions & 0 deletions starter_code/backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Coffee Shop Backend

## Getting Started

### Installing Dependencies

#### Python 3.7

Follow instructions to install the latest version of python for your platform in the [python docs](https://docs.python.org/3/using/unix.html#getting-and-installing-the-latest-version-of-python)

#### Virtual Environment

We recommend working within a virtual environment whenever using Python for projects. This keeps your dependencies for each project separate and organized. Instructions for setting up a virtual environment for your platform can be found in the [python docs](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)

#### PIP Dependencies!!

Once you have your virtual environment setup and running, install dependencies by naviging to the `/backend` directory and running:

```bash
pip install -r requirements.txt
```

This will install all of the required packages we selected within the `requirements.txt` file.

##### Key Dependencies

- [Flask](http://flask.pocoo.org/) is a lightweight backend microservices framework. Flask is required to handle requests and responses.

- [SQLAlchemy](https://www.sqlalchemy.org/) and [Flask-SQLAlchemy](https://flask-sqlalchemy.palletsprojects.com/en/2.x/) are libraries to handle the lightweight sqlite database. Since we want you to focus on auth, we handle the heavy lift for you in `./src/database/models.py`. We recommend skimming this code first so you know how to interface with the Drink model.

- [jose](https://python-jose.readthedocs.io/en/latest/) JavaScript Object Signing and Encryption for JWTs. Useful for encoding, decoding, and verifying JWTS.

## Running the server

From within the `./src` directory first ensure you are working using your created virtual environment.

Each time you open a new terminal session, run:

```bash
export FLASK_APP=api.py;
```

To run the server, execute:

```bash
flask run --reload
```

The `--reload` flag will detect file changes and restart the server automatically.

## Tasks

### Setup Auth0

1. Create a new Auth0 Account
2. Select a unique tenant domain
3. Create a new, single page web application
4. Create a new API
- in API Settings:
- Enable RBAC
- Enable Add Permissions in the Access Token
5. Create new API permissions:
- `get:drinks`
- `get:drinks-detail`
- `post:drinks`
- `patch:drinks`
- `delete:drinks`
6. Create new roles for:
- Barista
- can `get:drinks-detail`
- can `get:drinks`
- Manager
- can perform all actions
7. Test your endpoints with [Postman](https://getpostman.com).
- Register 2 users - assign the Barista role to one and Manager role to the other.
- Sign into each account and make note of the JWT.
- Import the postman collection `./starter_code/backend/udacity-fsnd-udaspicelatte.postman_collection.json`
- Right-clicking the collection folder for barista and manager, navigate to the authorization tab, and including the JWT in the token field (you should have noted these JWTs).
- Run the collection and correct any errors.
- Export the collection overwriting the one we've included so that we have your proper JWTs during review!

### Implement The Server

There are `@TODO` comments throughout the `./backend/src`. We recommend tackling the files in order and from top to bottom:

1. `./src/auth/auth.py`
2. `./src/api.py`
20 changes: 20 additions & 0 deletions starter_code/backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
astroid==2.2.5
Click==7.0
ecdsa==0.13.2
Flask==1.0.2
Flask-SQLAlchemy==2.5.0
future==0.17.1
isort==4.3.18
itsdangerous==1.1.0
Jinja2==2.10.1
lazy-object-proxy==1.4.0
MarkupSafe==1.1.1
mccabe==0.6.1
pycryptodome==3.3.1
pylint==2.3.1
python-jose-cryptodome==1.3.2
six==1.12.0
typed-ast==1.4.2
Werkzeug==0.15.6
wrapt==1.11.1
Flask-Cors==3.0.8
Empty file.
194 changes: 194 additions & 0 deletions starter_code/backend/src/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import os
from flask import Flask, request, jsonify, abort
from sqlalchemy import exc
import json
from flask_cors import CORS

from .database.models import db_drop_and_create_all, setup_db, Drink
from .auth.auth import AuthError, requires_auth

app = Flask(__name__)
setup_db(app)
CORS(app)

'''
@TODO uncomment the following line to initialize the datbase
!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH
!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN
!! Running this funciton will add one
'''
# db_drop_and_create_all()

# ROUTES
'''
@TODO implement endpoint
GET /drinks
it should be a public endpoint
it should contain only the drink.short() data representation
returns status code 200 and json {"success": True, "drinks": drinks} where drinks is the list of drinks
or appropriate status code indicating reason for failure
'''

@app.route('/drinks', methods = ['GET'])
def get_drinks():
try:

drinks = Drink.query.all()
drink = [drink.short() for drink in drinks]
return ({
'success' : True,
'drinks' : drink
})
except:
abort(422)
'''
@TODO implement endpoint
GET /drinks-detail
it should require the 'get:drinks-detail' permission
it should contain the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drinks} where drinks is the list of drinks
or appropriate status code indicating reason for failure
'''
@app.route('/drinks_detail', methods = ['GET'])
def get_drinks_details():
drink = Drink.query.all()
drinks = [drinks.long() for drinks in drink]
return jsonify({
'success' : True,
'drinks' : drinks
})

'''
@TODO implement endpoint
POST /drinks
it should create a new row in the drinks table
it should require the 'post:drinks' permission
it should contain the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drink} where drink an array containing only the newly created drink
or appropriate status code indicating reason for failure
'''
@app.route('/drinks', methods = ['POST'])
def create_drinks():
body = request.get_json()
new_title= body.get('title', None)
new_recipe = body.get('recipe', None)

new_drink = Drink(
title = new_title,
recipe = new_recipe
)
drinks.insert()
drink = [drink.long() for drink in drinks]
return jsonify({
'success' : True,
'drinks' : drink
})

'''
@TODO implement endpoint
PATCH /drinks/<id>
where <id> is the existing model id
it should respond with a 404 error if <id> is not found
it should update the corresponding row for <id>
it should require the 'patch:drinks' permission
it should contain the drink.long() data representation
returns status code 200 and json {"success": True, "drinks": drink} where drink an array containing only the updated drink
or appropriate status code indicating reason for failure
'''
@app.route('/drinks/<int:drink_id>', methods = ['PATCH'])
def update_drinks(drink_id):
body = request.get_json()
drinks = Drink.query.filter(Drink.id == drink_id).one_or_none()
if drinks is None:
abort(404)
if 'title' in body:
drinks.title = body.get('title')
drinks.update()
if 'recipe' in body:
drinks.recipe = body.get('recipe')
drinks.update()
drik = [drik.long() for drik in drinks]
return ({
'success' : True,
'drinks' : drik
})

'''
@TODO implement endpoint
DELETE /drinks/<id>
where <id> is the existing model id
it should respond with a 404 error if <id> is not found
it should delete the corresponding row for <id>
it should require the 'delete:drinks' permission
returns status code 200 and json {"success": True, "delete": id} where id is the id of the deleted record
or appropriate status code indicating reason for failure
'''
@app.route('/drinks/<int:drink_id>', methods = ['DELETE'])
def delete_drinks(drink_id):
drinks = Drink.query.filter(Drink.id == drink_id).one_or_none()
if drinks is None:
abort(404)
else:
drinks.delete()

return jsonify({
'success' : True,
'delete' : drink_id

})

# Error Handling
'''
Example error handling for unprocessable entity
'''


@app.errorhandler(422)
def unprocessable(error):
return jsonify({
"success": False,
"error": 422,
"message": "unprocessable"
}), 422


'''
@TODO implement error handlers using the @app.errorhandler(error) decorator
each error handler should return (with approprate messages):
jsonify({
"success": False,
"error": 404,
"message": "resource not found"
}), 404
'''
@app.errorhandler(404)
def resource_not_found(error):
return jsonify({
'success' : False,
'error' : 404,
'message': 'Resource not found'
}), 404
'''
@TODO implement error handler for 404
error handler should conform to general task above
'''
@app.errorhandler(422)
def bad_request (error):
return jsonify({
'success' : False,
'error' : 422,
'message' : 'Bad Request'
}), 422

'''
@TODO implement error handler for AuthError
error handler should conform to general task above
'''
@app.errorhandler(AuthError)
def auth_error(error):
return jsonify({
"success": False,
"error": error.status_result,
"message": error.error['description']
}), error.status_result
Empty file.
Loading

0 comments on commit cab983c

Please sign in to comment.