コード例 #1
0
def add_get_participant(**kwargs):
    email = kwargs.get('email')
    if email is None:
        raise ValueError("Email cannot be none")
    email_result = requests.post(
        TRIPLESTORE_URL,
        data={"query": CHECK_PERSON_SPARQL.format(email),
              "format": "json"})
    if email_result.status_code < 400:
        info = email_result.json().get('results').get('bindings')
        if len(info) > 1:
            return rdflib.URIRef(info[0].get('entity').get('value'))
        person_response = requests.post(REPOSITORY_URL)
        if person_response.status_code > 399:
            raise falcon.HTTPBadGateway(
                description="Failed to Add Person Code {}\nError: {}".format(
                    person_response.status_code,
                    person_response.text))
        new_person_uri = rdflib.URIRef(person_response.text)
        new_person = default_graph()
        new_person.parse(str(new_person_uri))
        new_person.add((new_person_uri,
                        RDF.type,
                        SCHEMA.Person))
        new_person.add((new_person_uri,
                        SCHEMA.email,
                        rdflib.Literal(email)))
       
        for prop in ['givenName', 'familyName', 'url']:
            if prop in kwargs:
                new_person.add((new_person_uri,
                               getattr(SCHEMA, prop),
                               rdflib.Literal(kwargs.get(prop))))
        for url in kwargs.get("sameAs", []):
            new_person.add((new_person_uri,
                            rdflib.OWL.sameAs,
                            rdflib.URIRef(url)))
        update_person_response = requests.put(
            str(new_person_uri),
            data=new_person.serialize(format='turtle'),
            headers={"Content-type": "text/turtle"})
        if update_person_response.status_code > 399:
            raise falcon.HTTPBadGateway(
                title="Failed to Update {} Code {}".format(
                    new_person_uri,
                    update_person_response.status_code),
                description="Error {}".format(
                    update_person_response.text))

        return new_person_uri
コード例 #2
0
 def test_http_bad_gateway_entity_with_title_and_desc_and_challenges(self):
     try:
         raise falcon.HTTPBadGateway(title='Test', description='Testdescription')
     except falcon.HTTPBadGateway as e:
         self.assertEqual('Test', e.title, 'Title should be "Test"')
         self.assertEqual('Testdescription', e.description,
                          'Description should be "Testdescription"')
コード例 #3
0
 def test_http_bad_gateway_entity_no_title_and_desc_and_challenges(self):
     try:
         raise falcon.HTTPBadGateway()
     except falcon.HTTPBadGateway as e:
         self.assertEqual(status.HTTP_502, e.title,
                          'The title should be ' + status.HTTP_502 + ', but it is: ' + e.title)
         self.assertEqual(None, e.description, 'The description should be None')
コード例 #4
0
    def on_post(self, req, resp):
        item = json.load(req.stream)

        try:
            event = Event(item)
            self.send_to_datadog(event)
            self.send_to_slack(event)
        except:
            log.exception("Failed to send!")
            raise falcon.HTTPBadGateway("Error sending data",
                                        "Could not reach upstream")

        resp = falcon.HTTP_204
コード例 #5
0
 def on_post(self, req, resp):
     """POST request to index provenance documents in Elasticsearch."""
     try:
         response = execute_indexing()
         result = {'taskID': response.id}
         resp.body = json.dumps(result)
         resp.content_type = 'application/json'
         resp.status = falcon.HTTP_200
     except Exception:
         raise falcon.HTTPBadGateway(
             'Services not found',
             'Could not find Services for either ldFrame, esIndexing or both.'
         )
     app_logger.info('Accepted POST Request for /index/prov.')
コード例 #6
0
 def __html__(self):
     """Generates an Assertion Form for issuing a Badge"""
     assertion_form = NewAssertion()
     all_badges_response = requests.post(TRIPLESTORE_URL,
                                         data={
                                             "query": FIND_ALL_CLASSES,
                                             "format": "json"
                                         })
     if all_badges_response.status_code > 399:
         raise falcon.HTTPBadGateway(
             description="Could not retrieve all Badge classes {}\n{}".
             format(all_badges_response.status_code,
                    all_badges_response.text))
     bindings = all_badges_response.json().get('results').get('bindings')
     assertion_form.badge.choices = [(r.get('altName')['value'],
                                      r.get('name')['value'])
                                     for r in bindings]
     assertion_template = ENV.get_template("assertion.html")
     return assertion_template.render(form=assertion_form)
コード例 #7
0
    def __html__(self, name=None):
        """Generates HTML view for web-browser"""
        if not name:
            badge_class_form = NewBadgeClass()
        badge_class_template = ENV.get_template("badge_class.html")
        all_badges_response = requests.post(TRIPLESTORE_URL,
                                            data={
                                                "query": FIND_ALL_CLASSES,
                                                "format": "json"
                                            })
        if all_badges_response.status_code > 399:
            raise falcon.HTTPBadGateway(
                description="Could not retrieve all Badge classes {}\n{}".
                format(all_badges_response.status_code,
                       all_badges_response.text))
        bindings = all_badges_response.json().get('results').get('bindings')

        return badge_class_template.render(name=name,
                                           badges=bindings,
                                           form=badge_class_form)
コード例 #8
0
ファイル: handlers.py プロジェクト: ocelot-saas/actions
    def on_post(self, req, resp, org_id_raw, restaurant_id_raw):
        """Create a new order."""

        # Parse and process direct input from the request.
        try:
            org_id = self._id_validator.validate(org_id_raw)
            restaurant_id = self._id_validator.validate(restaurant_id_raw)
            order_creation_request_raw = req.stream().read().decode('utf-8')
            order_creation_request = \
                self._order_creation_request_validator.validate(order_creation_request_raw)
        except validation.Error as e:
            raise falcon.HTTPBadRequest(
                title='Invalid order creation data',
                description='Invalid order creation data') from e

        # Retrieve information about the restaurant for which the order is placed.
        try:
            org, restaurant = self._inventory_client.get_org_and_restaurant(org_id, restaurant_id)
        except inventory_sdk.Error as e:
            raise falcon.HTTPBadGateway(
                title='Cannot retrieve data from inventory service',
                description='Could not retrieve data from inventory service') from e

        # Retrieve information about the user which has placed the order, if any.
        # TODO(horia141)

        try:
            order = self._model.create_order(org, restaurant, order_creation_request['items'],
                order_creation_request['delivery_address'], order_creation_request['delivery_notes'])
        except model.Error as e:
            raise falcon.HTTPInternalServerError(
                title='Error while inserting the order',
                description='Error while inserting the order') from e

        response = {'orders': [order]}

        self._orders_response_validator.validate(response)
                
        resp.status = falcon.HTTP_201
        resp.body = json.dumps(response)
コード例 #9
0
def issue_badge(**kwargs):
    """Function issues a badge based on an event and an email, returns the
    assertation URI.

    Keyword Args:
        email(str): Email of participant
        badge(str): Badge Class 
        issuer(dict):  Dictionary with name and url fields. Required
        givenName(str): Given name of participant, defaults to None
        familyName(str): Family name of participant, defaults to None
        issuedOne(datetime): Datetime the Badge was issued, defaults to 
                             UTC timestamp

    Returns:
        assertation_uri(str)
    """
    email = kwargs.get('email')
    badge_class = kwargs.get('badge')
    issuer = kwargs.get('issuer')
    issuedOn = kwargs.get('issuedOn', datetime.datetime.utcnow())
    if email is None or badge_class is None:
        raise ValueError("email and badge class cannot be None")
    event_check_result = requests.post(
        TRIPLESTORE_URL,
        data={"query": FIND_CLASS_SPARQL.format(badge_class),
              "format": "json"})
    
    if event_check_result.status_code > 399:
        raise falcon.HTTPBadGateway(
            
            description="Could not find Badge Class Code {}\nError {}".format(
                event_check_result.status_code,
                event_check_result.text))
    info = event_check_result.json().get('results').get('bindings')
    if len(info) < 1:
        raise ValueError("{} event not found".format(event))
    else:
        event_uri = rdflib.URIRef(info[0].get('class').get('value'))
    new_assertion_response = requests.post(REPOSITORY_URL)
    if new_assertion_response.status_code > 399:
        raise falcon.HTTPBadGateway(
            description="Failed to add new Assertion Code {}\Error {}".format(
                new_assertion_response.status_code,
                new_assertion_response.text))
    badge_uri = rdflib.URIRef(new_assertion_response.text)
    badge_uid = str(badge_uri).split("/")[-1]
    badge_url = "{}/badges/Assertion/{}".format(
        issuer.get('url'),
        badge_uid)
    new_badge_img_response = requests.post(
        str(badge_uri),
        data=bake_badge_dev(badge_url),
        headers={"Content-type": 'image/png'})
    if new_badge_img_response.status_code > 399:
        raise falcon.HTTPBadGateway(
            description="Failed to add image to Assertion {} Code {}\Error {}".format(
                badge_uri,
                new_badge_img_response.status_code,
                new_badge_img_response.text))
    badge_assertion_graph = default_graph()
    badge_assertion_graph.parse(str(badge_uri))
    badge_assertion_graph.add((badge_uri,
                               RDF.type,
                               OBI.Assertion))
    badge_assertion_graph.add((badge_uri,
                               OBI.hasBadge, # Shouldn't this be OBI.badge?
                               event_uri))
    badge_assertion_graph.add((badge_uri,
                               OBI.type,
                               OBI.Assertion))
    badge_assertion_graph.add((badge_uri,
                               OBI.verify,
                               OBI.hosted))
    badge_assertion_graph.add((badge_uri, 
                         RDF.type, 
                         OBI.Badge))
    badge_assertion_graph.add((badge_uri,
        OBI.image,
        rdflib.URIRef(new_badge_img_response.text)))
    # Now add/get Recipient ID 
    recipient_uri = add_get_participant(**kwargs)
    # Save IdentityObject related triples to Assertion Graph
    salt = os.urandom(20)
    badge_assertion_graph.add((badge_uri,
                            OBI.salt,
                            rdflib.Literal(str(salt))))
    identity_hash = hashlib.sha256(email.encode())
    identity_hash.update(salt)
    badge_assertion_graph.add(
        (badge_uri,
         OBI.identity,
         rdflib.Literal("sha256?{}".format(identity_hash.hexdigest()))))
#    badge_assertion_graph.add(
#        (badge_uri,
#         OBI.uid,
#         rdflib.Literal(badge_uid)))
    
    badge_assertion_graph.add(
         (badge_uri, 
          OBI.recipient,
          recipient_uri))  
    badge_assertion_graph.add(
        (badge_uri,
         OBI.verify,
         OBI.hosted))
    badge_assertion_graph.add(
        (badge_uri,
         OBI.issuedOn,
         rdflib.Literal(issuedOn.timestamp())))
    update_badge_response = requests.put(
        str(badge_uri),
        data=badge_assertion_graph.serialize(format='turtle'),
        headers={"Content-type": "text/turtle"})
    if update_badge_response.status_code > 399:
         raise falcon.HTTPBadGateway(
            title="Failed to update Assertion {} Code {}".format(
                badge_uri,
                update_badge_response.status_code),
            description="\Error {}".format(
               update_badge_response.text))
    
       
    print("Issued badge {}".format(badge_url))
    return str(badge_url)
コード例 #10
0
def new_badge_class(**kwargs):
    """Function creates a New Badge Class using a Fedora 4 repository and
    a Blazegraph triplestore.

    Keyword arguments:
       image -- Required
       name -- Required
       description -- Required
       startDate -- Datetime in YYYY-MM-DD format, Required
       endDate -- Datetime in YYYY-MM-DD format, Optional default is None
       criteria -- List of string with each string a description criteria, 
                   good candidate for controlled vocabulary, Optional default  
                   is an empty string
       tags --  List of descriptive key-word tags, Required
       image -- Binary of Open Badge Image to be used in badge baking,
                      Required
       issuer -- Dictionary with name and url fields. Required

    Returns:
       A Python tuple of the Badge URL and the slug for the Badge
    """         
    image_raw = kwargs.get('image')
    badge_name = kwargs.get('name')
    badge_name_slug = slugify(badge_name)
    description = kwargs.get('description')
    started_on = kwargs.get('startDate')
    ended_on = kwargs.get('endDate')
    keywords = kwargs.get('tags')
    criteria = kwargs.get('criteria', None)
    issuer = kwargs.get('issuer')
    badge_image = kwargs.get('image')
    new_badge_result = requests.post(REPOSITORY_URL)
    if new_badge_result.status_code > 399:
        raise falcon.HTTPBadGateway("Error adding new badge {}\n{}".format(
	    new_badge_result.status_code,
	    new_badge_result.text))
    badge_class_uri = rdflib.URIRef(new_badge_result.text)
    image_add_response = requests.post(
        str(badge_class_uri),
        data=badge_image,
        headers={"Content-type": "image/png"})
    if image_add_response.status_code > 399:
        raise falcon.HTTPBadGateway("Error adding new badge image{}\n{}".format(
            image_add_response.status_code,
            image_add_response.text))
    image_uri = rdflib.URIRef(image_add_response.text)
    class_graph = default_graph()
    class_graph.parse(str(badge_class_uri))
    class_graph.add((badge_class_uri, RDF.type, OBI.BadgeClass))
    class_graph.add((badge_class_uri, OBI.type, OBI.BadgeClass))
    class_graph.add((badge_class_uri, RDF.type, SCHEMA.EducationalEvent))
    class_graph.add((badge_class_uri, OBI.image, image_uri))
    # Searches for issuer, creates issuer_uri
    issuer_uri = add_get_issuer(**issuer)
    class_graph.add((badge_class_uri, 
        OBI.issuer,
        issuer_uri))
    class_graph.add((badge_class_uri, 
        OBI.name, 
        rdflib.Literal(badge_name)))
    class_graph.add((badge_class_uri, 
        SCHEMA.alternativeName, 
        rdflib.Literal(badge_name_slug)))  
    class_graph.add((badge_class_uri, 
        OBI.description, 
        rdflib.Literal(description)))
    class_graph.add((badge_class_uri, 
        SCHEMA.startDate, 
        rdflib.Literal(''.join(started_on))))
    if ended_on and len(ended_on) > 0:
        class_graph.add((badge_class_uri, 
            SCHEMA.endDate, 
        rdflib.Literal(''.join(ended_on))))
    for keyword in keywords:
        class_graph.add((badge_class_uri,
            OBI.tags,
	    rdflib.Literal(keyword)))
    for requirement in criteria:
        class_graph.add((badge_class_uri,
            OBI.criteria,
            rdflib.Literal(requirement)))
    update_class_result = requests.put(
        str(badge_class_uri),
        data=class_graph.serialize(format='turtle'),
        headers={"Content-type": "text/turtle"})
    if update_class_result.status_code > 399:
        raise falcon.HTTPBadGateway("Could not update {} with RDF {}\n{} {}".format(
	    str(badge_class_uri),
	    class_graph.serialize(format='turtle').decode(),
	    update_class_result.status_code,
	    update_class_result.text))
    return str(badge_class_uri), badge_name_slug