Started creating the api
This commit is contained in:
parent
43768d76d8
commit
1f2f6070ef
|
|
@ -0,0 +1,2 @@
|
|||
.venv
|
||||
/instance
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
alembic==1.13.1
|
||||
blinker==1.7.0
|
||||
click==8.1.7
|
||||
Flask==3.0.3
|
||||
Flask-Migrate==4.0.7
|
||||
Flask-SQLAlchemy==3.1.1
|
||||
greenlet==3.0.3
|
||||
itsdangerous==2.1.2
|
||||
Jinja2==3.1.3
|
||||
Mako==1.3.3
|
||||
MarkupSafe==2.1.5
|
||||
python-dotenv==1.0.1
|
||||
SQLAlchemy==2.0.29
|
||||
typing_extensions==4.11.0
|
||||
Werkzeug==3.0.2
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
# Configuration Mode => development, testing, staging, or production
|
||||
CONFIG_MODE = development
|
||||
|
||||
# POSTGRESQL_DATABASE_URI => 'postgresql+psycopg2://user:password@host:port/database'
|
||||
DEVELOPMENT_DATABASE_URL = 'sqlite:///DevDB.db'
|
||||
TEST_DATABASE_URL = 'sqlite:///TestDB.db'
|
||||
STAGING_DATABASE_URL = 'sqlite:///StagingDB.db'
|
||||
PRODUCTION_DATABASE_URL =
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,44 @@
|
|||
from flask import request, jsonify
|
||||
import uuid
|
||||
from ..app import db
|
||||
from .models import Film
|
||||
|
||||
def list_all_films_controller():
|
||||
films = Film.query.all()
|
||||
response = []
|
||||
for film in films: response.append(film.toDict())
|
||||
return jsonify(response)
|
||||
|
||||
def create_film_controller():
|
||||
request_form = request.form.to_dict()
|
||||
print(request_form)
|
||||
new_film = Film(
|
||||
name = request_form['name'],
|
||||
ISO = request_form['ISO'],
|
||||
Push_Pull = request_form['Push_Pull'],
|
||||
fk_FilmManufacturer_id = request_form["manufacturerID"]
|
||||
)
|
||||
db.session.add(new_film)
|
||||
db.session.commit()
|
||||
response = Film.query.all()
|
||||
return(jsonify(request_form))
|
||||
|
||||
def retrieve_film_controller(film_id):
|
||||
response = Film.query.get(film_id).toDict()
|
||||
return jsonify(response)
|
||||
|
||||
def update_film_controller(film_id):
|
||||
request_form = request.form.to_dict()
|
||||
film = Film.query.get(film_id)
|
||||
film.name = request_form['name']
|
||||
film.ISO = request_form['ISO']
|
||||
film.Push_Pull = request_form['Push_Pull']
|
||||
film.fk_FilmManufacturer_id = request_form["manufacturerID"]
|
||||
db.session.commit()
|
||||
response = Film.query.get(film_id).toDict()
|
||||
return jsonify(response)
|
||||
|
||||
def delete_film_controller(film_id):
|
||||
Film.query.filter_by(id=film_id).delete()
|
||||
db.session.commit()
|
||||
return f"Film with ID={film_id} was removed successfully"
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
from sqlalchemy import inspect
|
||||
from datetime import datetime
|
||||
|
||||
from ..app import db
|
||||
|
||||
class Film(db.Model):
|
||||
id = db.Column(db.Integer(),primary_key=True,nullable=False,unique=True, autoincrement=True)
|
||||
name = db.Column(db.String(255))
|
||||
ISO = db.Column(db.String(10))
|
||||
Push_Pull = db.Column(db.String(10))
|
||||
fk_FilmManufacturer_id = db.Column(db.Integer(),db.ForeignKey("film_manufacturer.id"))
|
||||
filmmanufacturer = db.relationship("FilmManufacturer",back_populates='films')
|
||||
def toDict(self):
|
||||
return {
|
||||
c.key: getattr(self,c.key) for c in inspect(self).mapper.column_attrs
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
from flask import request
|
||||
|
||||
from ..app import app
|
||||
from .controllers import list_all_films_controller,create_film_controller,retrieve_film_controller,update_film_controller,delete_film_controller
|
||||
|
||||
@app.route("/Films",methods=["GET","POST"])
|
||||
def list_all_create_films():
|
||||
if request.method == 'GET' : return list_all_films_controller()
|
||||
if request.method == 'POST' : return create_film_controller()
|
||||
|
||||
@app.route("/Films/<film_id>",methods=["GET","PUT","DELETE"])
|
||||
def retrieve_update_delete_Films(film_id):
|
||||
if request.method == 'GET' : return retrieve_film_controller(film_id)
|
||||
if request.method == 'PUT' : return update_film_controller(film_id)
|
||||
if request.method == "DELETE": return delete_film_controller(film_id)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,40 @@
|
|||
from flask import request, jsonify
|
||||
import uuid
|
||||
from ..app import db
|
||||
from .models import FilmManufacturer
|
||||
|
||||
def list_all_filmmanufacturers_controller():
|
||||
filmmanufacturers = FilmManufacturer.query.all()
|
||||
response = []
|
||||
for filmmanufacturer in filmmanufacturers: response.append(filmmanufacturer.toDict())
|
||||
return jsonify(response)
|
||||
|
||||
def create_filmmanufacturer_controller():
|
||||
request_form = request.form.to_dict()
|
||||
print(request_form)
|
||||
new_filmmanufacturer = FilmManufacturer(
|
||||
name = request_form['name'],
|
||||
)
|
||||
db.session.add(new_filmmanufacturer)
|
||||
db.session.commit()
|
||||
response = FilmManufacturer.query.all()
|
||||
return(jsonify(request_form))
|
||||
|
||||
def retrieve_filmmanufacturer_controller(filmmanufacturer_id):
|
||||
response = FilmManufacturer.query.get(filmmanufacturer_id).toDict()
|
||||
print(response)
|
||||
return jsonify(response)
|
||||
|
||||
def update_filmmanufacturer_controller(filmmanufacturer_id):
|
||||
request_form = request.form.to_dict()
|
||||
filmmanufacturer = FilmManufacturer.query.get(filmmanufacturer_id)
|
||||
filmmanufacturer.name = request_form['name']
|
||||
|
||||
db.session.commit()
|
||||
response = FilmManufacturer.query.get(filmmanufacturer_id).toDict()
|
||||
return jsonify(response)
|
||||
|
||||
def delete_filmmanufacturer_controller(filmmanufacturer_id):
|
||||
FilmManufacturer.query.filter_by(id=filmmanufacturer_id).delete()
|
||||
db.session.commit()
|
||||
return f"FilmManufacturer with ID={FilmManufacturer} was removed successfully"
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
from sqlalchemy import inspect
|
||||
|
||||
from ..app import db
|
||||
|
||||
class FilmManufacturer(db.Model):
|
||||
id = db.Column(db.Integer(),primary_key=True,nullable=False,unique=True, autoincrement=True)
|
||||
name = db.Column(db.String(255))
|
||||
films = db.relationship("Film",back_populates='filmmanufacturer')
|
||||
def toDict(self):
|
||||
return {
|
||||
c.key: getattr(self,c.key) for c in inspect(self).mapper.column_attrs
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
from flask import request
|
||||
|
||||
from ..app import app
|
||||
from .controllers import list_all_filmmanufacturers_controller,create_filmmanufacturer_controller,retrieve_filmmanufacturer_controller,update_filmmanufacturer_controller,delete_filmmanufacturer_controller
|
||||
|
||||
@app.route("/FilmManufacturer",methods=["GET","POST"])
|
||||
def list_all_create_filmmanufacturers():
|
||||
if request.method == 'GET' : return list_all_filmmanufacturers_controller()
|
||||
if request.method == 'POST' : return create_filmmanufacturer_controller()
|
||||
|
||||
@app.route("/FilmManufacturer/<filmmanufacturer_id>",methods=["GET","PUT","DELETE"])
|
||||
def retrieve_update_delete_FilmManufacturers(filmmanufacturer_id):
|
||||
if request.method == 'GET' : return retrieve_filmmanufacturer_controller(filmmanufacturer_id)
|
||||
if request.method == 'PUT' : return update_filmmanufacturer_controller(filmmanufacturer_id)
|
||||
if request.method == "DELETE": return delete_filmmanufacturer_controller(filmmanufacturer_id)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,43 @@
|
|||
import os
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from sqlalchemy import event
|
||||
|
||||
from .config import config
|
||||
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
|
||||
def create_app(config_mode):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_mode])
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app,db,render_as_batch=True)
|
||||
|
||||
with app.app_context():
|
||||
@event.listens_for(db.engine, 'connect')
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON;")
|
||||
cursor.close()
|
||||
|
||||
|
||||
|
||||
return app
|
||||
|
||||
app = create_app(os.getenv("CONFIG_MODE"))
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def hello():
|
||||
return "Hellord"
|
||||
|
||||
from .Film import urls
|
||||
from .FilmManufacturer import urls
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True,port=8008)
|
||||
print(os.getenv("CONFIG_MODE"))
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEVELOPMENT =True
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv("DEVELOPMENT_DATABASE_URL")
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv("TEST_DATABASE_URL")
|
||||
class StagingConfig(Config):
|
||||
DEVELOPMENT = True
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv("STAGING_DATABASE_URL")
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv("PRODUCTION_DATABASE_URL")
|
||||
|
||||
config = {
|
||||
"development": DevelopmentConfig,
|
||||
"testing": TestingConfig,
|
||||
"staging": StagingConfig,
|
||||
"production": ProductionConfig
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
Single-database configuration for Flask.
|
||||
Binary file not shown.
|
|
@ -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
|
||||
|
|
@ -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()
|
||||
|
|
@ -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"}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
"""empty message
|
||||
|
||||
Revision ID: 724351b0562f
|
||||
Revises:
|
||||
Create Date: 2024-04-10 02:15:27.572875
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '724351b0562f'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('film_manufacturer',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('id')
|
||||
)
|
||||
op.create_table('film',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=True),
|
||||
sa.Column('ISO', sa.String(length=10), nullable=True),
|
||||
sa.Column('Push_Pull', sa.String(length=10), nullable=True),
|
||||
sa.Column('fk_FilmManufacturer_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['fk_FilmManufacturer_id'], ['film_manufacturer.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('film')
|
||||
op.drop_table('film_manufacturer')
|
||||
# ### end Alembic commands ###
|
||||
Binary file not shown.
Loading…
Reference in New Issue