Skip to content
38 changes: 25 additions & 13 deletions examples/async.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,19 @@ def id_(self):
hsh = hashlib.sha1()
values = [self.data[attr] for attr in sorted(self.data)]
for v in values:
hsh.update(bytes(str(v), 'utf-8'))
hsh.update(bytes(str(v), "utf-8"))
return hsh.hexdigest()

def type_(self):
return 'post'
return "post"

def attributes(self):
return self.data

def __init__(self, data):
self.data = data
schema = json.loads("""
schema = json.loads(
"""
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "post",
Expand All @@ -53,11 +54,12 @@ def __init__(self, data):
"required": [ "text", "author" ],
"additionalProperties": false
}
""")
"""
)
super().__init__(schema)

def name(self):
return 'post'
return "post"

@gen.coroutine
def create(self, attributes):
Expand Down Expand Up @@ -89,23 +91,33 @@ def delete(self, id_):
return False

@gen.coroutine
def list_(self):
def list_(self, limit=0, page=0):
"""
Note that limit and page are not implemented in this example
"""
return [Posts.ResourceObject(self, p) for p in self.data]

@gen.coroutine
def list_count(self):
return len(self.data)


def main():
define("debug", default=False, help="Run in debug mode")
options.parse_command_line()
settings = {}
settings.update(options.group_dict(None))
settings.update(tornado_jsonapi.handlers.not_found_handling_settings())
application = tornado.web.Application([
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=Posts(json.loads(open('data.json').read())))
),
], **settings)
application = tornado.web.Application(
[
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=Posts(json.loads(open("data.json").read()))),
),
],
**settings
)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()

Expand Down
39 changes: 28 additions & 11 deletions examples/dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
import tornado_jsonapi.resource


schema = json.loads("""
schema = json.loads(
"""
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "post",
Expand All @@ -31,7 +32,8 @@
"required": [ "text", "author" ],
"additionalProperties": false
}
""")
"""
)


def main():
Expand All @@ -41,16 +43,31 @@ def main():
settings.update(options.group_dict(None))
settings.update(tornado_jsonapi.handlers.not_found_handling_settings())

r = tornado_jsonapi.resource.DBAPI2Resource(
schema, sqlite3, sqlite3.connect(':memory:'))
conn = sqlite3.connect(":memory:")

r = tornado_jsonapi.resource.DBAPI2Resource(schema, sqlite3, conn)
r._create_table()
application = tornado.web.Application([
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=r)
),
], **settings)

cur = conn.cursor()
for i in range(1, 16):
cur.execute(
"INSERT INTO posts(text,author) VALUES(?,?)",
(
"Text" + str(i),
str(i)
)
)

application = tornado.web.Application(
[
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=r),
),
],
**settings
)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()

Expand Down
30 changes: 16 additions & 14 deletions examples/postgre.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
import tornado_jsonapi.resource


schema = json.loads("""
schema = json.loads(
"""
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "post",
Expand All @@ -33,7 +34,8 @@
"required": [ "text", "author" ],
"additionalProperties": false
}
""")
"""
)


def main():
Expand All @@ -48,11 +50,8 @@ def main():
# connect to postgre using momoko
# see http://momoko.61924.nl/en/latest/tutorial.html#trival-example
conn = momoko.Pool(
'dbname=postgres '
'user=postgres '
'host=localhost '
'port=5432',
ioloop=io_loop
"dbname=postgres " "user=postgres " "host=localhost " "port=5432",
ioloop=io_loop,
)
future = conn.connect()
io_loop.add_future(future, lambda x: io_loop.stop())
Expand All @@ -62,13 +61,16 @@ def main():
r = tornado_jsonapi.resource.DBAPI2Resource(schema, momoko, connection)
io_loop.add_future(r._create_table(), lambda x: io_loop.stop())
io_loop.start()
application = tornado.web.Application([
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=r)
),
], **settings)
application = tornado.web.Application(
[
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=r),
),
],
**settings
)
application.listen(8888)
io_loop.start()

Expand Down
40 changes: 28 additions & 12 deletions examples/sqla.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,24 @@
import tornado.ioloop
from tornado.options import options, define

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

import tornado_jsonapi.handlers
import tornado_jsonapi.resource


Base = declarative_base()


class Post(Base):
__tablename__ = 'posts'
__tablename__ = "posts"

id = Column(Integer, primary_key=True)
author = Column(String)
text = Column(String)
hideMe = Column(DateTime)
hideMe2 = Column(String, default="secret")


def main():
Expand All @@ -29,19 +30,34 @@ def main():
settings = {}
settings.update(options.group_dict(None))
settings.update(tornado_jsonapi.handlers.not_found_handling_settings())
settings.update({"jsonapi_limit": 12})

engine = create_engine('sqlite:///:memory:', echo=settings['debug'])
engine = create_engine("sqlite:///:memory:", echo=settings["debug"])
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)

application = tornado.web.Application([
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=tornado_jsonapi.resource.SQLAlchemyResource(
Post, Session))
),
], **settings)
s = Session()
for i in range(1, 16):
p = Post()
p.author = "Author %d" % i
p.text = "Text for %d" % i
s.add(p)
s.commit()

postResource = tornado_jsonapi.resource.SQLAlchemyResource(Post, Session)
postResource.blacklist.append(Post.hideMe)
postResource.blacklist.append("hideMe2")

application = tornado.web.Application(
[
(
r"/api/posts/([^/]*)",
tornado_jsonapi.handlers.APIHandler,
dict(resource=postResource),
),
],
**settings
)
application.listen(8888)
tornado.ioloop.IOLoop.current().start()

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def run_tests(self):
'tornado>=4.2',
],
extras_require={
'sqlalchemy': ['SQLAlchemy==1.0.12', 'alchemyjsonschema==0.3.3'],
'sqlalchemy': ['SQLAlchemy==1.0.12', 'alchemyjsonschema>=0.6.1'],
'dbapi2': ['antiorm==1.2.0']
},
tests_require=['pytest==2.9.1', 'pytest-pep8==1.0.6',
Expand Down
4 changes: 2 additions & 2 deletions test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import tornado.testing
from tornado import netutil
from tornado.testing import AsyncHTTPTestCase
from tornado.wsgi import WSGIAdapter
from tornado.wsgi import WSGIContainer
from http.cookiejar import CookieJar

import tornado_jsonapi.handlers
Expand Down Expand Up @@ -94,7 +94,7 @@ def content_type(self):
def setUp(self):
AsyncHTTPTestCase.setUp(self)
self.app = webtest.TestApp(
WSGIAdapter(self.get_app()),
WSGIContainer(self.get_app()),
cookiejar=CookieJar())


Expand Down
10 changes: 5 additions & 5 deletions tornado_jsonapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# vim: set fileencoding=utf8 :

'''
"""

Handlers
--------
Expand All @@ -20,8 +20,8 @@

.. automodule:: tornado_jsonapi.exceptions
:members:
'''
"""

__author__ = 'Andrew Kravchuk'
__email__ = 'awkravchuk@gmail.com'
__version__ = '0.1.3'
__author__ = "Andrew Kravchuk"
__email__ = "awkravchuk@gmail.com"
__version__ = "0.1.3"
18 changes: 9 additions & 9 deletions tornado_jsonapi/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class Meta(jsl.Document):
class Options(object):
definition_id = 'meta'
definition_id = "meta"
additional_properties = True


Expand All @@ -17,15 +17,15 @@ class Link(jsl.Document):
meta = jsl.DocumentField(Meta, as_ref=True)

class Options(object):
definition_id = 'link'
definition_id = "link"


class Links(jsl.Document):
self = jsl.UriField()
related = jsl.DocumentField(Link, as_ref=True)

class Options(object):
definition_id = 'links'
definition_id = "links"
additional_properties = True


Expand All @@ -37,15 +37,15 @@ class PostResource(jsl.Document):
meta = jsl.DocumentField(Meta, as_ref=True)

class Options(object):
definition_id = 'resource'
definition_id = "resource"


class PostData(jsl.Document):
data = jsl.DocumentField(PostResource, as_ref=True)

class Options(object):
title = 'Data'
definition_id = 'data'
title = "Data"
definition_id = "data"


class PatchResource(jsl.Document):
Expand All @@ -56,15 +56,15 @@ class PatchResource(jsl.Document):
meta = jsl.DocumentField(Meta, as_ref=True)

class Options(object):
definition_id = 'resource'
definition_id = "resource"


class PatchData(jsl.Document):
data = jsl.DocumentField(PatchResource, as_ref=True)

class Options(object):
title = 'Data'
definition_id = 'data'
title = "Data"
definition_id = "data"


def _build_schema(cls):
Expand Down
Loading