Initial commit

master
androiddrew 7 years ago
parent dd71324d2e
commit 830340b448

2
.gitignore vendored

@ -58,3 +58,5 @@ docs/_build/
# PyBuilder # PyBuilder
target/ target/
# Pycharm
.idea

@ -1,2 +1,20 @@
# cookiecutter-apistar # 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

@ -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"
}

@ -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,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.

@ -0,0 +1,3 @@
# {{ cookiecutter.project_name }}
{{cookiecutter.description}}

@ -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

@ -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)

@ -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()

@ -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)

@ -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()

@ -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)

@ -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)

@ -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')
Loading…
Cancel
Save