[pyramid, predicate] Add a predicate that matches if the pattern is an eid in the DB
authorSimon Chabot <simon.chabot@logilab.fr>
Wed, 12 Feb 2020 13:58:17 +0100
changeset 12890 0cd5b9057202
parent 12889 bbf3e56b43fe
child 12891 eb0cd6060062
[pyramid, predicate] Add a predicate that matches if the pattern is an eid in the DB
cubicweb/pyramid/predicates.py
--- a/cubicweb/pyramid/predicates.py	Wed Mar 13 11:06:46 2019 +0100
+++ b/cubicweb/pyramid/predicates.py	Wed Feb 12 13:58:17 2020 +0100
@@ -21,6 +21,8 @@
 """Contains predicates used in Pyramid views.
 """
 
+from cubicweb._exceptions import UnknownEid
+
 
 class MatchIsETypePredicate(object):
     """A predicate that match if a given etype exist in schema.
@@ -38,5 +40,30 @@
             request.registry['cubicweb.registry'].case_insensitive_etypes
 
 
+class MatchIsEIDPredicate(object):
+    """A predicate that match if a given eid exist in the database.
+    """
+    def __init__(self, matchname, config):
+        self.matchname = matchname
+
+    def text(self):
+        return 'match_is_eid = %s' % self.matchname
+
+    phash = text
+
+    def __call__(self, info, request):
+        try:
+            eid = int(info['match'][self.matchname])
+        except ValueError:
+            return False
+
+        try:
+            request.cw_cnx.entity_from_eid(eid)
+        except UnknownEid:
+            return False
+        return True
+
+
 def includeme(config):
     config.add_route_predicate('match_is_etype', MatchIsETypePredicate)
+    config.add_route_predicate('match_is_eid', MatchIsEIDPredicate)