def execute_request(self, method, params, url): # type: (str, typing.Optional[dict], str) -> dict headers = { 'Content-Type': 'application/json', 'X-Clarifai-Client': 'python:%s' % CLIENT_VERSION, 'Python-Client': '%s:%s' % (OS_VER, PYTHON_VERSION), 'Authorization': 'Key %s' % self._api_key } logger.debug("=" * 100) succinct_payload = self._mangle_base64_values(params) logger.debug("%s %s\nHEADERS:\n%s\nPAYLOAD:\n%s", method, url, pformat(headers), pformat(succinct_payload)) try: if method == 'GET': res = self._session.get(url, params=params, headers=headers) elif method == "POST": res = self._session.post(url, data=json.dumps(params), headers=headers) elif method == "DELETE": res = self._session.delete(url, data=json.dumps(params), headers=headers) elif method == "PATCH": res = self._session.patch(url, data=json.dumps(params), headers=headers) elif method == "PUT": res = self._session.put(url, data=json.dumps(params), headers=headers) else: raise Exception("Unsupported request type: '%s'" % method) except requests.RequestException as e: raise ApiError(url, params, method, e.response) try: response_json = json.loads(res.content.decode('utf-8')) except ValueError: logger.exception("Could not get valid JSON from server response.") logger.debug("\nRESULT:\n%s", pformat(res.content.decode('utf-8'))) error = ApiError(url, params, method, res) raise error else: logger.debug("\nRESULT:\n%s", pformat(response_json)) if int(res.status_code / 100) != 2: error = ApiError(url, params, method, res) logger.warning("%s", str(error)) raise error return response_json
def test_get_non_existing_input(mock_http_client): # type: (mock.Mock) -> None mock_execute_request = mock_request_with_failed_response( mock_http_client, json_responses=[ApiError("/v2/inputs/@nonexistentID", {}, "GET")]) app = ClarifaiApp() with pytest.raises(ApiError): app.inputs.get("@nonexistentID") assert_request(mock_execute_request, 'GET', '/v2/inputs/@nonexistentID')
def test_get_non_existing_model(mock_http_client): # type: (mock.Mock) -> None response = requests.Response() response.status_code = 401 mock_execute_request = mock_request_with_failed_response( mock_http_client, json_responses=[ ApiError("/v2/models/@nonexistentID", {}, "GET", response) ]) app = ClarifaiApp() with pytest.raises(ApiError): app.models.get("@nonexistentID") assert_request(mock_execute_request, 'GET', '/v2/models/@nonexistentID')
def post(self): # get number of requested questions from form question_num = request.form.get('questionNumber') selected_topic = request.form.get('topic') print(selected_topic) # make an API call based on users choices if selected_topic == 'union of sets' or selected_topic == 'symmetric difference' or selected_topic == 'partition' or selected_topic == 'difference of sets' or selected_topic == 'complement' or selected_topic == 'cartesian product': resp = requests.get('https://mathgen-api.herokuapp.com' + self.topic_json['topics'][selected_topic] + question_num + '/11') else: resp = requests.get('https://mathgen-api.herokuapp.com' + self.topic_json['topics'][selected_topic] + question_num) # check if the API call was successful if resp.status_code != 200: # This means something went wrong. raise ApiError('GET /tasks/ {}'.format(resp.status_code)) # save response from API response = resp.json() # change quiz from json to string quiz_json = str(response) # generates a unique id for quiz quiz_id = uuid.uuid1().hex # add quiz_id and quiz_json to database quiz_query = mds.QuizJson(quiz_id=quiz_id, quiz_json=quiz_json) db.session.add(quiz_query) db.session.commit() db.session.close() # redirect to quiz page return redirect("quiz?quiz_id=" + quiz_id)
def pre_quiz(): """ Pre-quiz( dashboard ) page""" # get current users email user_email = current_user.email # get the text before @ to show user id after welcome text user_id_arr = user_email.split("@") user_id = user_id_arr[0] # get available topics from API topics = requests.get('https://mathgen-api.herokuapp.com/topics') # save topics in a var topic_json = topics.json() # key: topic name, value: topic html path topic_urls = { 'Universal Set': 'course-content/set-theory/universal-set/index.html', 'Sub Sets': 'course-content/set-theory/subsets/index.html', 'Cardinality': 'course-content/set-theory/properties/cardinality/index.html', 'Complement': 'course-content/set-theory/properties/complement/index.html', 'Countable Uncountable': 'course-content/set-theory/properties/countable-uncountable/index.html', 'Set Equality': 'course-content/set-theory/properties/set-equality/index.html', 'Mod': 'course-content/set-theory/partitions/mod/index.html', 'Partitions': 'course-content/set-theory/partitions/partitions/index.html', 'Power Set': 'course-content/set-theory/partitions/power-set/index.html', 'Relations': 'course-content/set-theory/partitions/relations/index.html', 'Cartesian Product': 'course-content/set-theory/operations/cartesian-product/index.html', 'Set Difference': 'course-content/set-theory/operations/set-difference/index.html', 'Set Intersection': 'course-content/set-theory/operations/set-intersection/index.html', 'Set Symmetric Difference': 'course-content/set-theory/operations/set-symmetric-difference/index.html', 'Set Union': 'course-content/set-theory/operations/set-union/index.html', 'Empty Set': 'course-content/set-theory/empty-set/index.html' } # key: topic name, value: quiz/api topic_questionUrl_dict = { 'Set Union': 'union of sets', } content_topics = [] for i in topic_urls: content_topics.append(i) if request.method == 'POST': if request.form['btn'] == 'quiz': # get number of requested questions from form question_num = request.form.get('questionNumber') selected_topic = request.form.get('topic') print(question_num) print(selected_topic) # make an API call based on users choices if selected_topic == 'union of sets' or selected_topic == 'symmetric difference' or selected_topic == 'partition' or selected_topic == 'difference of sets' or selected_topic == 'complement' or selected_topic == 'cartesian product': resp = requests.get('https://mathgen-api.herokuapp.com' + topic_json['topics'][selected_topic] + question_num + '/11') else: resp = requests.get('https://mathgen-api.herokuapp.com' + topic_json['topics'][selected_topic] + question_num) # check if the API call was successful if resp.status_code != 200: # This means something went wrong. raise ApiError('GET /tasks/ {}'.format(resp.status_code)) # save response from API response = resp.json() # change quiz from json to string quiz_json = str(response) # generates a unique id for quiz quiz_id = uuid.uuid1().hex # add quiz_id and quiz_json to database quiz_query = mds.QuizJson(quiz_id=quiz_id, quiz_json=quiz_json) db.session.add(quiz_query) db.session.commit() db.session.close() # redirect to quiz page return redirect(url_for("quiz", quiz_id=quiz_id)) elif request.form['btn'] == 'content': content_topic = request.form.get('contentTopic') # return render_template(topic_urls[content_topic]) if content_topic in topic_questionUrl_dict: body = parseBody(topic_urls[content_topic]) print(body) return render_template( "content.html", topic=body, quizUrl=topic_questionUrl_dict[content_topic]) else: body = parseBody(topic_urls[content_topic]) return render_template("content.html", topic=body, quizUrl="none") else: # get the keys from each topic to show in select menu topics_list = list(topic_json['topics'].keys()) # render pre-quiz.html return render_template("pre_quiz.html", topics=topics_list, user_id=user_id, content_topics=content_topics)
import requests from clarifai.errors import ApiError from ast import literal_eval import uuid from datetime import date resp = requests.get( 'https://mathgen-api.herokuapp.com/probability/multiplication/2') if resp.status_code != 200: # This means something went wrong. raise ApiError('GET /tasks/ {}'.format(resp.status_code)) #print(list(resp.json())) d = resp.json() print(type(d)) num = 1 print(d['quizTitle']) print(d['questions'][0]['question']) print(d['questions'][0]['question']) print(d['questions'][0]['answers'][0]) print(d['questions'][0]['answers'][1]) print(d['questions'][0]['answers'][2]) print(d['questions'][0]['answers'][3]) print(d['questions'][0]['correctAnswer']) print(uuid.uuid1()) print(type(d['questions'][0]['questionID'])) # for i in d['questions']: #
def __call__(self, request, metadata=None): """ This is where the actually calls come through when the stub is called such as stub.PostInputs(). They get passed to this method which actually makes the request. Args: request: the proto object for the request. It must be the proper type for the request or the server will complain. Note: this doesn't type check the incoming request in the client but does make sure it can serialize before sending to the server atleast. metadata: not used currently, just added to match grpc. Returns: response: the proto object that this method returns. """ if metadata is not None: raise Exception("No support currently for metadata field.") # There is no __self__ attribute on the request_serializer unfortunately. expected_object_name = self.request_message_descriptor.name if type(request).__name__ != expected_object_name: raise Exception("The input request must be of type: %s from %s" % (expected_object_name, self.request_message_descriptor.file.name)) params = protobuf_to_dict(request) url, method = _pick_proper_endpoint(self.resources, params) headers = { 'Content-Type': 'application/json', 'X-Clarifai-Client': 'python:%s' % CLIENT_VERSION, 'Python-Client': '%s:%s' % (OS_VER, PYTHON_VERSION), 'Authorization': self.headers['Authorization'] } logger.debug("=" * 100) succinct_payload = _mangle_base64_values(params) logger.debug("%s %s\nHEADERS:\n%s\nPAYLOAD:\n%s", method, url, pformat(headers), pformat(succinct_payload)) if method == 'GET': res = requests.get(url, params=params, headers=headers) elif method == "POST": res = requests.post(url, data=json.dumps(params), headers=headers) elif method == "DELETE": res = requests.delete(url, data=json.dumps(params), headers=headers) elif method == "PATCH": res = requests.patch(url, data=json.dumps(params), headers=headers) elif method == "PUT": res = requests.put(url, data=json.dumps(params), headers=headers) else: raise Exception("Unsupported request type: '%s'" % method) try: response_json = json.loads(res.content.decode('utf-8')) except ValueError: logger.exception("Could not get valid JSON from server response.") logger.debug("\nRESULT:\n%s", pformat(res.content.decode('utf-8'))) return res else: logger.debug("\nRESULT:\n%s", pformat(response_json)) if int(res.status_code / 100) != 2: error = ApiError(url, params, method, res) logger.warn("%s", str(error)) raise error # Get the actual message object to construct message = self.response_deserializer result = dict_to_protobuf(message, response_json) return result