diff --git a/.gitignore b/.gitignore index 7f7cccc..31496a5 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,5 @@ docs/_build/ # PyBuilder target/ +# Pycharm +.idea \ No newline at end of file diff --git a/README.md b/README.md index a67e060..a7b5518 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,20 @@ # cookiecutter-apistar +An API Star template for [cookiecutter](https://github.com/audreyr/cookiecutter) + +## Usage + + ```python + $ pip install cookiecutter + $ cookiecutter https://git.androiddrew.com/androiddrew/cookiecutter-apistar.git + ``` +You will be asked for some basic information regarding your project (name, project name, etc.). This info will be used in your new project + +## License + +MIT Licensed. + +## Changelog + +### 0.0.1 (11/07/2017) +- Initial release \ No newline at end of file diff --git a/cookiecutter.json b/cookiecutter.json new file mode 100644 index 0000000..537b46b --- /dev/null +++ b/cookiecutter.json @@ -0,0 +1,9 @@ +{ + "full_name": "Drew Bednar", + "email": "drew@androiddrew.com", + "github_username": "andoiddrew", + "project_name": "apistar-app", + "project_slug": "{{ cookiecutter.project_name.lower().strip().replace(' ', '_').replace('-','_')}}", + "description": "An apistar project templated by cookiecutter-apistar", + "year": "2017" +} \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/.gitignore b/{{cookiecutter.project_slug}}/.gitignore new file mode 100644 index 0000000..31496a5 --- /dev/null +++ b/{{cookiecutter.project_slug}}/.gitignore @@ -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 \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/LICENSE b/{{cookiecutter.project_slug}}/LICENSE new file mode 100644 index 0000000..e55e41c --- /dev/null +++ b/{{cookiecutter.project_slug}}/LICENSE @@ -0,0 +1,8 @@ +MIT License +Copyright (c) {{cookiecutter.year}} {{cookiecutter.full_name}} + +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. diff --git a/{{cookiecutter.project_slug}}/README.md b/{{cookiecutter.project_slug}}/README.md new file mode 100644 index 0000000..83c8eb5 --- /dev/null +++ b/{{cookiecutter.project_slug}}/README.md @@ -0,0 +1,3 @@ +# {{ cookiecutter.project_name }} + +{{cookiecutter.description}} \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/requirements.txt b/{{cookiecutter.project_slug}}/requirements.txt new file mode 100644 index 0000000..338351d --- /dev/null +++ b/{{cookiecutter.project_slug}}/requirements.txt @@ -0,0 +1,19 @@ +apistar==0.3.9 +certifi==2017.11.5 +chardet==3.0.4 +colorama==0.3.9 +coreapi==2.3.3 +coreschema==0.0.4 +idna==2.6 +itypes==1.1.0 +Jinja2==2.9.6 +MarkupSafe==1.0 +psycopg2==2.7.3.2 +py==1.4.34 +pytest==3.2.3 +requests==2.18.4 +SQLAlchemy==1.1.15 +uritemplate==3.0.0 +urllib3==1.22 +Werkzeug==0.12.2 +whitenoise==3.3.1 diff --git a/{{cookiecutter.project_slug}}/tests/__init__.py b/{{cookiecutter.project_slug}}/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/{{cookiecutter.project_slug}}/tests/conftest.py b/{{cookiecutter.project_slug}}/tests/conftest.py new file mode 100644 index 0000000..fda4358 --- /dev/null +++ b/{{cookiecutter.project_slug}}/tests/conftest.py @@ -0,0 +1,51 @@ +from apistar.frameworks.wsgi import WSGIApp +from apistar.backends.sqlalchemy_backend import SQLAlchemyBackend, get_session + +import pytest + +from {{cookiecutter.project_slug}}.models import Base +from {{cookiecutter.project_slug}}.renders import JSONRenderer +from {{cookiecutter.project_slug}}.app import commands, routes, components + +settings = { + 'DATABASE': { + #'URL': 'postgresql://apistar:local@localhost/test_cookie_api', + 'URL': 'sqlite:///', + 'METADATA': Base.metadata + }, + 'RENDERERS': [JSONRenderer()], +} + +backend = SQLAlchemyBackend(settings) + + +@pytest.fixture(autouse=True) +def create_db(): + Base.metadata.create_all(backend.engine) + + yield + + Base.metadata.drop_all(backend.engine) + + +@pytest.fixture(name='rb_session') +def db_session_fixure(): + "Returns a SQLAlchemy session with automatic rollback" + session = backend.Session() + try: + yield session + session.rollback() + except: + session.rollback() + raise + finally: + session.close() + + +@pytest.fixture(name='app', scope='session') +def apistar_app_fixture(): + """Returns a session scoped WSGIApp instance""" + return WSGIApp(settings=settings, + commands=commands, + components=components, + routes=routes) \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/tests/test_app_routes.py b/{{cookiecutter.project_slug}}/tests/test_app_routes.py new file mode 100644 index 0000000..12419b6 --- /dev/null +++ b/{{cookiecutter.project_slug}}/tests/test_app_routes.py @@ -0,0 +1,5 @@ +from {{cookiecutter.project_slug}}.app import welcome + +def test_welcome_route(): + message = {"message": "welcome to {{cookiecutter.project_slug}}"} + assert message == welcome() \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/tests/test_renders.py b/{{cookiecutter.project_slug}}/tests/test_renders.py new file mode 100644 index 0000000..f0be21b --- /dev/null +++ b/{{cookiecutter.project_slug}}/tests/test_renders.py @@ -0,0 +1,23 @@ +import datetime as dt +from decimal import Decimal +import json + +from {{cookiecutter.project_slug}}.renders import extended_encoder, JSONRenderer + + +def test_extended_encoder_date_parsing(): + test_date = dt.datetime(2017, 5, 10) + assert test_date.isoformat() == extended_encoder(test_date) + + +def test_extended_encoder_decimal_casting(): + test_decimal = Decimal('1.0') + assert 1.0 == extended_encoder(test_decimal) + + +def test_render_with_extended_encoder(): + test_date = dt.datetime(2017, 5, 10) + test_decimal = Decimal('0.1') + expected = dict(my_date="2017-05-10T00:00:00", my_float=0.1) + test_response = dict(my_date=test_date, my_float=test_decimal) + assert json.dumps(expected).encode('utf-8') == JSONRenderer().render(test_response) \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/wsgi_app.py b/{{cookiecutter.project_slug}}/wsgi_app.py new file mode 100644 index 0000000..2bbcc8c --- /dev/null +++ b/{{cookiecutter.project_slug}}/wsgi_app.py @@ -0,0 +1,9 @@ +from {{cookiecutter.project_slug}} import application_factory + +# Override base application settings here +settings = {} + +app = application_factory(settings) + +if __name__ == "__main__": + app.main() \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/__init__.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/__init__.py new file mode 100644 index 0000000..0d30fba --- /dev/null +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/__init__.py @@ -0,0 +1 @@ +from .app import application_factory \ No newline at end of file diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/app.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/app.py new file mode 100644 index 0000000..296624b --- /dev/null +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/app.py @@ -0,0 +1,43 @@ +from apistar import Include, Route +from apistar.frameworks.wsgi import WSGIApp as App +from apistar.backends import sqlalchemy_backend +from apistar.backends.sqlalchemy_backend import Session +from apistar.handlers import docs_urls, static_urls + +from .models import Base +from .renders import JSONRenderer + + +def welcome(): + return {"message": "welcome to {{cookiecutter.project_slug}}"} + + +routes = [ + Route('/', 'GET', welcome), + Include('/docs', docs_urls), + Include('/static', static_urls) +] + +_settings = { + 'DATABASE': { + 'URL': 'postgresql://@localhost/{{cookiecutter.project_name}}', + 'METADATA': Base.metadata + }, + 'RENDERERS': [JSONRenderer()] +} + + +routes = routes + +commands = sqlalchemy_backend.commands + +components = sqlalchemy_backend.components + + +def application_factory(settings={}): + """Returns an instance of Cookie API""" + app_settings = {**_settings, **settings} + return App(settings=app_settings, + commands=commands, + components=components, + routes=routes) diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/models.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/models.py new file mode 100644 index 0000000..d3890b3 --- /dev/null +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/models.py @@ -0,0 +1,34 @@ +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean, Numeric +from sqlalchemy.orm import relationship, backref +from sqlalchemy.sql import expression +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.types import DateTime as DateTimeType + + +class utcnow(expression.FunctionElement): + type = DateTimeType() + + +@compiles(utcnow, 'postgresql') +def pg_utcnow(element, compiler, **kw): + return "TIMEZONE('utc', CURRENT_TIMESTAMP)" + + +Base = declarative_base() + + +class DBMixin: + id = Column(Integer, primary_key=True, autoincrement=True) + created_date = Column(DateTime, server_default=utcnow()) + modified_date = Column(DateTime, server_default=utcnow(), onupdate=utcnow()) + + def to_dict(self): + d = self.__dict__.copy() + if '_sa_instance_state' in d: + d.pop('_sa_instance_state') + return d + + +def ReferenceCol(tablename, nullable=False, **kw): + return Column(ForeignKey('{}.id'.format(tablename)), nullable=nullable, **kw) diff --git a/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/renders.py b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/renders.py new file mode 100644 index 0000000..353cca4 --- /dev/null +++ b/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/renders.py @@ -0,0 +1,23 @@ +import datetime as dt +import decimal +import json + +from apistar import http +from apistar.renderers import Renderer + + +def extended_encoder(obj): + """JSON encoder function with support for ISO 8601 datetime serialization and Decimal to float casting""" + if isinstance(obj, dt.datetime): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return float(obj) + + +class JSONRenderer(Renderer): + """JSON Render with support for ISO 8601 datetime serialization and Decimal to float casting""" + media_type = 'application/json' + charset = None + + def render(self, data: http.ResponseData) -> bytes: + return json.dumps(data, default=extended_encoder).encode('utf-8') \ No newline at end of file