Initial commit
commit
8a6a156555
@ -0,0 +1,3 @@
|
||||
# Runcible
|
||||
|
||||
A Vuejs application backed by a Molten ReSTful API.
|
@ -0,0 +1,6 @@
|
||||
[run]
|
||||
source = runcible
|
||||
omit = test*
|
||||
|
||||
[report]
|
||||
show_missing = True
|
@ -0,0 +1,62 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*,cover
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Pycharm
|
||||
.idea
|
@ -0,0 +1,10 @@
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019, Drew Bednar
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
@ -0,0 +1,64 @@
|
||||
# runcible
|
||||
|
||||
A backend service for the runcible project
|
||||
|
||||
## First time setup
|
||||
|
||||
Create a virtual environment and activate it. Now from the root project directory run `./scripts/bootstrap`. This will install `pip-tools` and sync any dependencies for the first time.
|
||||
|
||||
To run the app you will need a [postgres] database. Create a development and a test database. Update the connection strings within the `runcible.settings.toml`. Create your first [alembic] migration using the `alembic revision --autogenerate -m "your revision message"` command. Finally, apply your first migration with `alembic upgrade head`.
|
||||
|
||||
|
||||
## Running the developement server
|
||||
A `manage.py` script has been included with a collection of [click] cli functions to assist in development.
|
||||
|
||||
__Note__: the developement server command is not a production webserver. You will need to c
|
||||
|
||||
```
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
## Using the interactive interpreter
|
||||
The `manage.py` script can be used to open an interactive interpreter with a configured molten application from your project.
|
||||
```
|
||||
python manage.py shell
|
||||
```
|
||||
|
||||
## Dependency management
|
||||
|
||||
Dependencies are managed via [pip-tools].
|
||||
|
||||
### Adding a dependency
|
||||
|
||||
To add a dependency, edit `requirements.in` (or `dev_requirements.in`
|
||||
for dev dependencies) and add your dependency then run `pip-compile
|
||||
requirements.in`.
|
||||
|
||||
### Syncing dependencies
|
||||
|
||||
Run `pip-sync requirements.txt dev_requirements.txt`.
|
||||
|
||||
|
||||
## Migrations
|
||||
|
||||
Migrations are managed using [alembic].
|
||||
|
||||
### Generating new migrations
|
||||
|
||||
alembic revision --autogenerate -m 'message'
|
||||
|
||||
### Running the migrations
|
||||
|
||||
alembic upgrade head # to upgrade the local db
|
||||
env ENVIRONMENT=test alembic upgrade head # to upgrade the test db
|
||||
env ENVIRONMENT=prod alembic upgrade head # to upgrade prod
|
||||
|
||||
## Testing
|
||||
|
||||
Run the tests by invoking `py.test` in the project root. Make sure you
|
||||
run any pending migrations beforehand.
|
||||
|
||||
[alembic]: http://alembic.zzzcomputing.com/en/latest/
|
||||
[click]: https://click.palletsprojects.com
|
||||
[pip-tools]: https://github.com/jazzband/pip-tools
|
||||
[postgres]: https://www.postgresql.org/
|
@ -0,0 +1,2 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
@ -0,0 +1,7 @@
|
||||
black
|
||||
bumpversion
|
||||
flake8
|
||||
pip-tools
|
||||
pytest
|
||||
pytest-cov
|
||||
werkzeug
|
@ -0,0 +1,29 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile
|
||||
# To update, run:
|
||||
#
|
||||
# pip-compile dev_requirements.in
|
||||
#
|
||||
--trusted-host pypi.python.org
|
||||
|
||||
appdirs==1.4.3 # via black
|
||||
atomicwrites==1.3.0 # via pytest
|
||||
attrs==18.2.0 # via black, pytest
|
||||
black==18.9b0
|
||||
bumpversion==0.5.3
|
||||
click==7.0 # via black, pip-tools
|
||||
coverage==4.5.2 # via pytest-cov
|
||||
entrypoints==0.3 # via flake8
|
||||
flake8==3.7.6
|
||||
mccabe==0.6.1 # via flake8
|
||||
more-itertools==6.0.0 # via pytest
|
||||
pip-tools==3.4.0
|
||||
pluggy==0.8.1 # via pytest
|
||||
py==1.7.0 # via pytest
|
||||
pycodestyle==2.5.0 # via flake8
|
||||
pyflakes==2.1.0 # via flake8
|
||||
pytest-cov==2.6.1
|
||||
pytest==4.3.0
|
||||
six==1.12.0 # via pip-tools, pytest
|
||||
toml==0.10.0 # via black
|
||||
werkzeug==0.14.1
|
@ -0,0 +1,82 @@
|
||||
import click
|
||||
from molten.contrib.sqlalchemy import EngineData
|
||||
from runcible.index import create_app
|
||||
|
||||
_, app = create_app()
|
||||
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
pass
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option("--host", "-h", default="0.0.0.0", help="A hostname or IP address")
|
||||
@click.option(
|
||||
"--port", "-p", default=8000, help="Port number to bind to development server"
|
||||
)
|
||||
def runserver(host, port):
|
||||
"""
|
||||
Runs a Werkzueg development server. Do no use for production.
|
||||
"""
|
||||
from werkzeug.serving import run_simple
|
||||
|
||||
run_simple(
|
||||
hostname=host, port=port, application=_, use_debugger=True, use_reloader=True
|
||||
)
|
||||
|
||||
|
||||
@cli.command()
|
||||
def shell():
|
||||
"""
|
||||
Enters an interactive shell with an app instance and dependency resolver.
|
||||
"""
|
||||
import rlcompleter
|
||||
import readline
|
||||
from code import InteractiveConsole
|
||||
|
||||
helpers = {"app": app, "resolver": app.injector.get_resolver()}
|
||||
|
||||
readline.parse_and_bind("tab: complete")
|
||||
interpreter = InteractiveConsole(helpers)
|
||||
interpreter.interact(f"Instances in scope: {', '.join(helpers)}.", "")
|
||||
|
||||
|
||||
@cli.command()
|
||||
def initdb():
|
||||
"""
|
||||
Initialize database
|
||||
"""
|
||||
click.echo("This feature has been commented out. Please use alembic to manage your database initialization and changes.")
|
||||
# from runcible.db import Base
|
||||
#
|
||||
# def _init(engine_data: EngineData):
|
||||
# Base.metadata.create_all(bind=engine_data.engine)
|
||||
#
|
||||
# click.echo("Creating database")
|
||||
# app.injector.get_resolver().resolve(_init)()
|
||||
# click.echo("Database created")
|
||||
|
||||
|
||||
@cli.command()
|
||||
def dropdb():
|
||||
"""
|
||||
Drop all tables in database
|
||||
"""
|
||||
|
||||
from runcible.db import Base
|
||||
|
||||
def _drop(engine_data: EngineData):
|
||||
Base.metadata.drop_all(bind=engine_data.engine)
|
||||
|
||||
click.echo("Are you sure you would like to drop the database?: [Y/N]")
|
||||
response = input()
|
||||
if response.lower() == "y":
|
||||
app.injector.get_resolver().resolve(_drop)()
|
||||
click.echo("Database dropped")
|
||||
else:
|
||||
click.echo("Database drop aborted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
@ -0,0 +1,21 @@
|
||||
"""isort:skip_file
|
||||
"""
|
||||
import os
|
||||
import sys; sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) # noqa
|
||||
|
||||
from alembic import context
|
||||
from runcible.index import create_app
|
||||
from runcible.db import Base
|
||||
from molten.contrib.sqlalchemy import EngineData
|
||||
|
||||
_, app = create_app()
|
||||
|
||||
|
||||
def run_migrations_online(engine_data: EngineData):
|
||||
with engine_data.engine.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=Base.metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
app.injector.get_resolver().resolve(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,7 @@
|
||||
click
|
||||
molten
|
||||
sqlalchemy
|
||||
psycopg2-binary
|
||||
alembic
|
||||
wsgicors
|
||||
whitenoise
|
@ -0,0 +1,23 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile
|
||||
# To update, run:
|
||||
#
|
||||
# pip-compile requirements.in
|
||||
#
|
||||
--trusted-host pypi.python.org
|
||||
|
||||
alembic==1.0.7
|
||||
click==7.0
|
||||
mako==1.0.7 # via alembic
|
||||
markupsafe==1.1.0 # via mako
|
||||
molten==0.7.4
|
||||
mypy-extensions==0.4.1 # via typing-inspect
|
||||
psycopg2-binary==2.7.7
|
||||
python-dateutil==2.8.0 # via alembic
|
||||
python-editor==1.0.4 # via alembic
|
||||
six==1.12.0 # via python-dateutil
|
||||
sqlalchemy==1.2.18
|
||||
typing-extensions==3.7.2 # via molten
|
||||
typing-inspect==0.3.1 # via molten
|
||||
whitenoise==4.1.2
|
||||
wsgicors==0.7.0
|
@ -0,0 +1 @@
|
||||
from .views import welcome, ping
|
@ -0,0 +1,8 @@
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def welcome() -> Dict:
|
||||
return {"message": "Welcome to runcible"}
|
||||
|
||||
def ping() -> Dict:
|
||||
return {"message": "pong"}
|
@ -0,0 +1,31 @@
|
||||
import datetime as dt
|
||||
from os import path
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from molten import JSONRenderer, is_schema, dump_schema
|
||||
|
||||
BASE_PATH = path.normpath(path.join(path.abspath(path.dirname(__file__)), "."))
|
||||
|
||||
|
||||
def path_to(*xs):
|
||||
"""
|
||||
Construct a path from the root project directory
|
||||
"""
|
||||
return path.join(BASE_PATH, *xs)
|
||||
|
||||
|
||||
class ExtJSONRenderer(JSONRenderer):
|
||||
"""JSON Render with support for ISO 8601 datetime format strings and Decimal"""
|
||||
|
||||
def default(self, ob: Any) -> Any:
|
||||
"""You may override this when subclassing the JSON renderer in
|
||||
order to encode non-standard object types.
|
||||
"""
|
||||
if is_schema(type(ob)):
|
||||
return dump_schema(ob)
|
||||
if isinstance(ob, dt.datetime):
|
||||
return ob.isoformat()
|
||||
if isinstance(ob, Decimal):
|
||||
return float(ob)
|
||||
|
||||
raise TypeError(f"cannot encode values of type {type(ob)}") # pragma: no cover
|
@ -0,0 +1,32 @@
|
||||
from sqlalchemy import Column, BigInteger, DateTime
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.schema import CreateColumn
|
||||
from sqlalchemy.sql import expression
|
||||
from sqlalchemy.types import DateTime as DatetimeType
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class utcnow(expression.FunctionElement):
|
||||
type = DatetimeType()
|
||||
|
||||
|
||||
@compiles(utcnow, "postgresql")
|
||||
def pg_utcnow(element, compiler, **kw):
|
||||
return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
|
||||
|
||||
|
||||
@compiles(CreateColumn, 'postgresql')
|
||||
def use_identity(element, compiler, **kw):
|
||||
text = compiler.visit_create_column(element, **kw)
|
||||
text = text.replace("SERIAL", "INT GENERATED BY DEFAULT AS IDENTITY")
|
||||
return text
|
||||
|
||||
|
||||
class DBMixin:
|
||||
id = Column(BigInteger, primary_key=True)
|
||||
created_date = Column(DateTime(timezone=True), server_default=utcnow())
|
||||
modified_date = Column(
|
||||
DateTime(timezone=True), server_default=utcnow(), onupdate=utcnow()
|
||||
)
|
@ -0,0 +1,5 @@
|
||||
from molten.errors import MoltenError
|
||||
|
||||
|
||||
class EntityNotFound(MoltenError):
|
||||
"""Raised when an entity is not found using an `exists` check in sqlalchemy."""
|
@ -0,0 +1,81 @@
|
||||
from typing import Tuple
|
||||
from molten import App, Route, ResponseRendererMiddleware, Settings
|
||||
from molten.http import HTTP_404, Request
|
||||
from molten.openapi import Metadata, OpenAPIHandler, OpenAPIUIHandler
|
||||
from molten.settings import SettingsComponent
|
||||
from molten.contrib.sqlalchemy import SQLAlchemyMiddleware, SQLAlchemyEngineComponent, SQLAlchemySessionComponent
|
||||
from wsgicors import CORS
|
||||
from whitenoise import WhiteNoise
|
||||
|
||||
from .api.welcome import welcome, ping
|
||||
from .common import ExtJSONRenderer
|
||||
from .logger import setup_logging
|
||||
from .schema import APIResponse
|
||||
from . import settings
|
||||
|
||||
get_schema = OpenAPIHandler(
|
||||
metadata=Metadata(
|
||||
title="runcible",
|
||||
description="A backend service for the runcible project",
|
||||
version="0.0.0"
|
||||
)
|
||||
)
|
||||
|
||||
get_docs = OpenAPIUIHandler()
|
||||
|
||||
components = [
|
||||
SettingsComponent(settings),
|
||||
SQLAlchemyEngineComponent(),
|
||||
SQLAlchemySessionComponent(),
|
||||
]
|
||||
|
||||
middleware = [ResponseRendererMiddleware(), SQLAlchemyMiddleware()]
|
||||
|
||||
renderers = [ExtJSONRenderer()]
|
||||
|
||||
routes = [
|
||||
Route("/", welcome, "GET"),
|
||||
Route("/ping", ping, "GET"),
|
||||
Route("/_schema", get_schema, "GET"),
|
||||
Route("/_docs", get_docs, "GET"),
|
||||
]
|
||||
|
||||
|
||||
class ExtApp(App):
|
||||
def handle_404(self, request: Request) -> Tuple[str, APIResponse]:
|
||||
"""
|
||||
Returns as standardized JSONResponse on HTTP 404 Error.
|
||||
"""
|
||||
return (
|
||||
HTTP_404,
|
||||
APIResponse(
|
||||
status=404,
|
||||
message=f"The resource you are looking for {request.scheme}://{request.host}{request.path} doesn't exist",
|
||||
),
|
||||
)
|
||||
|
||||
@property
|
||||
def settings(self):
|
||||
def _get_settings(_settings: Settings):
|
||||
return _settings
|
||||
|
||||
settings = self.injector.get_resolver().resolve(_get_settings)()
|
||||
return settings
|
||||
|
||||
|
||||
def create_app(_components=None, _middleware=None, _routes=None, _renderers=None):
|
||||
"""
|
||||
Factory function for the creation of a `molten.App`.
|
||||
"""
|
||||
setup_logging()
|
||||
|
||||
wrapped_app = app = ExtApp(
|
||||
components=_components or components,
|
||||
middleware=_middleware or middleware,
|
||||
routes=_routes or routes,
|
||||
renderers=_renderers or renderers
|
||||
)
|
||||
wrapped_app = CORS(wrapped_app, **settings.strict_get("wsgicors"))
|
||||
wrapped_app = WhiteNoise(wrapped_app, **settings.strict_get("whitenoise"))
|
||||
|
||||
return wrapped_app, app
|
@ -0,0 +1,29 @@
|
||||
import logging.config
|
||||
import sys
|
||||
|
||||
FORMAT = "[%(asctime)s] [PID %(process)d] [%(threadName)s] [%(request_id)s] [%(name)s] [%(levelname)s] %(message)s" # noqa
|
||||
|
||||
|
||||
def setup_logging():
|
||||
logging.config.dictConfig(
|
||||
{
|
||||
"disable_existing_loggers": False,
|
||||
"version": 1,
|
||||
"filters": {
|
||||
"request_id": {"()": "molten.contrib.request_id.RequestIdFilter"}
|
||||
},
|
||||
"formatters": {"console": {"format": FORMAT}},
|
||||
"handlers": {
|
||||
"default": {
|
||||
"level": "DEBUG",
|
||||
"class": "logging.StreamHandler",
|
||||
"stream": sys.stderr,
|
||||
"formatter": "console",
|
||||
"filters": ["request_id"],
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"": {"handlers": ["default"], "level": "DEBUG", "propagate": False}
|
||||
},
|
||||
}
|
||||
)
|
@ -0,0 +1,32 @@
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from molten import BaseApp, HTTPError, HTTP_409, HTTP_404
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
class BaseManager(metaclass=ABCMeta):
|
||||
"""Base instance for Model managers"""
|
||||
|
||||
def __init__(self, session: Session, app: BaseApp):
|
||||
self.session = session
|
||||
self.app = app
|
||||
|
||||
@abstractmethod
|
||||
def model_from_schema(self, schema):
|
||||
"""Converts a Schema instance into a SQLAlchemy ORM model instance"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def schema_from_model(self, result):
|
||||
"""Converts a SQLAlchemy results proxy into a Schema instance"""
|
||||
pass
|
||||
|
||||
def raise_409(self, id:int):
|
||||
"""Raises a 409 HTTP error response in the event of Conflict"""
|
||||
raise HTTPError(
|
||||
HTTP_409,
|
||||
{
|
||||
"status": 409,
|
||||
"message": f"Entity {self.__class__.__name__} with id: {id} already exists"
|
||||
}
|
||||
|
||||
)
|
@ -0,0 +1,14 @@
|
||||
from molten import schema, field
|
||||
|
||||
|
||||
@schema
|
||||
class Link:
|
||||
href: str
|
||||
|
||||
|
||||
@schema
|
||||
class APIResponse:
|
||||
status: int = field(description="An HTTP status code")
|
||||
message: str = field(
|
||||
description="A user presentable message in response to the request provided to the API"
|
||||
)
|
@ -0,0 +1,12 @@
|
||||
import os
|
||||
|
||||
from molten.contrib.toml_settings import TOMLSettings
|
||||
|
||||
from .common import path_to
|
||||
|
||||
ENVIRONMENT = os.getenv("ENVIRONMENT", "dev")
|
||||
SETTINGS = TOMLSettings.from_path(path_to("settings.toml"), ENVIRONMENT)
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
return getattr(SETTINGS, name)
|
@ -0,0 +1,26 @@
|
||||
[common]
|
||||
database_engine_dsn = "postgresql://runcible:@localhost/dev_runcible_db"
|
||||
|
||||
[common.wsgicors]
|
||||
headers="*"
|
||||
methods="*"
|
||||
maxage="180"
|
||||
origin="*"
|
||||
|
||||
[common.whitenoise]
|
||||
root = "static"
|
||||
prefix = "/static"
|
||||
autorefresh = true
|
||||
|
||||
[dev]
|
||||
database_engine_params.echo = true
|
||||
database_engine_params.connect_args.options = "-c timezone=utc"
|
||||
|
||||
[test]
|
||||
database_engine_dsn = "postgresql://runcible:@localhost/test_runcible_db"
|
||||
database_engine_params.echo = true
|
||||
|
||||
[prod.whitenoise]
|
||||
root = "static"
|
||||
prefix = "/static"
|
||||
autorefresh = false
|
@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# setting -e to exit immediately on a command failure.
|
||||
# setting -o pipefail sets the exit code of a pipeline to that of the rightmost command to exit with a non-zero status, or to zero if all commands of the pipeline exit successfully.
|
||||
set -eo pipefail
|
||||
|
||||
if [ -z "$VIRTUAL_ENV" ]; then
|
||||
echo "warning: you are not in a virtualenv"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
pip install -U pip pip-tools
|
||||
pip-compile requirements.in
|
||||
pip-compile dev_requirements.in
|
||||
pip-sync requirements.txt dev_requirements.txt
|
@ -0,0 +1,15 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="runcible",
|
||||
version="0.1.0",
|
||||
author="Drew Bednar",
|
||||
author_email="drew@androiddrew.com",
|
||||
description="A backend service for the runcible project",
|
||||
packages=find_packages(exclude=["tests"]),
|
||||
classifiers=[
|
||||
"Programming Language :: Python :: 3",
|
||||
"License :: OSI Approved :: MIT license",
|
||||
"Operating System :: OS Independent",
|
||||
],
|
||||
)
|
@ -0,0 +1,51 @@
|
||||
import pytest
|
||||
|
||||
from molten import testing
|
||||
from molten.contrib.sqlalchemy import Session
|
||||
|
||||
from runcible.index import create_app
|
||||
|
||||
|
||||
def truncate_all_tables(session: Session):
|
||||
table_names = session.execute("""
|
||||
select table_name from information_schema.tables
|
||||
where table_schema = 'public'
|
||||
and table_type = 'BASE TABLE'
|
||||
and table_name != 'alembic_version'
|
||||
""")
|
||||
for (table_name,) in table_names:
|
||||
# "truncate" can deadlock so we use delete which is guaranteed not to.
|
||||
session.execute(f"delete from {table_name}")
|
||||
session.commit()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def app_global():
|
||||
_, app = create_app()
|
||||
yield app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(app_global):
|
||||
# This is a little "clever"/piggy. We only want a single instance
|
||||
# of the app to ever be created, but we also want to ensure that
|
||||
# the DB is cleared after every test hence "app_global" being a
|
||||
# session-scoped fixture and this one being test-scoped.
|
||||
yield app_global
|
||||
resolver = app_global.injector.get_resolver()
|
||||
resolver.resolve(truncate_all_tables)()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
"""Creates a testing client"""
|
||||
return testing.TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def load_component(app):
|
||||
def load(annotation):
|
||||
def loader(c: annotation):
|
||||
return c
|
||||
return app.injector.get_resolver().resolve(loader)()
|
||||
return load
|
@ -0,0 +1,11 @@
|
||||
def test_welcome_route(client):
|
||||
message = "Welcome to runcible"
|
||||
response = client.get("/")
|
||||
content = response.json()
|
||||
assert message == content.get("message")
|
||||
|
||||
def test_ping_route(client):
|
||||
message = "pong"
|
||||
response = client.get("/ping")
|
||||
content = response.json()
|
||||
assert message == content.get("message")
|
@ -0,0 +1,15 @@
|
||||
import datetime as dt
|
||||
from decimal import Decimal
|
||||
from runcible.common import ExtJSONRenderer
|
||||
|
||||
|
||||
def test_extended_encoder_date_parsing():
|
||||
json_renderer = ExtJSONRenderer()
|
||||
test_date = dt.datetime(2017, 5, 10)
|
||||
assert test_date.isoformat() == json_renderer.default(test_date)
|
||||
|
||||
|
||||
def test_extended_encoder_decimal_casting():
|
||||
json_renderer = ExtJSONRenderer()
|
||||
test_decimal = Decimal('1.0')
|
||||
assert 1.0 == json_renderer.default(test_decimal)
|
@ -0,0 +1,5 @@
|
||||
[*.{js,jsx,ts,tsx,vue}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
@ -0,0 +1,21 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
/dist
|
||||
|
||||
# local env files
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Log files
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
.vscode
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw*
|
@ -0,0 +1,34 @@
|
||||
# frontend
|
||||
|
||||
## Project setup
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compiles and hot-reloads for development
|
||||
```
|
||||
npm run serve
|
||||
```
|
||||
|
||||
### Compiles and minifies for production
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Run your tests
|
||||
```
|
||||
npm run test
|
||||
```
|
||||
|
||||
### Lints and fixes files
|
||||
```
|
||||
npm run lint
|
||||
```
|
||||
|
||||
### Run your unit tests
|
||||
```
|
||||
npm run test:unit
|
||||
```
|
||||
|
||||
### Customize configuration
|
||||
See [Configuration Reference](https://cli.vuejs.org/config/).
|
@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
presets: [
|
||||
'@vue/app'
|
||||
]
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,80 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
"build": "vue-cli-service build",
|
||||
"lint": "vue-cli-service lint",
|
||||
"test:unit": "vue-cli-service test:unit"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.18.0",
|
||||
"vue": "^2.6.6",
|
||||
"vue-router": "^3.0.1",
|
||||
"vuex": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vue/cli-plugin-babel": "^3.4.0",
|
||||
"@vue/cli-plugin-eslint": "^3.4.0",
|
||||
"@vue/cli-plugin-unit-jest": "^3.4.0",
|
||||
"@vue/cli-service": "^3.4.0",
|
||||
"@vue/eslint-config-standard": "^4.0.0",
|
||||
"@vue/test-utils": "^1.0.0-beta.20",
|
||||
"babel-core": "7.0.0-bridge.0",
|
||||
"babel-eslint": "^10.0.1",
|
||||
"babel-jest": "^23.6.0",
|
||||
"eslint": "^5.8.0",
|
||||
"eslint-plugin-vue": "^5.0.0",
|
||||
"node-sass": "^4.9.0",
|
||||
"sass-loader": "^7.1.0",
|
||||
"vue-template-compiler": "^2.5.21"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"root": true,
|
||||
"env": {
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"plugin:vue/essential",
|
||||
"@vue/standard"
|
||||
],
|
||||
"rules": {},
|
||||
"parserOptions": {
|
||||
"parser": "babel-eslint"
|
||||
}
|
||||
},
|
||||
"postcss": {
|
||||
"plugins": {
|
||||
"autoprefixer": {}
|
||||
}
|
||||
},
|
||||
"browserslist": [
|
||||
"> 1%",
|
||||
"last 2 versions",
|
||||
"not ie <= 8"
|
||||
],
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"jsx",
|
||||
"json",
|
||||
"vue"
|
||||
],
|
||||
"transform": {
|
||||
"^.+\\.vue$": "vue-jest",
|
||||
".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
|
||||
"^.+\\.jsx?$": "babel-jest"
|
||||
},
|
||||
"moduleNameMapper": {
|
||||
"^@/(.*)$": "<rootDir>/src/$1"
|
||||
},
|
||||
"snapshotSerializers": [
|
||||
"jest-serializer-vue"
|
||||
],
|
||||
"testMatch": [
|
||||
"**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
|
||||
],
|
||||
"testURL": "http://localhost/"
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 1.1 KiB |
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
||||
</noscript>
|
||||
<div id="app"></div>
|
||||
<!-- built files will be auto injected -->
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,30 @@
|
||||
<template>
|
||||
<div id="app">
|
||||
<div id="nav">
|
||||
<router-link to="/">Home</router-link> |
|
||||
<router-link to="/about">About</router-link> |
|
||||
<router-link to="/ping">Ping</router-link>
|
||||
</div>
|
||||
<router-view/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss">
|
||||
#app {
|
||||
font-family: 'Avenir', Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
text-align: center;
|
||||
color: #2c3e50;
|
||||
}
|
||||
#nav {
|
||||
padding: 30px;
|
||||
a {
|
||||
font-weight: bold;
|
||||
color: #2c3e50;
|
||||
&.router-link-exact-active {
|
||||
color: #42b983;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
@ -0,0 +1,17 @@
|
||||
import axios from 'axios'
|
||||
|
||||
axios.defaults.baseURL = 'http://localhost:8000'
|
||||
|
||||
const appService = {
|
||||
getPing () {
|
||||
return new Promise((resolve, reject) => {
|
||||
axios.get('/ping')
|
||||
.then(response => {
|
||||
resolve(response.data)
|
||||
})
|
||||
.catch(error => { reject(error.status) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default appService
|
@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<div class="hello">
|
||||
<h1>{{ msg }}</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'HelloWorld',
|
||||
props: {
|
||||
msg: String
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Add "scoped" attribute to limit CSS to this component only -->
|
||||
<style scoped lang="scss">
|
||||
h3 {
|
||||
margin: 40px 0 0;
|
||||
}
|
||||
ul {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
li {
|
||||
display: inline-block;
|
||||
margin: 0 10px;
|
||||
}
|
||||
a {
|
||||
color: #42b983;
|
||||
}
|
||||
</style>
|
@ -0,0 +1,12 @@
|
||||
import Vue from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import store from './store'
|
||||
|
||||
Vue.config.productionTip = false
|
||||
|
||||
new Vue({
|
||||
router,
|
||||
store,
|
||||
render: h => h(App)
|
||||
}).$mount('#app')
|
@ -0,0 +1,30 @@
|
||||
import Vue from 'vue'
|
||||
import Router from 'vue-router'
|
||||
import Home from './views/Home.vue'
|
||||
import Ping from './views/Ping.vue'
|
||||
|
||||
Vue.use(Router)
|
||||
|
||||
export default new Router({
|
||||
mode: 'history',
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'home',
|
||||
component: Home
|
||||
},
|
||||
{
|
||||
path: '/ping',
|
||||
name: 'ping',
|
||||
component: Ping
|
||||
},
|
||||
{
|
||||
path: '/about',
|
||||
name: 'about',
|
||||
// route level code-splitting
|
||||
// this generates a separate chunk (about.[hash].js) for this route
|
||||
// which is lazy-loaded when the route is visited.
|
||||
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
|
||||
}
|
||||
]
|
||||
})
|
@ -0,0 +1,16 @@
|
||||
import Vue from 'vue'
|
||||
import Vuex from 'vuex'
|
||||
|
||||
Vue.use(Vuex)
|
||||
|
||||
export default new Vuex.Store({
|
||||
state: {
|
||||
|
||||
},
|
||||
mutations: {
|
||||
|
||||
},
|
||||
actions: {
|
||||
|
||||
}
|
||||
})
|
@ -0,0 +1,5 @@
|
||||
<template>
|
||||
<div class="about">
|
||||
<h1>This is an about page</h1>
|
||||
</div>
|
||||
</template>
|
@ -0,0 +1,17 @@
|
||||
<template>
|
||||
<div class="home">
|
||||
<HelloWorld msg="Welcome to Runcible"/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
// @ is an alias to /src
|
||||
import HelloWorld from '@/components/HelloWorld.vue'
|
||||
|
||||
export default {
|
||||
name: 'home',
|
||||
components: {
|
||||
HelloWorld
|
||||
}
|
||||
}
|
||||
</script>
|
@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<div class="ping">
|
||||
<h1 v-if="msg">{{ msg }}</h1>
|
||||
<h1 class="error" v-else>{{ error_msg }}</h1>
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
import appService from '../app.service'
|
||||
|
||||
export default {
|
||||
name: 'Ping',
|
||||
data () {
|
||||
return {
|
||||
msg: '',
|
||||
error_msg: ''
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
getMessage () {
|
||||
appService.getPing()
|
||||
.then(data => { this.msg = data.message })
|
||||
.catch(error => {
|
||||
if (error) {
|
||||
this.error_msg = error.message
|
||||
}
|
||||
else { this.error_msg = 'HTTP Connection error' }
|
||||
})
|
||||
}
|
||||
},
|
||||
created () {
|
||||
this.getMessage()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<style scoped lang="scss">
|
||||
.error {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
env: {
|
||||
jest: true
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
import { shallowMount } from '@vue/test-utils'
|
||||
import HelloWorld from '@/components/HelloWorld.vue'
|
||||
|
||||
describe('HelloWorld.vue', () => {
|
||||
it('renders props.msg when passed', () => {
|
||||
const msg = 'new message'
|
||||
const wrapper = shallowMount(HelloWorld, {
|
||||
propsData: { msg }
|
||||
})
|
||||
expect(wrapper.text()).toMatch(msg)
|
||||
})
|
||||
})
|
Loading…
Reference in New Issue