Skip to content

Commit

Permalink
UrlForMixin now offers an absolute_url property (resolves #193) (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
jace committed Nov 22, 2018
1 parent 02a76cd commit bf25849
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
methods
* New: ``coaster.views.endpoint_for``: discover an endpoint given a URL
* Changed: ``UuidMixin`` no longer provides ``url_id``
* New: ``coaster.sqlalchemy.UrlForMixin`` now provides an ``absolute_url``
property


0.6.0
Expand Down
5 changes: 5 additions & 0 deletions coaster/sqlalchemy/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,11 @@ def url_for(self, action='view', **kwargs):
# url_for from flask
return url_for(endpoint, **params)

@with_roles(read={'all'})
@property
def absolute_url(self):
return self.url_for(_external=True)

@classmethod
def is_url_for(cls, _action, _endpoint=None, _external=None, **paramattrs):
"""
Expand Down
3 changes: 2 additions & 1 deletion tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ class DefaultValue(BaseMixin, db.Model):
__tablename__ = 'default_value'
value = db.Column(db.Unicode(100), default='default')


auto_init_default(DefaultValue.value)


Expand Down Expand Up @@ -527,7 +528,7 @@ def test_has_timestamps(self):
self.session.commit()
self.assertTrue(d.updated_at > updated_at)

def test_url_for(self):
def test_url_for_fail(self):
d = UnnamedDocument(content="hello")
self.assertEqual(d.url_for(), None)

Expand Down
18 changes: 18 additions & 0 deletions tests/test_url_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,21 @@ def test_url_for(self):
self.assertEqual(doc2.url_for('edit'), 'http://localhost/1/document2/edit')
self.assertEqual(doc2.url_for('edit', _external=False), '/1/document2/edit')
self.assertEqual(doc2.url_for('edit', _external=True), 'http://localhost/1/document2/edit')

def test_url(self):
"""
The .url property is the same as .url_for(_external=True)
"""
# Make two documents
doc1 = NamedDocument(name=u'document1', title=u"Document 1")
self.session.add(doc1)
c1 = Container() # Gets an autoincrementing id starting from 1
self.session.add(c1)
doc2 = ScopedNamedDocument(container=c1, name=u'document2', title=u"Document 2")
self.session.add(doc2)
self.session.commit()

assert doc1.absolute_url == doc1.url_for(_external=True)
assert doc1.absolute_url != doc1.url_for(_external=False)
assert doc2.absolute_url == doc2.url_for(_external=True)
assert doc2.absolute_url != doc2.url_for(_external=False)

0 comments on commit bf25849

Please sign in to comment.