Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from decouple import config as decouple_config
import os

BASE_DIR = os.path.dirname(os.path.realpath(__file__))


class Config:
SECRET_KEY = decouple_config('SECRET_KEY')
SQLALCHEMY_TRACK_MODIFICAITONS = decouple_config('SQLALCHEMY_TRACK_MODIFICAITONS', cast = bool)

class DevConfig(Config):
SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(BASE_DIR, 'dev.db')
DEBUG = True
SQLALCHEMY_ECHO = True

class ProdConfig(Config):
pass

class TestConfig(Config):
pass

Binary file added dev.db
Binary file not shown.
3 changes: 3 additions & 0 deletions exts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
182 changes: 173 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,178 @@
import os
from flask import Flask
from flask import Flask, request,jsonify
from flask_restx import Api,Resource,fields
from config import DevConfig
from model import Recipe,User
from exts import db
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import JWTManager,create_access_token,create_refresh_token,jwt_required

app = Flask(__name__)

@app.route('/')
def index():
return "<h1>Welcome to PipeOps</h1>"


app = Flask(__name__) # Var keep flask obj

app.config.from_object(DevConfig)

db.init_app(app)

migrate = Migrate(app, db)

JWTManager(app)

api = Api(app, doc='/docs')

# model (serializer) # This is use to return responses.
recipe_model = api.model(
"Recipe",
{
'id': fields.Integer(),
'title': fields.String(),
'description': fields.String()
}
)


signUp_model = api.model(
"SignUp",
{
'username': fields.String(),
'email': fields.String(),
'password': fields.String()
}
)

login_model = api.model(
'Login',{
'username': fields.String(),
'password': fields.String()
}
)

# route Api
@api.route('/home')
class HomeResource(Resource):
def get(self):
return {"message": "Welcome to Harmony"}

@api.route('/signup')
class SignUp(Resource):

@api.expect(signUp_model)
def post(self):
data = request.get_json()

username = data.get('username')
db_user = User.query.filter_by(username = username).first()

if db_user is not None:
return jsonify({"message": f"User with username {username} already exit."})


new_user = User(
username = data.get('username'),
email = data.get('email'),
password = generate_password_hash(data.get('password'))
)

new_user.save()

return jsonify({'message': 'User created sucessful'})


@api.route('/login')
class Login(Resource):

@api.expect(login_model)
def post(self):
data = request.get_json()

username = data.get('username')
password = data.get('password')

db_user = User.query_filter_by(username = username).first()

if db_user and check_password_hash(db_user.password, password):

access_token = create_access_token(identity = db_user.username)
refresh_token = create_refresh_token(identity = db_user.username)

return jsonify(
{'access_token': access_token, 'refresh_token': refresh_token}
)


@api.route('/recipes')
class RecipesResource(Resource):

@api.marshal_list_with(recipe_model) # return list of obj
def get(self):
"""Get all recipes"""
recipes = Recipe.query.all()

return recipes

@api.marshal_with(recipe_model) # return a single obj
@api.expect(recipe_model)
@jwt_required()
def post(self):
"""Create a new recipe"""
data = request.get_json() # This enable us to acquire the client data (head, body, title,,,....) from the request

new_recipe = Recipe(
title = data.get("title"),
description = data.get('description')
)

new_recipe.save()

return new_recipe, 201

@api.route('/recipe/<int:id>')
class RecipeResource(Resource):

@api.marshal_with(recipe_model)
def get(self, id):
"""Get a recipe by id"""
recipe = Recipe.query.get_or_404(id)
return recipe

@api.marshal_with(recipe_model)
@jwt_required()
def put(self, id):
"""Update a recipe by id"""

recipe_to_update = Recipe.query.get_or_404(id)

data = request.get_json()

recipe_to_update.update(data.get('title'), data.get('description'))

return recipe_to_update

@api.marshal_with(recipe_model)
@jwt_required()
def delete(self, id):
"""Delete a recipe by id"""

recipe_to_delete = Recipe.query.get_or_404(id)

recipe_to_delete.delete()

return recipe_to_delete

@app.shell_context_processor
def make_shell_context():
return {
"db":db,
"Recipe": Recipe
}

if __name__ == '__main__':
# Use PORT environment variable if available, or default to 5000
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
app.run()


# if __name__ == '__main__':
# # Use PORT environment variable if available, or default to 5000
# port = int(os.environ.get('PORT', 5000))
# app.run(host='0.0.0.0', port=port)
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
50 changes: 50 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
113 changes: 113 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig

from flask import current_app

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')


def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine


def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')


# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata


def run_migrations_offline():
"""Run migrations in 'offline' mode.

This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.

Calls to context.execute() here emit the given string to the
script output.

"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives

connectable = get_engine()

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
**conf_args
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Loading