Skip to content

Commit

Permalink
Put the uploaded zip files into a database
Browse files Browse the repository at this point in the history
This includes the initial migration to create the table and minimal
setup of the tests to have the database around. Ideally the test
database would be in memory, however there seem to be issues within
the databases library around that (encode/databases#75).
  • Loading branch information
PeterJCLaw committed Jun 26, 2020
1 parent f356cfb commit 94ad476
Show file tree
Hide file tree
Showing 12 changed files with 280 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,6 @@ dmypy.json

# Pyre type checker
.pyre/

# Development database
/sqlite.db
85 changes: 85 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = migrations

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat migrations/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = driver://user:pass@localhost/dbname


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79

# 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
15 changes: 14 additions & 1 deletion code_submitter/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import io
import zipfile

import databases
from starlette.routing import Route
from starlette.requests import Request
from starlette.responses import Response
from starlette.templating import Jinja2Templates
from starlette.applications import Starlette
from starlette.datastructures import UploadFile

from . import config
from .tables import Archive

database = databases.Database(config.DATABASE_URL)
templates = Jinja2Templates(directory='templates')


Expand Down Expand Up @@ -37,6 +42,10 @@ async def upload(request: Request) -> Response:
except zipfile.BadZipFile:
return Response("Must upload a ZIP file", status_code=400)

await database.execute(
Archive.insert().values(content=contents),
)

return Response('')


Expand All @@ -45,4 +54,8 @@ async def upload(request: Request) -> Response:
Route('/upload', endpoint=upload, methods=['POST']),
]

app = Starlette(routes=routes)
app = Starlette(
routes=routes,
on_startup=[database.connect],
on_shutdown=[database.disconnect],
)
6 changes: 6 additions & 0 deletions code_submitter/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from starlette.config import Config

config = Config('.env')

DATABASE_URL: str = config('DATABASE_URL', default='sqlite:///sqlite.db')
TESTING: bool = config('TESTING', cast=bool, default=False)
10 changes: 10 additions & 0 deletions code_submitter/tables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import sqlalchemy

metadata = sqlalchemy.MetaData()

Archive = sqlalchemy.Table(
'archive',
metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True), # noqa:A003
sqlalchemy.Column('content', sqlalchemy.LargeBinary, nullable=False),
)
74 changes: 74 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from logging.config import fileConfig

from alembic import context
from sqlalchemy import pool, engine_from_config
from code_submitter.config import DATABASE_URL
from code_submitter.tables import metadata as target_metadata

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

config.set_main_option('sqlalchemy.url', DATABASE_URL)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# 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() -> None:
"""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,
dialect_opts={"paramstyle": "named"},
)

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


def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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,
)

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() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
32 changes: 32 additions & 0 deletions migrations/versions/dc858321fd15_create_archive_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Create archive table
Revision ID: dc858321fd15
Revises:
Create Date: 2020-06-26 18:08:18.808381
"""
import sqlalchemy as sa
from alembic import op

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


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
'archive',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('content', sa.LargeBinary(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('archive')
# ### end Alembic commands ###
2 changes: 2 additions & 0 deletions script/typing/requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
mypy

sqlalchemy-stubs
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,5 @@ strict_equality = True

scripts_are_modules = True
warn_unused_configs = True

plugins = sqlmypy
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,8 @@
'starlette',
'jinja2',
'python-multipart',
'databases[sqlite]',
'sqlalchemy',
'alembic',
],
)
26 changes: 25 additions & 1 deletion tests/tests_app.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
import io
import zipfile
import tempfile
import unittest
from typing import IO

from code_submitter import app
import alembic # type: ignore[import]
from sqlalchemy import create_engine
from alembic.config import Config # type: ignore[import]
from starlette.config import environ
from starlette.testclient import TestClient

DATABASE_FILE: IO[bytes]


def setUpModule() -> None:
global DATABASE_FILE

DATABASE_FILE = tempfile.NamedTemporaryFile(suffix='sqlite.db')
url = 'sqlite:///{}'.format(DATABASE_FILE.name)

environ['TESTING'] = 'True'
environ['DATABASE_URL'] = url

create_engine(url)

alembic.command.upgrade(Config('alembic.ini'), 'head')


class AppTests(unittest.TestCase):
def setUp(self) -> None:
super().setUp()

# App import must happen after TESTING environment setup
from code_submitter import app

test_client = TestClient(app)
self.session = test_client.__enter__()

Expand Down

0 comments on commit 94ad476

Please sign in to comment.