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
Add handler for rendering pages #7
Merged
miltontony
merged 6 commits into
develop
from
feature/issue-7-add-handler-for-rendering-pages
Mar 18, 2014
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f797961
added hanlder for rendering pages
miltontony 80a3cb3
ensure we can handle an invalid querystring
miltontony 3033a74
beef up test
miltontony 2cf22eb
return 400 when querystring missing
miltontony f7c2813
add hits column + tests
miltontony eeff405
remove unused import
miltontony File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
class BaseApiHandler(object): | ||
def __init__(self, config, db_engine): | ||
self.config = config | ||
self.engine = db_engine | ||
|
||
def render(self): | ||
""" | ||
Generates a dict that will be returned as json | ||
|
||
Should return a Dict | ||
""" | ||
raise NotImplementedError('Subclasses should implement this.') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
from twisted.internet.defer import inlineCallbacks, returnValue | ||
from shortener.handlers.base import BaseApiHandler | ||
from shortener.models import ShortenerTables | ||
from twisted.web import http | ||
|
||
|
||
class Dump(BaseApiHandler): | ||
def _format(self, row, audit): | ||
return { | ||
'domain': row['domain'], | ||
'user_token': row['user_token'], | ||
'short_url': row['short_url'], | ||
'long_url': row['long_url'], | ||
'created_at': row['created_at'].isoformat(), | ||
'hits': audit['hits'] | ||
} | ||
|
||
@inlineCallbacks | ||
def render(self, request): | ||
short_url = request.args.get('url') | ||
conn = yield self.engine.connect() | ||
try: | ||
tables = ShortenerTables(self.config['account'], conn) | ||
if not short_url: | ||
request.setResponseCode(http.BAD_REQUEST) | ||
returnValue({'error': 'expected "?url=<short_url>"'}) | ||
else: | ||
row = yield tables.get_row_by_short_url(short_url[0], False) | ||
|
||
if row: | ||
audit = yield tables.get_audit_row(row['id']) | ||
returnValue(self._format(row, audit)) | ||
else: | ||
request.setResponseCode(http.NOT_FOUND) | ||
returnValue({'error': 'short url not found'}) | ||
finally: | ||
yield conn.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
import json | ||
import os | ||
import treq | ||
|
||
from twisted.internet import reactor | ||
from twisted.internet.defer import inlineCallbacks | ||
from twisted.web.client import HTTPConnectionPool | ||
from twisted.trial.unittest import TestCase | ||
from twisted.web.server import Site | ||
|
||
from aludel.database import MetaData | ||
from shortener.api import ShortenerServiceApp | ||
from shortener.models import ShortenerTables | ||
from shortener.metrics import CarbonClientService | ||
from shortener.tests.doubles import ( | ||
DisconnectingStringTransport, StringTransportClientEndpoint) | ||
|
||
|
||
class TestHandlers(TestCase): | ||
timeout = 5 | ||
|
||
def _drop_tables(self): | ||
# NOTE: This is a blocking operation! | ||
md = MetaData(bind=self.service.engine._engine) | ||
md.reflect() | ||
md.drop_all() | ||
assert self.service.engine._engine.table_names() == [] | ||
|
||
@inlineCallbacks | ||
def setUp(self): | ||
reactor.suggestThreadPoolSize(1) | ||
connection_string = os.environ.get( | ||
"SHORTENER_TEST_CONNECTION_STRING", "sqlite://") | ||
|
||
self.account = 'test-account' | ||
cfg = { | ||
'host_domain': 'http://wtxt.io', | ||
'account': self.account, | ||
'connection_string': connection_string, | ||
'graphite_endpoint': 'tcp:www.example.com:80', | ||
'handlers': [ | ||
{'dump': 'shortener.handlers.dump.Dump'}, | ||
], | ||
} | ||
self.pool = HTTPConnectionPool(reactor, persistent=False) | ||
self.service = ShortenerServiceApp( | ||
reactor=reactor, | ||
config=cfg | ||
) | ||
|
||
self.tr = DisconnectingStringTransport() | ||
endpoint = StringTransportClientEndpoint(reactor, self.tr) | ||
self.service.metrics.carbon_client = CarbonClientService(endpoint) | ||
self.service.metrics.carbon_client.startService() | ||
yield self.service.metrics.carbon_client.connect_d | ||
|
||
site = Site(self.service.app.resource()) | ||
self.listener = reactor.listenTCP(0, site, interface='localhost') | ||
self.listener_port = self.listener.getHost().port | ||
self._drop_tables() | ||
self.conn = yield self.service.engine.connect() | ||
self.addCleanup(self.listener.loseConnection) | ||
self.addCleanup(self.pool.closeCachedConnections) | ||
|
||
def make_url(self, path): | ||
return 'http://localhost:%s%s' % (self.listener_port, path) | ||
|
||
@inlineCallbacks | ||
def test_api_dump(self): | ||
yield ShortenerTables(self.account, self.conn).create_tables() | ||
|
||
url = 'http://en.wikipedia.org/wiki/Cthulhu' | ||
yield self.service.shorten_url(url, 'test-user') | ||
yield treq.get( | ||
self.make_url('/qr0'), | ||
allow_redirects=False, | ||
pool=self.pool) | ||
|
||
resp = yield treq.get( | ||
self.make_url('/api/handler/dump?url=qr0'), | ||
allow_redirects=False, | ||
pool=self.pool) | ||
|
||
self.assertEqual(resp.code, 200) | ||
result = yield treq.json_content(resp) | ||
self.assertEqual(result['user_token'], 'test-user') | ||
self.assertEqual(result['short_url'], 'qr0') | ||
self.assertEqual(result['long_url'], url) | ||
self.assertEqual(result['hits'], 1) | ||
self.assertEqual(result['domain'], 'en.wikipedia.org') | ||
|
||
@inlineCallbacks | ||
def test_api_dump_invalid_querystring(self): | ||
yield ShortenerTables(self.account, self.conn).create_tables() | ||
|
||
url = 'http://en.wikipedia.org/wiki/Cthulhu' | ||
yield self.service.shorten_url(url, 'test-user') | ||
yield treq.get( | ||
self.make_url('/qr0'), | ||
allow_redirects=False, | ||
pool=self.pool) | ||
|
||
resp = yield treq.get( | ||
self.make_url('/api/handler/dump'), | ||
allow_redirects=False, | ||
pool=self.pool) | ||
|
||
self.assertEqual(resp.code, 400) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unused import.