Skip to content

Commit

Permalink
complete Assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
otienosteve committed Sep 11, 2023
1 parent 9131278 commit 98743f8
Show file tree
Hide file tree
Showing 9 changed files with 525 additions and 177 deletions.
3 changes: 2 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ importlib-metadata = "6.0.0"
importlib-resources = "5.10.0"
ipdb = "0.13.9"
pytest = "7.1.3"
sqlalchemy = "==1.4"

[requires]
python_full_version = "3.8.13"
python_full_version = "3.10"
440 changes: 264 additions & 176 deletions Pipfile.lock

Large diffs are not rendered by default.

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
91 changes: 91 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
from __future__ import with_statement

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')

# 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',
str(current_app.extensions['migrate'].db.get_engine().url).replace(
'%', '%%'))
target_metadata = current_app.extensions['migrate'].db.metadata

# 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 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=target_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.')

connectable = current_app.extensions['migrate'].db.get_engine()

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)

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


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
47 changes: 47 additions & 0 deletions migrations/versions/5912c9d88958_initial_revision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Initial Revision
Revision ID: 5912c9d88958
Revises:
Create Date: 2023-09-11 09:35:24.945410
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '5912c9d88958'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('authors',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('phone_number', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('content', sa.String(), nullable=True),
sa.Column('category', sa.String(), nullable=True),
sa.Column('summary', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('posts')
op.drop_table('authors')
# ### end Alembic commands ###
Binary file added server/app.db
Binary file not shown.
46 changes: 46 additions & 0 deletions server/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import validates
from sqlalchemy.exc import IntegrityError, CompileError


db = SQLAlchemy()

class Author(db.Model):
Expand All @@ -12,6 +15,22 @@ class Author(db.Model):
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, onupdate=db.func.now())

@validates('name')
def validate_name(cls, key, name):
existing_name = Author.query.filter_by(name=name).first()
if not name:
raise ValueError("Name must be added")
if existing_name:
raise IntegrityError("Name already exists in the Database")
return name

@validates('phone_number')
def validate_phone(cls, key, phone_number):
if 10 < len(phone_number) > 10:
raise ValueError("Phone number must be 10 digits")
return phone_number


def __repr__(self):
return f'Author(id={self.id}, name={self.name})'

Expand All @@ -27,6 +46,33 @@ class Post(db.Model):
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, onupdate=db.func.now())

@validates('title')
def validate_title(cls, key, title):
if not title:
raise ValueError("Title must be added")
if "Won't Believe" not in title or "Secret" not in title or "Top" not in title or "Guess" not in title:
raise ValueError("Not ClickBaitable")
return title

@validates('content')
def validate_content(cls, key, content):
if len(content) < 250 :
raise ValueError("The content Length Must be greater than 250 characters")
return content

@validates('summary')
def validate_summary(cls, key, summary):
if len(summary) > 250:
raise ValueError("The content Length Should be Less than 250 characters")
return summary

@validates('category')
def validate_category(cls, key, category):
if category!='Fiction' and category!='Non-Fiction':
raise ValueError('The Values are not Valid')
return category



def __repr__(self):
return f'Post(id={self.id}, title={self.title} content={self.content}, summary={self.summary})'

0 comments on commit 98743f8

Please sign in to comment.