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
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from src.ext import db
class Tour(db.Model):
from src.models.base import BaseModel
class Tour(BaseModel):
__tablename__ = "tours"
id = db.Column(db.Integer, primary_key=True)
country = db.Column(db.String)
Expand Down
1 change: 1 addition & 0 deletions Chapter08_User/Projects/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

მაგალითი:
- სახელი გვარი | [პროექტი](/მისამართი)
- სალომე პაპაშვილი | [GlobeTales](/Chapter08_User/Projects/Salome_Papashvili/app.py)

### 2025 ზაფხული
5 changes: 5 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from src import create_app
app = create_app()

if __name__ == "__main__":
app.run(debug=True)
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
50 changes: 50 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/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 Chapter08_User/Projects/Salome_Papashvili/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()
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"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Flask==3.1.0
Flask-Login==0.6.3
Flask-Migrate==4.1.0
Flask-SQLAlchemy==3.1.1
Flask-WTF==1.2.2
uwsgi
34 changes: 34 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from flask import Flask
from src.commands import init_db, populate_db
from src.config import Config
from src.ext import db, migrate, login_manager
from src.views import main_blueprint, auth_blueprint, product_blueprint
from src.models import User
BLUEPRINTS = [main_blueprint, product_blueprint, auth_blueprint]
COMMANDS = [init_db, populate_db]

def create_app():
app = Flask(__name__)
app.config.from_object(Config)

register_extensions(app)
register_blueprints(app)
register_commands(app)
return app

def register_extensions(app):
db.init_app(app)
migrate.init_app(app, db)
login_manager.init_app(app)
login_manager.login_view = 'auth.login'
@login_manager.user_loader
def load_user(_id):
return User.query.get(_id)

def register_blueprints(app):
for blueprint in BLUEPRINTS:
app.register_blueprint(blueprint)

def register_commands(app):
for command in COMMANDS:
app.cli.add_command(command)
83 changes: 83 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from flask.cli import with_appcontext
import click
from src.ext import db
from src.models import Tour, User

@click.command("init_db")
@with_appcontext
def init_db():
click.echo("Initializing database...")
db.drop_all()
db.create_all()
click.echo("Initialized database")


@click.command("populate_db")
@with_appcontext
def populate_db():
tours = [
{
"id": 0,
"country": "Italy",
"title": "Rome Ancient Wonders Tour",
"description": "Discover the Colosseum, Roman Forum, and Vatican City.",
"price": 279.99,
"currency": "EUR",
"image": "https://www.agoda.com/wp-content/uploads/2024/08/Colosseum-Rome-Featured.jpg",
"duration": "4 days",
},
{
"id": 1,
"country": "Egypt",
"title": "Cairo & Pyramids Adventure",
"description": "Visit the Great Pyramids of Giza and the Egyptian Museum.",
"price": 349.99,
"currency": "USD",
"image": "https://upload.wikimedia.org/wikipedia/commons/a/af/All_Gizah_Pyramids.jpg",
"duration": "5 days",
},
{
"id": 2,
"country": "Australia",
"title": "Sydney & Blue Mountains",
"description": "Explore Sydney Opera House, Harbour Bridge, and Blue Mountains.",
"price": 499.99,
"currency": "AUD",
"image": "https://www.sydneytravelguide.com.au/wp-content/uploads/2024/09/sydney-australia.jpg",
"duration": "6 days",
},
{
"id": 3,
"country": "Spain",
"title": "Barcelona",
"description": "Admire Sagrada Familia, Park Güell, and Gothic Quarter.",
"price": 259.99,
"currency": "EUR",
"image": "https://www.introducingbarcelona.com/f/espana/barcelona/barcelona.jpg",
"duration": "3 days",
},
{
"id": 4,
"country": "Turkey",
"title": "Istanbul Heritage Tour",
"description": "Visit Hagia Sophia, Blue Mosque, and Grand Bazaar.",
"price": 199.99,
"currency": "USD",
"image": "https://deih43ym53wif.cloudfront.net/small_cappadocia-turkey-shutterstock_1320608780_9fc0781106.jpeg",
"duration": "4 days",
}
]

for tour in tours:
new_tour = Tour(country=tour["country"],
title=tour["title"],
description=tour["description"],
price=tour["price"],
currency=tour["currency"],
image=tour["image"],
duration=tour["duration"])
db.session.add(new_tour)
db.session.commit()

# Admin
User(username="Admin", password="password12345", profile_image="admin.png", role="Admin").create()
7 changes: 7 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from os import path

class Config(object):
BASE_DIRECTORY = path.abspath(path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = "sqlite:///database.db"
SECRET_KEY = "GJFKLDJKljklhhjkhjk@595jijkjd"
UPLOAD_PATH = path.join(BASE_DIRECTORY, "static", "upload")
6 changes: 6 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/ext.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from src.models.product import Tour
from src.models.person import Person
from src.models.user import User
16 changes: 16 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/models/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from src.ext import db

class BaseModel(db.Model):
__abstract__ = True
def create(self, commit=True):
db.session.add(self)
if commit:
self.save()

def save(self):
db.session.commit()

def delete(self, commit=True):
db.session.delete(self)
if commit:
self.save()
13 changes: 13 additions & 0 deletions Chapter08_User/Projects/Salome_Papashvili/src/models/person.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from src.ext import db
from src.models.base import BaseModel
class Person(BaseModel):
__tablename__ = "persons"

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
email = db.Column(db.String, nullable=False, unique=True)
password = db.Column(db.String, nullable=False)
birthday = db.Column(db.Date, nullable=False)
gender = db.Column(db.String, nullable=False)
country = db.Column(db.String, nullable=False)
profile_image = db.Column(db.String)
Loading