Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User Management backend - Base - DB migrations #39

Closed
wants to merge 68 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
68 commits
Select commit Hold shift + click to select a range
a156d92
Restructured project
DoRTaL94 Apr 25, 2020
4e7656f
Updated Vagrantfile
DoRTaL94 Apr 25, 2020
33b715c
Made edison folder a module
DoRTaL94 Apr 25, 2020
2f69aa4
Added config file
DoRTaL94 Apr 25, 2020
54a6d85
Set FLASK_ENV environment var
DoRTaL94 Apr 25, 2020
7ba1ebc
Added config file
DoRTaL94 Apr 25, 2020
934df87
Added db support
DoRTaL94 Apr 25, 2020
a43367c
Updated requirements
DoRTaL94 Apr 25, 2020
2d56d44
Updated Vagrantfile
DoRTaL94 Apr 25, 2020
e0e2129
Added db models
DoRTaL94 Apr 25, 2020
bc0d2a1
Added Flask-Migrate extension
DoRTaL94 Apr 25, 2020
dc33484
Removed unnecessary comment
DoRTaL94 Apr 26, 2020
2acd8a7
Added db auto creation on vagrant up
DoRTaL94 Apr 27, 2020
cbba2fe
Merge branch 'db-support' of https://github.com/DoRTaL94/edison into …
DoRTaL94 Apr 27, 2020
64ec2e4
Changed comment in Vagrantfile
DoRTaL94 May 2, 2020
3345ec0
Merge branch 'project-restructure' of https://github.com/DoRTaL94/edi…
DoRTaL94 May 2, 2020
ea6a71a
Merge branch 'config' of https://github.com/DoRTaL94/edison into db-s…
DoRTaL94 May 2, 2020
0b13b2e
Merge branch 'db-support' of https://github.com/DoRTaL94/edison into …
DoRTaL94 May 2, 2020
932511b
Merge pull request #36 from DoRTaL94/project-restructure
lmilbaum May 3, 2020
6949701
Merge branch 'master' of https://www.github.com/knowabli/edison into …
DoRTaL94 May 3, 2020
400e700
Merge pull request #6 from DoRTaL94/config
RoniRush May 4, 2020
997b110
1. remove unnecessary dictionary variable and simplify the function
RoniRush May 4, 2020
548060d
Merge pull request #1 from RoniRush/config
RoniRush May 4, 2020
a8de0cb
few changes in the docstring
RoniRush May 4, 2020
2e4d198
Merge pull request #2 from RoniRush/config
RoniRush May 4, 2020
7a9d486
remove space line
RoniRush May 4, 2020
f1988af
Merge pull request #3 from RoniRush/config
RoniRush May 4, 2020
4159b68
fix indentation in docstring
RoniRush May 4, 2020
14f70dd
Merge pull request #4 from RoniRush/config
RoniRush May 4, 2020
6170756
the front side
naamaCohen1 Apr 22, 2020
654f5d8
changing the front side
naamaCohen1 Apr 23, 2020
48d0ed6
changing the run from home page
naamaCohen1 Apr 23, 2020
d4f9d20
cleanPR
naamaCohen1 May 5, 2020
0ed356c
adding deleted files
naamaCohen1 May 5, 2020
c59bff5
adding a newline
naamaCohen1 May 6, 2020
9d2e64c
Merge pull request #35 from naamaCohen1/frontTemplate
naamaCohen1 May 7, 2020
1609057
add add policy function and ordering the home & layout so the footer …
naamaCohen1 May 7, 2020
2fcc7e9
chaning the files according to the PR
naamaCohen1 May 9, 2020
a82e7a8
changinh according to the format
naamaCohen1 May 9, 2020
4dd8c68
changing variables names and ID's in policy.html
naamaCohen1 May 9, 2020
2b7031f
delete consol.log from this file
naamaCohen1 May 9, 2020
d7b20f8
Merge pull request #41 from naamaCohen1/policy
naamaCohen1 May 10, 2020
48d13c5
fixed the wrong checking - if a class is subclass of config
RoniRush May 10, 2020
a65a7c0
Merge pull request #5 from RoniRush/config
RoniRush May 10, 2020
12ddf41
Merge pull request #37 from DoRTaL94/config
simzacks May 10, 2020
7da9125
adding show policies
naamaCohen1 May 10, 2020
77d67cf
Merge branch 'master' of https://www.github.com/knowabli/edison into …
DoRTaL94 May 10, 2020
0575f8a
changing the id in html & js to another convention and changing as re…
naamaCohen1 May 10, 2020
3d4251a
changing according to string formmting
naamaCohen1 May 10, 2020
e0d9b46
changing the variables name and try to be in JSstandart
naamaCohen1 May 10, 2020
2cbf890
putting post function in command
naamaCohen1 May 10, 2020
6541bf0
putting the example array in a new class
naamaCohen1 May 11, 2020
1f3cffc
changing the class to get a json Array & continue changing to string …
naamaCohen1 May 11, 2020
cf05078
Merge pull request #42 from naamaCohen1/show_polices
naamaCohen1 May 11, 2020
384a58c
Updated .gitignore
ahinoamta May 13, 2020
02fa0d2
Imported DB Models to app.py so the DB tables will be created
ahinoamta May 13, 2020
1c34a90
Deleted Token model and some of User model to minimize the PR
ahinoamta May 13, 2020
25b67f3
Merge pull request #38 from DoRTaL94/db-support
simzacks May 17, 2020
32ddf09
enter a varuable form global to private
naamaCohen1 May 17, 2020
db96341
changing fron in count condition to set cout condition
naamaCohen1 May 18, 2020
c8c773c
changing the icrease count condition, and changing the create ements …
naamaCohen1 May 18, 2020
b5cac71
Merge pull request #44 from naamaCohen1/update_button
naamaCohen1 May 18, 2020
7bf330b
misspelling changing
naamaCohen1 May 18, 2020
0160a87
Added Flask-Migrate extension
DoRTaL94 Apr 25, 2020
f9bac1f
Deleted DB restore process
ahinoamta May 19, 2020
d86a25e
Added pytest to requirements.txt
ahinoamta May 19, 2020
6bc32bb
Merge branch 'db-migrations' of https://github.com/DoRTaL94/edison in…
ahinoamta May 19, 2020
3dcd5dc
Updated .gitignore
ahinoamta May 19, 2020
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
29 changes: 25 additions & 4 deletions Vagrantfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
FLASK_PORT=5000
POSTGRESQL_PORT=5432
db_file_exists = "test -f /vagrant/edison/db.sql"
restore_db = "sudo -u postgres psql edison < /vagrant/edison/db.sql"
db_restored_msg = "echo \"Database restored.\""
db_not_exists_msg = "echo \"db.sql not exists.\""
try_restore_db = "bash -c '#{db_file_exists} && #{restore_db} && #{db_restored_msg} || #{db_not_exists_msg}'"
save_db_data = "sudo -u postgres pg_dump edison > /vagrant/edison/db.sql"

Vagrant.configure("2") do |config|
config.trigger.before :destroy do |trigger|
trigger.info = "Saving database data inside synced folder..."
trigger.run_remote = {inline: "#{save_db_data}"}
end

config.trigger.after :up do |trigger|
trigger.info = "Trying to restore database from /vagrant/edison/db.sql..."
trigger.run_remote = {inline: "#{try_restore_db}"}
end

config.vm.box = "ubuntu/bionic64"
config.vm.provision :shell, path: "setup.sh"
config.vm.network :forwarded_port, guest: FLASK_PORT, host: FLASK_PORT
config.vm.network :forwarded_port, guest: POSTGRESQL_PORT, host: POSTGRESQL_PORT
config.vm.network "private_network", type: "dhcp"
config.vm.provider "virtualbox" do |v|
v.gui = false
v.name = "Edison_test"
Expand All @@ -14,3 +27,11 @@ Vagrant.configure("2") do |config|
end

end

# Fixes a dhcp configuration conflict of the private network.
# Issue: https://github.com/hashicorp/vagrant/issues/8878
class VagrantPlugins::ProviderVirtualBox::Action::Network
def dhcp_server_matches_config?(dhcp_server, config)
true
end
end
12 changes: 12 additions & 0 deletions edison/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from edison.config import get_config_object


# Put app here so the entire app could import it.
app = Flask(__name__)
app.config.from_object(get_config_object(app.config["ENV"]))
basedir = os.path.abspath(os.path.dirname(__file__))
db = SQLAlchemy(app)
21 changes: 21 additions & 0 deletions edison/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import edison

from flask import render_template
from flask_migrate import Migrate


app = edison.app
db = edison.db
migrate = Migrate(app, db)

# Creates all tables defined in the database models and the only ones that are not created yet.
# If there's any change in the database models you should perform a migration to apply this change in the database itself.
# More about database migrations can be found in /edison/migrations/README.
db.create_all()

@app.route("/")
def index():
return render_template('index.html')

if __name__ == "__main__":
app.run(host='0.0.0.0')
32 changes: 32 additions & 0 deletions edison/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import secrets
import importlib, inspect
import sys, inspect

config_dict = {}

# If config_dict is empty this function builds it dynamically
# and returns the appropriate config object path.
def get_config_object(env_keyword: str):
if(len(config_dict) == 0):
# Iterating through all config.py members
for name, obj in inspect.getmembers(sys.modules[__name__]):
# We're interested only with the derived classes of the Config class
if inspect.isclass(obj) and name != "Config":
config_dict[obj.ENV_KEYWORD] = ".".join([obj.__module__, name])

return config_dict[env_keyword]

class Config:
ENV_KEYWORD = ""
DEBUG = False
# Turns off the Flask-SQLAlchemy event system
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:[email protected]/edison'

# PostgreSQL connection string should be updated once an actual production environment is established.
class ProductionConfig(Config):
ENV_KEYWORD = "production"

class DevelopmentConfig(Config):
ENV_KEYWORD = "development"
DEBUG = True
43 changes: 43 additions & 0 deletions edison/migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
This information and more can be found at - https://flask-migrate.readthedocs.io/

The content of edison/migrations folder is auto-created by Flask-Migrate extension.
Flask-Migrate is an extension that configures Alembic in the proper way to work with Flask and Flask-SQLAlchemy application.
In terms of the actual database migrations, everything is handled by Alembic so you get exactly the same functionality.

FAQ

1. Why to use database migrations ?

Database migrations basically track granular changes to our database schema.
These granular changes are typically reflected as separate scripted files.
Every time we make a change to our database schema we should perform a migration.
This migration creates a new file that describes our current database schema inside edison/migrations/versions.
That way we could downgrade or upgrade our database schema to different versions if needed.

2. When to use database migration ?

You should perform a database migration on any change you make to the database models.
When a migration is performed it applies those changes to the database itself.

3. How to perform a database migration ?

- First, we need to initialize our migrations folder (If it's not already created).
To do so you should first make sure to define the Flask app path inside FLASK_APP environment variable,
and then execute the following command:
flask db init
Executing this command will create the migrations folder inside /home/vagrant/migrations,
which is not good for us because we want it to be created in our project directory.
So we simply need to add the directory flag:
flask db init --directory /vagrant/edison/migrations

- Then, we should perform the migration as follow:
flask db migrate -m "<migration message>" --directory /vagrant/edison/migrations
It will create a new version file of the database schema inside edison/migrations/versions.

- Last, we need to apply this migration on the database itself by executing:
flask db upgrade --directory /vagrant/edison/migrations.

4. How to downgrade the database schema ?

Simply execute the following command:
flask db downgrade --directory /vagrant/edison/migrations.
45 changes: 45 additions & 0 deletions edison/migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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

[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

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

import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

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
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.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 = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)

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 edison/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"}
2 changes: 2 additions & 0 deletions edison/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .token import Token
from .user import User
12 changes: 12 additions & 0 deletions edison/models/token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from edison import db


class Token(db.Model):
__tablename__ = 'token_blacklist'

id = db.Column(db.Integer, primary_key=True)
jti = db.Column(db.String(150), nullable=False, unique=True)
creation_timestamp = db.Column(db.TIMESTAMP(timezone=False), nullable=False)

def __repr__(self):
return f"<Token: jti: {self.jti}, creation time: {self.creation_timestamp}>"
25 changes: 25 additions & 0 deletions edison/models/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from edison import db


class User(db.Model):
__tablename__ = 'users'
__table_args__ = {'extend_existing': True}

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
password = db.Column(db.String(150), nullable=False)
first_name = db.Column(db.String(50), nullable=False)
last_name = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(150), nullable=False)

def to_json(self):
return {
"username": self.username,
"first_name": self.first_name,
"last_name": self.last_name,
"email": self.email
}

def __repr__(self):
return f"<User: id = {self.id}, first_name = {self.first_name}, " \
f"last_name = {self.last_name}, username = {self.username}, email = {self.email}>"
File renamed without changes
File renamed without changes.
10 changes: 0 additions & 10 deletions flask_init.py

This file was deleted.

3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
Flask==1.1.1
flask-sqlalchemy==2.4.1
psycopg2-binary==2.8.5
Flask-Migrate==2.5.3
Loading