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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.venv/
venv/
app*.db
__pycache__
Expand Down
18 changes: 17 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from sqlalchemy import MetaData

from .util import dateformat, DateConverter

Expand All @@ -17,8 +19,22 @@
except ImportError:
print('No custom config found.')

# SQL constraints naming convention
convention = {
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=convention)

# init models database
db = SQLAlchemy(app)
db = SQLAlchemy(app, metadata=metadata)
# migrations manager
# render_as_batch works arond SQLite's ALTER TABLE limitations
migrate = Migrate(app, db, render_as_batch=True)

# init user management
login_manager = LoginManager(app)
bcrypt = Bcrypt(app)
Expand Down
6 changes: 3 additions & 3 deletions app/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from app.models import Place


def get_places():
return Place.query
def get_active_places():
return Place.query.filter(Place.archived == False)


class NightForm(FlaskForm):
Expand All @@ -22,7 +22,7 @@ class NightForm(FlaskForm):
amount = TimeDeltaField('Durée', validators=[InputRequired()])
alone = BooleanField('Seul')
sleepless = BooleanField('Nuit blanche')
place = QuerySelectField('Lieu', query_factory=get_places, validators=[InputRequired()])
place = QuerySelectField('Lieu', query_factory=get_active_places, validators=[InputRequired()])

def to_bed_datetime(self):
date = self.day.data
Expand Down
4 changes: 3 additions & 1 deletion app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class Place(db.Model):
__tablename__ = 'places'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), index=True, unique=True)
archived = db.Column(db.Boolean, nullable=False, server_default='0')
_latitude = db.Column(db.Float)
_longitude = db.Column(db.Float)
_timezone = db.Column(db.String(50))
Expand Down Expand Up @@ -141,7 +142,8 @@ def serialize(self):
'name': self.name,
'lat': self.latitude,
'lon': self.longitude,
'tz': self.timezone
'tz': self.timezone,
'archived': self.archived
}


Expand Down
3 changes: 3 additions & 0 deletions app/templates/places-home.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
</div>
<div class="tile-action">
<a href="{{url_for('place', pid=p.id)}}" class="btn">Modifier</a>
<a href="{{url_for('archive_place', pid=p.id)}}" class="btn">
{% if p.archived %}Activer{% else %}Désactiver{% endif %}
</a>
{% if p.nights|length == 0 %}
<a href="{{url_for('delete_place', pid=p.id)}}" class="btn btn-error">Supprimer</a>
{% endif %}
Expand Down
14 changes: 14 additions & 0 deletions app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ def place(pid):
return render_template('place-form.html', form=form)


@app.route('/places/archive/<int:pid>')
@login_required
def archive_place(pid):
"""
Toggle the place's archived status.
"""
p = Place.query.get_or_404(pid)

p.archived = not p.archived
db.session.commit()

return redirect(url_for('show_places'))


@app.route('/places/delete/<int:pid>')
@login_required
def delete_place(pid):
Expand Down
1 change: 1 addition & 0 deletions default_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
basedir = os.path.abspath(os.path.dirname(__file__))
# sqlalchemy
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
# reload on code change
DEBUG = False
# flask-wtforms - csrf
Expand Down
11 changes: 0 additions & 11 deletions manage.py

This file was deleted.

1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
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
90 changes: 90 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
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.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.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"}
61 changes: 61 additions & 0 deletions migrations/versions/13b09aff19df_add_archived_column_for_places.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Initial migration

Revision ID: 13b09aff19df
Revises:
Create Date: 2022-11-26 10:10:23.031654

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '13b09aff19df'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('nights', schema=None) as batch_op:
batch_op.alter_column('day',
existing_type=sa.DATE(),
nullable=True)
batch_op.alter_column('sleepless',
existing_type=sa.BOOLEAN(),
nullable=True)
batch_op.alter_column('alone',
existing_type=sa.BOOLEAN(),
nullable=True)
batch_op.alter_column('place_id',
existing_type=sa.INTEGER(),
nullable=True)
batch_op.create_unique_constraint(None, ['to_rise'])
batch_op.create_unique_constraint(None, ['to_bed'])

with op.batch_alter_table('places', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_places_name'), ['name'], unique=True)

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('nights', schema=None) as batch_op:
batch_op.drop_constraint('uq_nights_to_rise', type_='unique')
batch_op.drop_constraint('uq_nights_to_bed', type_='unique')
batch_op.alter_column('place_id',
existing_type=sa.INTEGER(),
nullable=False)
batch_op.alter_column('alone',
existing_type=sa.BOOLEAN(),
nullable=False)
batch_op.alter_column('sleepless',
existing_type=sa.BOOLEAN(),
nullable=False)
batch_op.alter_column('day',
existing_type=sa.DATE(),
nullable=False)

# ### end Alembic commands ###
38 changes: 38 additions & 0 deletions migrations/versions/8d4773ad4ccc_add_archived_column_to_places.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Add archived column to places

Revision ID: 8d4773ad4ccc
Revises: 13b09aff19df
Create Date: 2022-11-26 15:27:10.413149

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '8d4773ad4ccc'
down_revision = '13b09aff19df'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('nights', schema=None) as batch_op:
batch_op.create_unique_constraint(batch_op.f('uq_nights_day'), ['day'])

with op.batch_alter_table('places', schema=None) as batch_op:
batch_op.add_column(sa.Column('archived', sa.Boolean(), server_default='0', nullable=False))

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('places', schema=None) as batch_op:
batch_op.drop_column('archived')

with op.batch_alter_table('nights', schema=None) as batch_op:
batch_op.drop_constraint(batch_op.f('uq_nights_day'), type_='unique')

# ### end Alembic commands ###
Loading