Skip to content

Commit

Permalink
feat: add a method for calling python APIs
Browse files Browse the repository at this point in the history
- add a method named `perform_v2_request` to call python method instead
of calling HTTPs APIs
- Use `perform_v2_request` method for pin, unpin thread and get user's data
by user_id
  • Loading branch information
Muhammad Faraz Maqsood committed Sep 12, 2024
1 parent a480618 commit d15c928
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from eventtracking import tracker

from . import models, settings, utils
from forum import api as forum_api


log = logging.getLogger(__name__)

Expand Down Expand Up @@ -193,24 +195,24 @@ def unFlagAbuse(self, user, voteable, removeAll):
voteable._update_from_response(response)

def pin(self, user, thread_id):
url = _url_for_pin_thread(thread_id)
params = {'user_id': user.id}
response = utils.perform_request(
response = utils.perform_v2_request(
'put',
url,
params,
forum_api.pin_thread,
params=params,
source_id=thread_id,
metric_tags=self._metric_tags,
metric_action='thread.pin'
)
self._update_from_response(response)

def un_pin(self, user, thread_id):
url = _url_for_un_pin_thread(thread_id)
params = {'user_id': user.id}
response = utils.perform_request(
response = utils.perform_v2_request(
'put',
url,
params,
forum_api.pin_thread,
params=params,
source_id=thread_id,
metric_tags=self._metric_tags,
metric_action='thread.unpin'
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


from . import models, settings, utils

from forum import api as forum_api

class User(models.Model):

Expand Down Expand Up @@ -149,11 +149,12 @@ def _retrieve(self, *args, **kwargs):
if self.attributes.get('group_id'):
retrieve_params['group_id'] = self.group_id
try:
response = utils.perform_request(
'get',
url,
retrieve_params,
metric_action='model.retrieve',
response = utils.perform_v2_request(
"get",
forum_api.retrieve_user,
params=retrieve_params,
source_id=self.attributes["id"],
metric_action="model.retrieve",
metric_tags=self._metric_tags,
)
except utils.CommentClientRequestError as e:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def perform_request(method, url, data_or_params=None, raw=False,
)

# For the better logging
response_to_log_and_compare = (
response.json() if response.content else response.content
)
log.info(
"""
======> FORUM <======
Expand All @@ -87,7 +90,13 @@ def perform_request(method, url, data_or_params=None, raw=False,
response: {response}
======> END <======
""".format(method=method, url=url, params=params, data=data, response=response.json())
""".format(
method=method,
url=url,
params=params,
data=data,
response=response_to_log_and_compare,
)
)

if method == "get":
Expand All @@ -100,12 +109,17 @@ def perform_request(method, url, data_or_params=None, raw=False,
headers=headers,
timeout=config.connection_timeout,
)
forum_v1_response_to_log_and_compare = (
forum_v1_response.json()
if forum_v1_response.content
else forum_v1_response.content
)
log.info(f"requested forum proxey url: {url}")
log.info(f"requested forum v1 url: {forum_v1_url}")
if forum_v1_response.json() != response.json():
if forum_v1_response_to_log_and_compare != response_to_log_and_compare:
log.error(
f"Forum v2 difference, for endpoint {forum_v1_url} with params={params}. \
Expected: {forum_v1_response.json()}. Got: {response.json()}."
Expected: {forum_v1_response_to_log_and_compare}. Got: {response_to_log_and_compare}."
)

metric_tags.append(f'status_code:{response.status_code}')
Expand Down Expand Up @@ -204,3 +218,62 @@ def check_forum_heartbeat():
return 'forum', False, res.get('check', 'Forum heartbeat failed')
except Exception as fail:
return 'forum', False, str(fail)


def perform_v2_request(
request_method,
forum_v2_method,
params=None,
source_id=None,
raw=False,
metric_action=None,
metric_tags=None,
):
# To avoid dependency conflict
from openedx.core.djangoapps.django_comment_common.models import ForumsConfig

config = ForumsConfig.current()

if not config.enabled:
raise CommentClientMaintenanceError("service disabled")

if metric_tags is None:
metric_tags = []

metric_tags.append(f"method:{request_method}")
if metric_action:
metric_tags.append(f"action:{metric_action}")

response = forum_v2_method(params, source_id)
status_code = response["status_code"]

metric_tags.append(f"status_code:{status_code}")

if status_code > 200:
metric_tags.append("result:failure")
else:
metric_tags.append("result:success")

if 200 < status_code < 500: # lint-amnesty, pylint: disable=no-else-raise
log.info(
f"Investigation Log: CommentClientRequestError for request with {request_method} and params {params}"
)
raise CommentClientRequestError(response.text, status_code)
# Heroku returns a 503 when an application is in maintenance mode
elif status_code == 503:
raise CommentClientMaintenanceError(response.text)
elif status_code == 500:
raise CommentClient500Error(response.text)
else:
if raw:
return response.text
else:
try:
data = response["data"]
except ValueError:
raise CommentClientError( # lint-amnesty, pylint: disable=raise-missing-from
"Invalid JSON response for request to forum v2 method named{forum_v2_method}; first 100 characters: '{content}'".format(
forum_v2_method=forum_v2_method, content=response.text[:100]
)
)
return data

0 comments on commit d15c928

Please sign in to comment.