Compare commits

..

15 Commits

Author SHA1 Message Date
Ben Lopatin 9198a1d549 Version bump 0.9.0 2019-10-06 11:43:56 -04:00
Logan Kilpatrick 53cc24744f Update README.rst (#21)
Update README.rst with link to web accessible documentation.
2019-10-06 12:05:50 +11:00
Ben Lopatin 9dcf5832b6 Merge pull request #18 from Lakshmipathi/master
Fix activate and deactivate call
2019-07-21 18:21:15 -04:00
Lakshmipathi.G 10c27d6338 Fix activate and deactivate call
Signed-off-by: Lakshmipathi.G <Lakshmipathi.G@giis.co.in>
2019-07-14 12:43:37 +05:30
Ben Lopatin 89f12f707b Break out of infinite loop for ok responses 2019-04-21 13:52:14 -04:00
Karl Goetz 0cef55a02f Handle HTTP 429, rate limiting
Per the announcement on Discourse meta, global API rate limits have been
introduced to the Discourse API.
This change adds a new DiscourseRateLimitedError class and a retry mechanism on
receipt of a 429.

https://meta.discourse.org/t/global-rate-limits-in-discourse/78612

Closes: #11

----

Added by Maintainer:

Closes: #13
Formatted with black as well
2019-04-21 13:39:34 -04:00
Ben Lopatin faa8895321 Merge pull request #16 from cck197/master
extra methods for deactivate/activate hack; see https://meta.discours…
2019-04-21 13:32:18 -04:00
Ben Lopatin e434edb2ea Merge pull request #17 from orsonmmz/topics
Added category_topics() and delete_topic() methods
2019-01-02 09:37:03 -05:00
Maciej Suminski 9601d96701 Added category_topics() and delete_topic() methods 2019-01-01 14:12:33 +01:00
Christopher Kelly d5ce2d78dc extra methods for deactivate/activate hack; see https://meta.discourse.org/t/creating-active-users-via-the-api-gem/33133/3 2018-12-07 19:37:55 -08:00
Ben Lopatin 84b59d2e4f Merge pull request #15 from cck197/master
groups endpoint moved; see https://meta.discourse.org/t/group-api-emp…
2018-12-07 16:52:56 -05:00
Christopher Kelly 1970e53059 suspend uses suspend_until ISO date string 2018-12-07 12:11:25 -08:00
Christopher Kelly 0c7b60fef8 groups endpoint moved; see https://meta.discourse.org/t/group-api-empty-response/67892 2018-12-07 11:28:21 -08:00
Ben Lopatin de6e758be6 Remove Python 3.7 from Travis testing
From
https://docs.travis-ci.com/user/languages/python/#development-releases-support:

> Recent Python branches require OpenSSL 1.0.2+. As this library is not
> available for Trusty, 3.7, 3.7-dev, 3.8-dev, and nightly do not work (or
> use outdated archive).
2018-10-29 18:35:43 -04:00
Ben Lopatin 0f2efa8e74 Update Python versions supported 2018-10-29 18:31:33 -04:00
9 changed files with 128 additions and 33 deletions
+1
View File
@@ -4,6 +4,7 @@ python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "pypy"
- "pypy3"
+6
View File
@@ -3,6 +3,12 @@
Release history
===============
0.9.0
-----
- Added rate limiting support
- Added some support for user activation
0.8.0
-----
+5
View File
@@ -6,6 +6,11 @@ pydiscourse
:alt: Build Status
:target: http://travis-ci.org/bennylope/pydiscourse
.. image:: https://img.shields.io/badge/Check%20out%20the-Docs-blue.svg
:alt: Check out the Docs
:target: https://discourse.readthedocs.io/en/latest/
A Python library for working with Discourse.
This is a fork of the original Tindie version. It was forked to include fixes,
+2 -2
View File
@@ -51,9 +51,9 @@ copyright = u'2014, Marc Sibson'
# built documents.
#
# The short X.Y version.
version = '0.8'
version = '0.9'
# The full version, including alpha/beta/rc tags.
release = '0.8.0'
release = '0.9.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+1 -1
View File
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
__version__ = "0.8.0"
__version__ = "0.9.0"
from pydiscourse.client import DiscourseClient
+107 -28
View File
@@ -3,11 +3,17 @@ Core API client module
"""
import logging
import time
import requests
from datetime import timedelta, datetime
from pydiscourse.exceptions import (
DiscourseError, DiscourseServerError, DiscourseClientError
DiscourseError,
DiscourseServerError,
DiscourseClientError,
DiscourseRateLimitedError,
)
from pydiscourse.sso import sso_payload
@@ -58,6 +64,15 @@ class DiscourseClient(object):
"""
return self._get("/users/{0}.json".format(username))["user"]
def approve(self, user_id):
return self._get("/admin/users/{0}/approve.json".format(user_id))
def activate(self, user_id):
return self._put("/admin/users/{0}/activate.json".format(user_id))
def deactivate(self, user_id):
return self._put("/admin/users/{0}/deactivate.json".format(user_id))
def user_all(self, user_id):
"""
Get all user information for a specific user, needs to be admin
@@ -153,8 +168,11 @@ class DiscourseClient(object):
????
"""
suspend_until = (datetime.now() + timedelta(days=duration)).isoformat()
return self._put(
"/admin/users/{0}/suspend".format(userid), duration=duration, reason=reason
"/admin/users/{0}/suspend".format(userid),
suspend_until=suspend_until,
reason=reason,
)
def unsuspend(self, userid):
@@ -416,6 +434,19 @@ class DiscourseClient(object):
"/topics/private-messages-unread/{0}.json".format(username), **kwargs
)
def category_topics(self, category_id, **kwargs):
"""
Returns a list of all topics in a category.
Args:
**kwargs:
Returns:
JSON API response
"""
return self._get("/c/{0}.json".format(category_id), **kwargs)
def hot_topics(self, **kwargs):
"""
@@ -462,6 +493,20 @@ class DiscourseClient(object):
"""
return self._get("/t/{0}/{1}.json".format(slug, topic_id), **kwargs)
def delete_topic(self, topic_id, **kwargs):
"""
Remove a topic
Args:
category_id:
**kwargs:
Returns:
JSON API response
"""
return self._delete(u"/t/{0}".format(topic_id), **kwargs)
def post(self, topic_id, post_id, **kwargs):
"""
@@ -527,7 +572,7 @@ class DiscourseClient(object):
def update_topic(self, topic_url, title, **kwargs):
"""
Update a topic
Update a topic
Args:
topic_url:
@@ -702,7 +747,7 @@ class DiscourseClient(object):
text_color: hex color without number symbol
permissions: dict of 'everyone', 'admins', 'moderators', 'staff' with values of ???
parent: name of the category
parent_category_id:
parent_category_id:
**kwargs:
Returns:
@@ -850,7 +895,7 @@ class DiscourseClient(object):
]
"""
return self._get("/admin/groups.json", **kwargs)
return self._get("/groups/search.json", **kwargs)
def group(self, group_name):
"""
@@ -1266,32 +1311,66 @@ class DiscourseClient(object):
url = self.host + path
headers = {"Accept": "application/json; charset=utf-8"}
response = requests.request(
verb,
url,
allow_redirects=False,
params=params,
files=files,
data=data,
json=json,
headers=headers,
timeout=self.timeout,
)
log.debug("response %s: %s", response.status_code, repr(response.text))
if not response.ok:
try:
msg = u",".join(response.json()["errors"])
except (ValueError, TypeError, KeyError):
if response.reason:
msg = response.reason
else:
msg = u"{0}: {1}".format(response.status_code, response.text)
# How many times should we retry if rate limited
retry_count = 4
# Extra time (on top of that required by API) to wait on a retry.
retry_backoff = 1
if 400 <= response.status_code < 500:
raise DiscourseClientError(msg, response=response)
while retry_count > 0:
response = requests.request(
verb,
url,
allow_redirects=False,
params=params,
files=files,
data=data,
json=json,
headers=headers,
timeout=self.timeout,
)
raise DiscourseServerError(msg, response=response)
log.debug("response %s: %s", response.status_code, repr(response.text))
if response.ok:
break
if not response.ok:
try:
msg = u",".join(response.json()["errors"])
except (ValueError, TypeError, KeyError):
if response.reason:
msg = response.reason
else:
msg = u"{0}: {1}".format(response.status_code, response.text)
if 400 <= response.status_code < 500:
if 429 == response.status_code:
# This codepath relies on wait_seconds from Discourse v2.0.0.beta3 / v1.9.3 or higher.
rj = response.json()
wait_delay = (
retry_backoff + rj["extras"]["wait_seconds"]
) # how long to back off for.
if retry_count > 1:
time.sleep(wait_delay)
retry_count -= 1
log.info(
"We have been rate limited and waited {0} seconds ({1} retries left)".format(
wait_delay, retry_count
)
)
log.debug("API returned {0}".format(rj))
continue
else:
raise DiscourseClientError(msg, response=response)
# Any other response.ok resulting in False
raise DiscourseServerError(msg, response=response)
if retry_count == 0:
raise DiscourseRateLimitedError(
"Number of rate limit retries exceeded. Increase retry_backoff or retry_count",
response=response,
)
if response.status_code == 302:
raise DiscourseError(
+4
View File
@@ -11,3 +11,7 @@ class DiscourseServerError(DiscourseError):
class DiscourseClientError(DiscourseError):
""" An invalid request has been made """
class DiscourseRateLimitedError(DiscourseError):
""" Request required more than the permissible number of retries """
+1 -1
View File
@@ -179,7 +179,7 @@ class TestTopics(ClientBaseTestCase):
)
@mock.patch("requests.request")
@mock.patch("pydiscourse.client.requests.request")
class MiscellaneousTests(ClientBaseTestCase):
def test_search(self, request):
+1 -1
View File
@@ -1,5 +1,5 @@
[tox]
envlist = py27, py34, py35, pypy, pypy3
envlist = py27, py34, py35, py36, py37, pypy, pypy3
[testenv]
setenv =