├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── app ├── __init__.py ├── auth │ ├── __init__.py │ └── views.py ├── models.py └── views.py ├── habitat ├── default.toml └── plan.sh ├── instance ├── __init__.py └── config.py ├── manage.py ├── migrations ├── README ├── alembic.ini ├── env.py ├── script.py.mako └── versions │ └── d4c79e829afa_.py ├── requirements.txt ├── run.py └── tests ├── test_auth.py └── test_bucketlist.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = 3 | */python?.?/* 4 | */site-packages/nose/* 5 | *__init__* 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | .webassets-cache 58 | 59 | # Scrapy stuff: 60 | .scrapy 61 | 62 | # Sphinx documentation 63 | docs/_build/ 64 | 65 | # PyBuilder 66 | target/ 67 | 68 | # IPython Notebook 69 | .ipynb_checkpoints 70 | 71 | # pyenv 72 | .python-version 73 | 74 | # celery beat schedule file 75 | celerybeat-schedule 76 | 77 | # dotenv 78 | .env 79 | 80 | # virtualenv 81 | venv/ 82 | flask-api 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.8.5" 4 | 5 | services: 6 | - postgresql 7 | 8 | # command to install dependencies 9 | install: 10 | - pip install -r requirements.txt 11 | - pip install coveralls --quiet 12 | 13 | before_script: 14 | - createdb test_db 15 | 16 | # command to run tests 17 | script: coverage run --source=app ./manage.py test 18 | after_success: coveralls 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Jee Githinji Gikera 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flask-rest-api [![Build Status](https://travis-ci.org/gitgik/flask-rest-api.svg?branch=master)](https://travis-ci.org/gitgik/flask-rest-api) 2 | 3 | A flask-driven restful API for Bucketlist interactions 4 | 5 | ## Technologies used 6 | 7 | * **[Python3](https://www.python.org/downloads/)** - A programming language that lets you work more quickly (The universe loves speed!). 8 | * **[Flask](flask.pocoo.org/)** - A microframework for Python based on Werkzeug, Jinja 2 and good intentions 9 | * **[Virtualenv](https://virtualenv.pypa.io/en/stable/)** - A tool to create isolated virtual environments 10 | * **[PostgreSQL](https://www.postgresql.org/download/)** – Postgres database offers many [advantages](https://www.postgresql.org/about/advantages/) over others. 11 | * Minor dependencies can be found in the requirements.txt file on the root folder. 12 | 13 | ## Installation / Usage 14 | 15 | * If you wish to run your own build, first ensure you have python3 globally installed in your computer. If not, you can get python3 [here](https://www.python.org). 16 | * After this, ensure you have installed virtualenv globally as well. If not, run this: 17 | 18 | ```bash 19 | pip install virtualenv 20 | ``` 21 | 22 | * Git clone this repo 23 | 24 | ```bash 25 | git clone git@github.com:gitgik/flask-rest-api.git 26 | ``` 27 | 28 | * ### Dependencies 29 | 30 | 1. Cd into your the cloned repo: 31 | 32 | ```bash 33 | cd flask-rest-api 34 | ``` 35 | 36 | 2. Create and get into your virtual environment: 37 | 38 | ```bash 39 | virtualenv -p python3 venv 40 | source venv/bin/activate 41 | ``` 42 | 43 | * ### Environment Variables 44 | 45 | Install [Dotenv](https://pypi.org/project/python-dotenv/) as follows: 46 | 47 | ```bash 48 | pip install python-dotenv 49 | ``` 50 | 51 | Create a .env file and add the following: 52 | 53 | ```bash 54 | SECRET="some-very-long-string-of-random-characters-CHANGE-TO-YOUR-LIKING" 55 | APP_SETTINGS="development" 56 | DATABASE_URL="postgresql://localhost/flask_api" 57 | ``` 58 | 59 | Dotenv will load your environment variables by reading the key-value pairs from the .env file. 60 | 61 | * ### Install your requirements 62 | 63 | ```bash 64 | (venv)$ pip install -r requirements.txt 65 | ``` 66 | 67 | * ### Database Migrations 68 | 69 | Make sure your postgresql server is running. Then, on your psql console, create your database: 70 | 71 | ```bash 72 | $ psql -U postgres 73 | > CREATE DATABASE flask_api; 74 | ``` 75 | 76 | In the project directory, make and apply your Migrations 77 | 78 | ```bash 79 | (venv)$ flask db init 80 | 81 | (venv)$ flask db migrate 82 | ``` 83 | 84 | And finally, migrate to persist them on the database 85 | 86 | ```bash 87 | (venv)$ flask db upgrade 88 | ``` 89 | 90 | * ### Running the Server 91 | 92 | On your terminal, run the server using this one simple command: 93 | 94 | ```bash 95 | (venv)$ flask run 96 | ``` 97 | 98 | You can now access the app on your local browser by using 99 | 100 | ```bash 101 | http://localhost:5000/bucketlists/ 102 | ``` 103 | 104 | Or test creating bucketlists using Postman 105 | -------------------------------------------------------------------------------- /app/__init__.py: -------------------------------------------------------------------------------- 1 | # app/__init__.py 2 | import json 3 | from flask_api import FlaskAPI, status 4 | from flask_sqlalchemy import SQLAlchemy 5 | 6 | from flask import request, jsonify, abort, make_response 7 | 8 | # local import 9 | 10 | from instance.config import app_config 11 | 12 | from flask_migrate import Migrate, migrate 13 | 14 | # For password hashing 15 | from flask_bcrypt import Bcrypt 16 | 17 | # initialize db 18 | db = SQLAlchemy() 19 | 20 | 21 | def create_app(config_name): 22 | 23 | from app.models import Bucketlist, User 24 | 25 | app = FlaskAPI(__name__, instance_relative_config=True) 26 | # overriding Werkzeugs built-in password hashing utilities using Bcrypt. 27 | bcrypt = Bcrypt(app) 28 | 29 | app.config.from_object(app_config[config_name]) 30 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 31 | db.init_app(app) 32 | migrate = Migrate(db, app) 33 | migrate.init_app(app, db) 34 | 35 | @app.route('/bucketlists/', methods=['POST', 'GET']) 36 | def bucketlists(): 37 | # get the access token 38 | auth_header = request.headers.get('Authorization') 39 | access_token = auth_header.split(" ")[1] 40 | 41 | if access_token: 42 | user_id = User.decode_token(access_token) 43 | if not isinstance(user_id, str): 44 | # Go ahead and handle the request, the user is authed 45 | if request.method == "POST": 46 | name = str(request.data.get('name', '')) 47 | if name: 48 | bucketlist = Bucketlist(name=name, created_by=user_id) 49 | bucketlist.save() 50 | response = jsonify({ 51 | 'id': bucketlist.id, 52 | 'name': bucketlist.name, 53 | 'date_created': bucketlist.date_created, 54 | 'date_modified': bucketlist.date_modified, 55 | 'created_by': user_id 56 | }) 57 | 58 | return make_response(response), 201 59 | 60 | else: 61 | # GET 62 | # get all the bucketlists for this user 63 | bucketlists = Bucketlist.get_all(user_id) 64 | results = [] 65 | 66 | for bucketlist in bucketlists: 67 | obj = { 68 | 'id': bucketlist.id, 69 | 'name': bucketlist.name, 70 | 'date_created': bucketlist.date_created, 71 | 'date_modified': bucketlist.date_modified, 72 | 'created_by': bucketlist.created_by 73 | } 74 | results.append(obj) 75 | 76 | return make_response(jsonify(results)), 200 77 | else: 78 | # user is not legit, so the payload is an error message 79 | message = user_id 80 | response = { 81 | 'message': message 82 | } 83 | return make_response(jsonify(response)), 401 84 | 85 | @app.route('/bucketlists/', methods=['GET', 'PUT', 'DELETE']) 86 | def bucketlist_manipulation(id, **kwargs): 87 | 88 | auth_header = request.headers.get('Authorization') 89 | access_token = auth_header.split(" ")[1] 90 | 91 | if access_token: 92 | user_id = User.decode_token(access_token) 93 | if not isinstance(user_id, str): 94 | bucketlist = Bucketlist.query.filter_by(id=id).first() 95 | if not bucketlist: 96 | # Raise an HTTPException with a 404 not found status code 97 | abort(404) 98 | 99 | if request.method == "DELETE": 100 | bucketlist.delete() 101 | return { 102 | "message": "bucketlist {} deleted".format(bucketlist.id) 103 | }, 200 104 | elif request.method == 'PUT': 105 | name = str(request.data.get('name', '')) 106 | bucketlist.name = name 107 | bucketlist.save() 108 | response = { 109 | 'id': bucketlist.id, 110 | 'name': bucketlist.name, 111 | 'date_created': bucketlist.date_created, 112 | 'date_modified': bucketlist.date_modified, 113 | 'created_by': bucketlist.created_by 114 | } 115 | return make_response(jsonify(response)), 200 116 | else: 117 | # GET 118 | response = jsonify({ 119 | 'id': bucketlist.id, 120 | 'name': bucketlist.name, 121 | 'date_created': bucketlist.date_created, 122 | 'date_modified': bucketlist.date_modified, 123 | 'created_by': bucketlist.created_by 124 | }) 125 | return make_response(response), 200 126 | else: 127 | # user is not legit, so the payload is an error message 128 | message = user_id 129 | response = { 130 | 'message': message 131 | } 132 | return make_response(jsonify(response)), 401 133 | 134 | # import the authentication blueprint and register it on the app 135 | from .auth import auth_blueprint 136 | app.register_blueprint(auth_blueprint) 137 | 138 | return app 139 | -------------------------------------------------------------------------------- /app/auth/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint 2 | 3 | auth_blueprint = Blueprint('auth', __name__) 4 | 5 | from . import views 6 | -------------------------------------------------------------------------------- /app/auth/views.py: -------------------------------------------------------------------------------- 1 | from . import auth_blueprint 2 | 3 | from flask.views import MethodView 4 | from flask import Blueprint, make_response, request, jsonify 5 | from app.models import User 6 | 7 | 8 | class RegistrationView(MethodView): 9 | """This class-based view registers a new user.""" 10 | 11 | def post(self): 12 | # Query to see if the user already exists 13 | user = User.query.filter_by(email=request.data['email']).first() 14 | 15 | if not user: 16 | try: 17 | post_data = request.data 18 | # Register the user 19 | email = post_data['email'] 20 | password = post_data['password'] 21 | user = User(email=email, password=password) 22 | user.save() 23 | 24 | response = { 25 | 'message': 'You registered successfully. Please login.', 26 | } 27 | return make_response(jsonify(response)), 201 28 | 29 | except Exception as e: 30 | response = { 31 | 'message': str(e) 32 | } 33 | return make_response(jsonify(response)), 401 34 | else: 35 | response = { 36 | 'message': 'User already exists. Please login.' 37 | } 38 | 39 | return make_response(jsonify(response)), 202 40 | 41 | 42 | class LoginView(MethodView): 43 | """This class-based view handles user login and access token generation.""" 44 | 45 | def post(self): 46 | try: 47 | user = User.query.filter_by(email=request.data['email']).first() 48 | 49 | if user and user.password_is_valid(request.data['password']): 50 | # Generate the access token 51 | access_token = user.generate_token(user.id) 52 | if access_token: 53 | response = { 54 | 'message': 'You logged in successfully.', 55 | 'access_token': access_token 56 | } 57 | return make_response(jsonify(response)), 200 58 | else: 59 | # User does not exist 60 | response = { 61 | 'message': 'Invalid email or password, Please try again.' 62 | } 63 | return make_response(jsonify(response)), 401 64 | 65 | except Exception as e: 66 | response = { 67 | 'message': str(e) 68 | } 69 | return make_response(jsonify(response)), 500 70 | 71 | 72 | # Define the API resource 73 | registration_view = RegistrationView.as_view('registration_view') 74 | login_view = LoginView.as_view('login_view') 75 | 76 | # Add the url rule for registering a user 77 | auth_blueprint.add_url_rule( 78 | '/auth/register', 79 | view_func=registration_view, 80 | methods=['POST']) 81 | auth_blueprint.add_url_rule( 82 | '/auth/login', 83 | view_func=login_view, 84 | methods=['POST'] 85 | ) 86 | -------------------------------------------------------------------------------- /app/models.py: -------------------------------------------------------------------------------- 1 | from app import db 2 | from flask_bcrypt import Bcrypt 3 | from flask import current_app 4 | import jwt 5 | from datetime import datetime, timedelta 6 | 7 | 8 | class User(db.Model): 9 | """This class defines the users table """ 10 | 11 | __tablename__ = 'users' 12 | 13 | # Define the columns of the users table, starting with the primary key 14 | id = db.Column(db.Integer, primary_key=True) 15 | email = db.Column(db.String(256), nullable=False, unique=True) 16 | password = db.Column(db.String(256), nullable=False) 17 | bucketlists = db.relationship( 18 | 'Bucketlist', order_by='Bucketlist.id', cascade="all, delete-orphan") 19 | 20 | def __init__(self, email, password): 21 | """Initialize the user with an email and a password.""" 22 | self.email = email 23 | self.password = Bcrypt().generate_password_hash(password).decode() 24 | 25 | def password_is_valid(self, password): 26 | """ 27 | Checks the password against it's hash to validates the user's password 28 | """ 29 | return Bcrypt().check_password_hash(self.password, password) 30 | 31 | def save(self): 32 | """Save a user to the database. 33 | This includes creating a new user and editing one. 34 | """ 35 | db.session.add(self) 36 | db.session.commit() 37 | 38 | def generate_token(self, user_id): 39 | """Generates the access token to be used as the Authorization header""" 40 | 41 | try: 42 | # set up a payload with an expiration time 43 | payload = { 44 | 'exp': datetime.utcnow() + timedelta(minutes=5), 45 | 'iat': datetime.utcnow(), 46 | 'sub': user_id 47 | } 48 | # create the byte string token using the payload and the SECRET key 49 | jwt_string = jwt.encode( 50 | payload, 51 | current_app.config.get('SECRET'), 52 | algorithm='HS256' 53 | ) 54 | return jwt_string 55 | 56 | except Exception as e: 57 | # return an error in string format if an exception occurs 58 | return str(e) 59 | 60 | @staticmethod 61 | def decode_token(token): 62 | """Decode the access token from the Authorization header.""" 63 | try: 64 | payload = jwt.decode(token, current_app.config.get( 65 | 'SECRET'), algorithms=["HS256"]) 66 | return payload['sub'] 67 | except jwt.ExpiredSignatureError: 68 | return "Expired token. Please log in to get a new token" 69 | except jwt.InvalidTokenError: 70 | return "Invalid token. Please register or login" 71 | 72 | 73 | class Bucketlist(db.Model): 74 | """This class defines the bucketlist table.""" 75 | 76 | __tablename__ = 'bucketlists' 77 | 78 | # define the columns of the table, starting with its primary key 79 | id = db.Column(db.Integer, primary_key=True) 80 | name = db.Column(db.String(255)) 81 | date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) 82 | date_modified = db.Column( 83 | db.DateTime, default=db.func.current_timestamp(), 84 | onupdate=db.func.current_timestamp()) 85 | created_by = db.Column(db.Integer, db.ForeignKey(User.id)) 86 | 87 | def __init__(self, name, created_by): 88 | """Initialize the bucketlist with a name and its creator.""" 89 | self.name = name 90 | self.created_by = created_by 91 | 92 | def save(self): 93 | """Save a bucketlist. 94 | This applies for both creating a new bucketlist 95 | and updating an existing onupdate 96 | """ 97 | db.session.add(self) 98 | db.session.commit() 99 | 100 | @staticmethod 101 | def get_all(user_id): 102 | """This method gets all the bucketlists for a given user.""" 103 | return Bucketlist.query.filter_by(created_by=user_id) 104 | 105 | def delete(self): 106 | """Deletes a given bucketlist.""" 107 | db.session.delete(self) 108 | db.session.commit() 109 | 110 | def __repr__(self): 111 | """Return a representation of a bucketlist instance.""" 112 | return "".format(self.name) 113 | -------------------------------------------------------------------------------- /app/views.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitgik/flask-rest-api/72df8805a001081e55599bddd57528e4af46a513/app/views.py -------------------------------------------------------------------------------- /habitat/default.toml: -------------------------------------------------------------------------------- 1 | listening_port = 8080 2 | secret = "abigsecret" 3 | database_uri = "postgresql://localhost/flask_api" 4 | -------------------------------------------------------------------------------- /habitat/plan.sh: -------------------------------------------------------------------------------- 1 | pkg_origin=gitgik 2 | pkg_name=flask-rest-api 3 | pkg_version=1.0.1 4 | pkg_maintainer="jeegiks@gmail.com" 5 | pkg_upstream_url="https://github.com/gitgik/flask-rest-api" 6 | pkg_exports=([port]=listening_port [database_uri]=database_uri [secret]=secret) 7 | pkg_exposes=(port secret database_uri) 8 | pkg_deps=(core/python) 9 | pkg_build_deps=(core/virtualenv) 10 | pkg_interpreters=(bin/python3.6) 11 | 12 | do_verify () { 13 | return 0 14 | } 15 | 16 | do_clean() { 17 | return 0 18 | } 19 | 20 | do_unpack() { 21 | # copy the contents of the source directory to the habitat cache path 22 | PROJECT_ROOT="${PLAN_CONTEXT}/.." 23 | 24 | mkdir -p $pkg_prefix 25 | build_line "Copying project data to $pkg_prefix/" 26 | cp -r $PROJECT_ROOT/app $pkg_prefix/ 27 | cp -r $PROJECT_ROOT/*.py $pkg_prefix/ 28 | cp -r $PROJECT_ROOT/requirements.txt $pkg_prefix/ 29 | build_line "Copying .env file with preset variables..." 30 | cp -vr $PROJECT_ROOT/.env $pkg_prefix/ 31 | cp -vr $PROJECT_ROOT/instance $pkg_prefix/ 32 | } 33 | 34 | do_build() { 35 | return 0 36 | } 37 | 38 | do_install() { 39 | cd $pkg_prefix 40 | build_line "Creating virtual environment..." 41 | virtualenv venv 42 | source venv/bin/activate 43 | pip install -r requirements.txt 44 | } 45 | -------------------------------------------------------------------------------- /instance/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gitgik/flask-rest-api/72df8805a001081e55599bddd57528e4af46a513/instance/__init__.py -------------------------------------------------------------------------------- /instance/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | 4 | # Load environment variables 5 | load_dotenv() 6 | 7 | 8 | class Config(object): 9 | """Parent configuration class.""" 10 | DEBUG = False 11 | CSRF_ENABLED = True 12 | SECRET = os.getenv('SECRET') 13 | SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') 14 | 15 | 16 | class DevelopmentConfig(Config): 17 | """Configurations for Development.""" 18 | DEBUG = True 19 | SQLALCHEMY_TRACK_MODIFICATIONS = False 20 | 21 | 22 | class TestingConfig(Config): 23 | """Configurations for Testing.""" 24 | TESTING = True 25 | SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_db' 26 | DEBUG = True 27 | 28 | 29 | class StagingConfig(Config): 30 | """Configurations for Staging.""" 31 | DEBUG = True 32 | 33 | 34 | class ProductionConfig(Config): 35 | """Configurations for Production.""" 36 | DEBUG = False 37 | TESTING = False 38 | 39 | 40 | app_config = { 41 | 'development': DevelopmentConfig, 42 | 'testing': TestingConfig, 43 | 'staging': StagingConfig, 44 | 'production': ProductionConfig, 45 | } 46 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | # class for handling a set of commands 4 | from flask_script import Manager 5 | from app import db, create_app 6 | 7 | # initialize the app with all its configurations 8 | app = create_app(config_name=os.getenv('APP_SETTINGS')) 9 | 10 | # create an instance of class that will handle our commands 11 | manager = Manager(app) 12 | 13 | # define our command for testing called "test" 14 | # Usage: python manage.py test 15 | 16 | 17 | @manager.command 18 | def test(): 19 | """Runs the unit tests without test coverage.""" 20 | tests = unittest.TestLoader().discover('./tests', pattern='test*.py') 21 | result = unittest.TextTestRunner(verbosity=2).run(tests) 22 | if result.wasSuccessful(): 23 | return 0 24 | return 1 25 | 26 | 27 | if __name__ == '__main__': 28 | manager.run() 29 | -------------------------------------------------------------------------------- /migrations/README: -------------------------------------------------------------------------------- 1 | Generic single-database configuration. -------------------------------------------------------------------------------- /migrations/alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # template used to generate migration files 5 | # file_template = %%(rev)s_%%(slug)s 6 | 7 | # set to 'true' to run the environment during 8 | # the 'revision' command, regardless of autogenerate 9 | # revision_environment = false 10 | 11 | 12 | # Logging configuration 13 | [loggers] 14 | keys = root,sqlalchemy,alembic 15 | 16 | [handlers] 17 | keys = console 18 | 19 | [formatters] 20 | keys = generic 21 | 22 | [logger_root] 23 | level = WARN 24 | handlers = console 25 | qualname = 26 | 27 | [logger_sqlalchemy] 28 | level = WARN 29 | handlers = 30 | qualname = sqlalchemy.engine 31 | 32 | [logger_alembic] 33 | level = INFO 34 | handlers = 35 | qualname = alembic 36 | 37 | [handler_console] 38 | class = StreamHandler 39 | args = (sys.stderr,) 40 | level = NOTSET 41 | formatter = generic 42 | 43 | [formatter_generic] 44 | format = %(levelname)-5.5s [%(name)s] %(message)s 45 | datefmt = %H:%M:%S 46 | -------------------------------------------------------------------------------- /migrations/env.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | from alembic import context 3 | from sqlalchemy import engine_from_config, pool 4 | from logging.config import fileConfig 5 | import logging 6 | 7 | # this is the Alembic Config object, which provides 8 | # access to the values within the .ini file in use. 9 | config = context.config 10 | 11 | # Interpret the config file for Python logging. 12 | # This line sets up loggers basically. 13 | fileConfig(config.config_file_name) 14 | logger = logging.getLogger('alembic.env') 15 | 16 | # add your model's MetaData object here 17 | # for 'autogenerate' support 18 | # from myapp import mymodel 19 | # target_metadata = mymodel.Base.metadata 20 | from flask import current_app 21 | config.set_main_option('sqlalchemy.url', 22 | current_app.config.get('SQLALCHEMY_DATABASE_URI')) 23 | target_metadata = current_app.extensions['migrate'].db.metadata 24 | 25 | # other values from the config, defined by the needs of env.py, 26 | # can be acquired: 27 | # my_important_option = config.get_main_option("my_important_option") 28 | # ... etc. 29 | 30 | 31 | def run_migrations_offline(): 32 | """Run migrations in 'offline' mode. 33 | 34 | This configures the context with just a URL 35 | and not an Engine, though an Engine is acceptable 36 | here as well. By skipping the Engine creation 37 | we don't even need a DBAPI to be available. 38 | 39 | Calls to context.execute() here emit the given string to the 40 | script output. 41 | 42 | """ 43 | url = config.get_main_option("sqlalchemy.url") 44 | context.configure(url=url) 45 | 46 | with context.begin_transaction(): 47 | context.run_migrations() 48 | 49 | 50 | def run_migrations_online(): 51 | """Run migrations in 'online' mode. 52 | 53 | In this scenario we need to create an Engine 54 | and associate a connection with the context. 55 | 56 | """ 57 | 58 | # this callback is used to prevent an auto-migration from being generated 59 | # when there are no changes to the schema 60 | # reference: http://alembic.readthedocs.org/en/latest/cookbook.html 61 | def process_revision_directives(context, revision, directives): 62 | if getattr(config.cmd_opts, 'autogenerate', False): 63 | script = directives[0] 64 | if script.upgrade_ops.is_empty(): 65 | directives[:] = [] 66 | logger.info('No changes in schema detected.') 67 | 68 | engine = engine_from_config(config.get_section(config.config_ini_section), 69 | prefix='sqlalchemy.', 70 | poolclass=pool.NullPool) 71 | 72 | connection = engine.connect() 73 | context.configure(connection=connection, 74 | target_metadata=target_metadata, 75 | process_revision_directives=process_revision_directives, 76 | **current_app.extensions['migrate'].configure_args) 77 | 78 | try: 79 | with context.begin_transaction(): 80 | context.run_migrations() 81 | finally: 82 | connection.close() 83 | 84 | if context.is_offline_mode(): 85 | run_migrations_offline() 86 | else: 87 | run_migrations_online() 88 | -------------------------------------------------------------------------------- /migrations/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision | comma,n} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | ${imports if imports else ""} 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = ${repr(up_revision)} 14 | down_revision = ${repr(down_revision)} 15 | branch_labels = ${repr(branch_labels)} 16 | depends_on = ${repr(depends_on)} 17 | 18 | 19 | def upgrade(): 20 | ${upgrades if upgrades else "pass"} 21 | 22 | 23 | def downgrade(): 24 | ${downgrades if downgrades else "pass"} 25 | -------------------------------------------------------------------------------- /migrations/versions/d4c79e829afa_.py: -------------------------------------------------------------------------------- 1 | """empty message 2 | 3 | Revision ID: d4c79e829afa 4 | Revises: 5 | Create Date: 2017-04-30 18:37:12.765820 6 | 7 | """ 8 | from alembic import op 9 | import sqlalchemy as sa 10 | 11 | 12 | # revision identifiers, used by Alembic. 13 | revision = 'd4c79e829afa' 14 | down_revision = None 15 | branch_labels = None 16 | depends_on = None 17 | 18 | 19 | def upgrade(): 20 | # ### commands auto generated by Alembic - please adjust! ### 21 | op.create_table('users', 22 | sa.Column('id', sa.Integer(), nullable=False), 23 | sa.Column('email', sa.String(length=256), nullable=False), 24 | sa.Column('password', sa.String(length=256), nullable=False), 25 | sa.PrimaryKeyConstraint('id'), 26 | sa.UniqueConstraint('email') 27 | ) 28 | op.create_table('bucketlists', 29 | sa.Column('id', sa.Integer(), nullable=False), 30 | sa.Column('name', sa.String(length=255), nullable=True), 31 | sa.Column('date_created', sa.DateTime(), nullable=True), 32 | sa.Column('date_modified', sa.DateTime(), nullable=True), 33 | sa.Column('created_by', sa.Integer(), nullable=True), 34 | sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), 35 | sa.PrimaryKeyConstraint('id') 36 | ) 37 | # ### end Alembic commands ### 38 | 39 | 40 | def downgrade(): 41 | # ### commands auto generated by Alembic - please adjust! ### 42 | op.drop_table('bucketlists') 43 | op.drop_table('users') 44 | # ### end Alembic commands ### 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | alembic~=1.7.5 2 | autoenv~=1.0.0 3 | autopep8~=1.6.0 4 | bcrypt~=3.2.0 5 | certifi~=2021.10.8 6 | cffi~=1.15.0 7 | charset-normalizer~=2.0.10 8 | click~=7.1.2 9 | coverage~=6.2 10 | Flask~=1.1.2 11 | Flask-API~=1.1 12 | Flask-Bcrypt~=0.7.1 13 | Flask-Migrate~=3.1.0 14 | Flask-Script~=2.0.6 15 | Flask-SQLAlchemy~=2.5.1 16 | greenlet~=1.1.2 17 | idna~=3.3 18 | importlib-metadata~=4.10.1 19 | importlib-resources~=5.4.0 20 | itsdangerous~=1.1.0 21 | Jinja2~=2.11.3 22 | Mako~=1.1.6 23 | Markdown~=3.3.6 24 | MarkupSafe~=2.0.1 25 | psycopg2~=2.9.3 26 | pycodestyle~=2.8.0 27 | pycparser~=2.21 28 | PyJWT~=2.3.0 29 | python-coveralls~=2.9.3 30 | python-dotenv~=0.19.2 31 | python-editor~=1.0.4 32 | PyYAML~=6.0 33 | requests~=2.27.1 34 | six~=1.16.0 35 | SQLAlchemy~=1.4.31 36 | toml~=0.10.2 37 | urllib3~=1.26.8 38 | Werkzeug~=1.0.1 39 | zipp~=3.7.0 40 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from app import create_app 4 | 5 | config_name = os.getenv('APP_SETTINGS') 6 | app = create_app(config_name) 7 | 8 | if __name__ == '__main__': 9 | app.run() 10 | -------------------------------------------------------------------------------- /tests/test_auth.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import json 3 | from app import create_app, db 4 | 5 | 6 | class AuthTestCase(unittest.TestCase): 7 | """Test case for the authentication blueprint.""" 8 | 9 | def setUp(self): 10 | """Set up test variables.""" 11 | self.app = create_app(config_name="testing") 12 | self.client = self.app.test_client 13 | self.user_data = { 14 | 'email': 'test@example.com', 15 | 'password': 'test_password' 16 | } 17 | 18 | with self.app.app_context(): 19 | # create all tables 20 | db.session.close() 21 | db.drop_all() 22 | db.create_all() 23 | 24 | def test_registration(self): 25 | """Test user registration works correcty.""" 26 | res = self.client().post('/auth/register', data=self.user_data) 27 | result = json.loads(res.data.decode()) 28 | self.assertEqual( 29 | result['message'], "You registered successfully. Please login.") 30 | self.assertEqual(res.status_code, 201) 31 | 32 | def test_already_registered_user(self): 33 | """Test that a user cannot be registered twice.""" 34 | res = self.client().post('/auth/register', data=self.user_data) 35 | self.assertEqual(res.status_code, 201) 36 | second_res = self.client().post('/auth/register', data=self.user_data) 37 | self.assertEqual(second_res.status_code, 202) 38 | result = json.loads(second_res.data.decode()) 39 | self.assertEqual( 40 | result['message'], "User already exists. Please login.") 41 | 42 | def test_user_login(self): 43 | """Test registered user can login.""" 44 | res = self.client().post('/auth/register', data=self.user_data) 45 | self.assertEqual(res.status_code, 201) 46 | login_res = self.client().post('/auth/login', data=self.user_data) 47 | result = json.loads(login_res.data.decode()) 48 | self.assertEqual(result['message'], "You logged in successfully.") 49 | self.assertEqual(login_res.status_code, 200) 50 | self.assertTrue(result['access_token']) 51 | 52 | def test_non_registered_user_login(self): 53 | """Test non registered users cannot login.""" 54 | not_a_user = { 55 | 'email': 'not_a_user@example.com', 56 | 'password': 'nope' 57 | } 58 | res = self.client().post('/auth/login', data=not_a_user) 59 | result = json.loads(res.data.decode()) 60 | self.assertEqual(res.status_code, 401) 61 | self.assertEqual( 62 | result['message'], "Invalid email or password, Please try again.") 63 | -------------------------------------------------------------------------------- /tests/test_bucketlist.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import json 4 | from app import create_app, db 5 | 6 | 7 | class BucketlistTestCase(unittest.TestCase): 8 | """This class represents the bucketlist test case""" 9 | 10 | def setUp(self): 11 | """Define test variables and initialize app.""" 12 | self.app = create_app(config_name="testing") 13 | self.client = self.app.test_client 14 | self.bucketlist = {'name': 'Go to Borabora for vacay'} 15 | 16 | # binds the app to the current context 17 | with self.app.app_context(): 18 | # create all tables 19 | db.session.close() 20 | db.drop_all() 21 | db.create_all() 22 | 23 | def register_user(self, email="user@test.com", password="test1234"): 24 | user_data = { 25 | 'email': email, 26 | 'password': password 27 | } 28 | return self.client().post('/auth/register', data=user_data) 29 | 30 | def login_user(self, email="user@test.com", password="test1234"): 31 | user_data = { 32 | 'email': email, 33 | 'password': password 34 | } 35 | return self.client().post('/auth/login', data=user_data) 36 | 37 | def test_bucketlist_creation(self): 38 | """Test API can create a bucketlist (POST request)""" 39 | self.register_user() 40 | result = self.login_user() 41 | access_token = json.loads(result.data.decode())['access_token'] 42 | 43 | res = self.client().post( 44 | '/bucketlists/', 45 | headers=dict(Authorization="Bearer " + access_token), 46 | data=self.bucketlist) 47 | 48 | self.assertEqual(res.status_code, 201) 49 | self.assertIn('Go to Borabora', str(res.data)) 50 | 51 | def test_api_can_get_all_bucketlists(self): 52 | """Test API can get a bucketlist (GET request).""" 53 | self.register_user() 54 | result = self.login_user() 55 | access_token = json.loads(result.data.decode())['access_token'] 56 | 57 | res = self.client().post( 58 | '/bucketlists/', 59 | headers={'Authorization': "Bearer " + access_token}, 60 | data=self.bucketlist) 61 | self.assertEqual(res.status_code, 201) 62 | res = self.client().get( 63 | '/bucketlists/', 64 | headers={'Authorization': "Bearer " + access_token}, 65 | ) 66 | self.assertEqual(res.status_code, 200) 67 | self.assertIn('Go to Borabora', str(res.data)) 68 | 69 | def test_api_can_get_bucketlist_by_id(self): 70 | """Test API can get a single bucketlist by using it's id.""" 71 | self.register_user() 72 | result = self.login_user() 73 | access_token = json.loads(result.data.decode())['access_token'] 74 | 75 | rv = self.client().post( 76 | '/bucketlists/', 77 | headers=dict(Authorization="Bearer " + access_token), 78 | data=self.bucketlist) 79 | self.assertEqual(rv.status_code, 201) 80 | results = json.loads(rv.data.decode()) 81 | result = self.client().get( 82 | '/bucketlists/{}'.format(results['id']), 83 | headers=dict(Authorization="Bearer " + access_token)) 84 | self.assertEqual(result.status_code, 200) 85 | self.assertIn('Go to Borabora', str(result.data)) 86 | 87 | def test_bucketlist_can_be_edited(self): 88 | """Test API can edit an existing bucketlist. (PUT request)""" 89 | self.register_user() 90 | result = self.login_user() 91 | access_token = json.loads(result.data.decode())['access_token'] 92 | 93 | rv = self.client().post( 94 | '/bucketlists/', 95 | headers=dict(Authorization="Bearer " + access_token), 96 | data={'name': 'Eat, pray and love'}) 97 | self.assertEqual(rv.status_code, 201) 98 | # get the json with the bucketlist 99 | results = json.loads(rv.data.decode()) 100 | rv = self.client().put( 101 | '/bucketlists/{}'.format(results['id']), 102 | headers=dict(Authorization="Bearer " + access_token), 103 | data={ 104 | "name": "Dont just eat, but also pray and love :-)" 105 | }) 106 | 107 | self.assertEqual(rv.status_code, 200) 108 | results = self.client().get( 109 | '/bucketlists/{}'.format(results['id']), 110 | headers=dict(Authorization="Bearer " + access_token)) 111 | self.assertIn('Dont just eat', str(results.data)) 112 | 113 | def test_bucketlist_deletion(self): 114 | """Test API can delete an existing bucketlist. (DELETE request).""" 115 | self.register_user() 116 | result = self.login_user() 117 | access_token = json.loads(result.data.decode())['access_token'] 118 | 119 | rv = self.client().post( 120 | '/bucketlists/', 121 | headers=dict(Authorization="Bearer " + access_token), 122 | data={'name': 'Eat, pray and love'}) 123 | self.assertEqual(rv.status_code, 201) 124 | # get the bucketlist in json 125 | results = json.loads(rv.data.decode()) 126 | res = self.client().delete( 127 | '/bucketlists/{}'.format(results['id']), 128 | headers=dict(Authorization="Bearer " + access_token),) 129 | self.assertEqual(res.status_code, 200) 130 | # Test to see if it exists, should return a 404 131 | result = self.client().get( 132 | '/bucketlists/1', 133 | headers=dict(Authorization="Bearer " + access_token)) 134 | self.assertEqual(result.status_code, 404) 135 | 136 | 137 | # Make the tests conveniently executable 138 | if __name__ == "__main__": 139 | unittest.main() 140 | --------------------------------------------------------------------------------