Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

performance improvements #141

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 17 additions & 18 deletions examples/flask/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,31 @@ def is_authenticated(self):
return True

def make_user_key(self, username):
return 'user_{}'.format(username)
return f'user_{username}'

def list(self):
usernames = self.conn.lrange('users', 0, 100)
users = []

for user in usernames:
users.append(self.conn.hgetall(self.make_user_key(user)))

return users
pipeline = self.conn.pipeline()
for username in usernames:
pipeline.hgetall(self.make_user_key(username))
return pipeline.execute()

def detail(self, username):
return self.conn.hgetall(self.make_user_key(username))

def create(self):
key = self.make_user_key(self.data['username'])
self.conn.hmset(
key,
{
'username': self.data['username'],
'email': self.data['email'],
'added_on': int(time.time()),
}
)
self.conn.rpush('users', self.data['username'])
return self.conn.hgetall(key)
user_data = {
'username': self.data['username'],
'email': self.data['email'],
'added_on': int(time.time()),
}
pipeline = self.conn.pipeline()
pipeline.hmset(key, user_data)
pipeline.rpush('users', self.data['username'])
pipeline.hgetall(key)
_, _, user = pipeline.execute()
return user


UserResource.add_url_rules(app, rule_prefix='/api/users/')
Expand All @@ -50,4 +49,4 @@ def create(self):

if __name__ == '__main__':
app.debug = True
app.run()
app.run()
8 changes: 2 additions & 6 deletions examples/pyramid/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ def make_user_key(self, username):

def list(self):
usernames = self.conn.lrange('users', 0, 100)
users = []

for user in usernames:
users.append(self.conn.hgetall(self.make_user_key(user)))

users = [self.conn.hgetall(self.make_user_key(user)) for user in usernames]
return users

def detail(self, username):
Expand All @@ -46,4 +42,4 @@ def create(self):
config = UserResource.add_views(config, '/users/')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
server.serve_forever()
5 changes: 2 additions & 3 deletions examples/tornado/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class PetResource(TornadoResource):
def prepare(self):
self.fake_db = {
self.fake_db = [
{
"id": 1,
"name": "Mitti",
Expand All @@ -15,7 +15,7 @@ def prepare(self):
"name": "Gary",
"type": "cat"
}
}
]

@gen.coroutine
def list(self):
Expand All @@ -32,4 +32,3 @@ def list(self):
if __name__ == '__main__':
app.listen(8001)
tornado.ioloop.IOLoop.instance().start()

30 changes: 10 additions & 20 deletions tests/test_dj.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,33 +66,26 @@ def fake_init(self):
]

def is_authenticated(self):
if self.request_method() == 'DELETE' and self.endpoint == 'list':
return False

return True
return not (self.request_method() == 'DELETE' and self.endpoint == 'list')

def list(self):
return self.fake_db

def detail(self, pk):
for item in self.fake_db:
if item.id == pk:
return item

# If it wasn't found in our fake DB, raise a Django-esque exception.
raise ObjectDoesNotExist("Model with pk {} not found.".format(pk))
try:
return next(item for item in self.fake_db if item.id == pk)
except StopIteration:
raise ObjectDoesNotExist(f"Model with pk {pk} not found.")

def create(self):
self.fake_db.append(FakeModel(
**self.data
))
self.fake_db.append(FakeModel(**self.data))

def update(self, pk):
for item in self.fake_db:
if item.id == pk:
for k, v in self.data:
for k, v in self.data.items():
setattr(item, k, v)
return
return

def create_detail(self):
raise ValueError({
Expand All @@ -101,10 +94,7 @@ def create_detail(self):
})

def delete(self, pk):
for i, item in enumerate(self.fake_db):
if item.id == pk:
del self.fake_db[i]
return
self.fake_db[:] = [item for item in self.fake_db if item.id != pk]

@skip_prepare
def schema(self):
Expand Down Expand Up @@ -481,4 +471,4 @@ def test_delete(self):
self.res.request = FakeHttpRequest('GET')
self.assertEqual(len(self.res.fake_db), 2)
resp = self.res.handle('detail', pk='de-faced')
self.assertEqual(resp.status_code, 404)
self.assertEqual(resp.status_code, 404)
5 changes: 2 additions & 3 deletions tests/test_tnd.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,10 +244,10 @@ class TndDeleteTestResource(TndBasicTestResource):
testing inherited resource
"""
def delete(self, pk):
self.fake_db = filter(lambda x: x['id'] != pk, self.fake_db)
self.fake_db = [x for x in self.fake_db if x['id'] != pk]

def delete_list(self):
self.fake_db = {}
self.fake_db = []


@unittest.skipIf(not app, 'Tornado is not available')
Expand Down Expand Up @@ -327,4 +327,3 @@ def test_as_detail(self):
'id': 'de-faced',
'title': 'Another'
})

4 changes: 2 additions & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ class FormatTracebackTestCase(unittest.TestCase):
def test_format_traceback(self):
try:
raise ValueError("Because we need an exception.")
except:
except ValueError as e:
exc_info = sys.exc_info()
result = format_traceback(exc_info)
self.assertTrue(result.startswith('Traceback (most recent call last):\n'))
self.assertFalse(result.endswith('\n'))
lines = result.split('\n')
self.assertGreater(len(lines), 3)
self.assertEqual(lines[-1], 'ValueError: Because we need an exception.')
self.assertEqual(lines[-1], 'ValueError: Because we need an exception.')