The synchronous Akismet client¶
- class akismet.SyncClient(config: akismet.Config | None = None, http_client: httpx.Client | None = None)[source]¶
Synchronous Akismet API client.
All methods of the Akismet 1.1 and 1.2 web APIs are implemented here:
Use of this client requires an Akismet API key; see <https://akismet.com> for instructions on how to obtain one. Once you have an Akismet API key and corresponding registered site URL to use with it, you can create an API client in either of two ways.
Recommended for most uses: Place your Akismet API key and site URL in the environment variables
PYTHON_AKISMET_API_KEYandPYTHON_AKISMET_BLOG_URL, and then use a client construction method which will automatically read those variables and validate your API key. You can do this with thevalidated_client()constructor method, or by creating your client as a context manager.Using
validated_client():import akismet akismet_client = akismet.SyncClient.validated_client()
This will automatically read the API key and site URL from the environment variables, instantiate a client, and use its
verify_key()method to ensure the key and URL are valid before returning the client instance to you. See the FAQ for the technical reasons why the default constructor does not have this behavior.If you don’t want to or can’t use the environment variables to configure Akismet, you can also explicitly configure by creating a
Configinstance with your API key and site URL, and passing it as the constructor argumentconfig:import akismet config = akismet.Config(key=your_api_key, url=your_site_url) akismet_client = akismet.SyncClient.validated_client(config=config)
If you rely on environment variable configuration and the complete configuration cannot be found in the environment variables,
validated_client()will raiseConfigurationError. If the API key and URL you supply are invalid according toverify_key()– regardless of whether you provided them via environment variables or an explicitConfig–validated_client()will raiseAPIKeyError.If you want to modify the HTTP request behavior – for example, to support a required HTTP proxy – you can construct a custom
httpx.Clientand pass it as the keyword argumenthttp_clientto eithervalidated_client()or the default constructor. Seeakismet.USER_AGENTfor the default user-agent string used by the Akismet API clients, and <https://www.python-httpx.org> for the full documentation of the HTTPX module.Note that if you only want to set a custom request timeout threshold (the default is 1 second), you can specify it by setting the environment variable
PYTHON_AKISMET_TIMEOUTto a value that can be parsed into afloatorintand represents the desired timeout in seconds.You can also use this class as a context manager; when doing so, you do not need to use the
validated_client()constructor, as the context manager can perform the API key validation for you when entering thewithblock.All arguments accepted by
validated_client()are also accepted by the default constructor when used as a context manager.import akismet with akismet.SyncClient() as akismet_client: # Use the client here. It will be automatically cleaned up when the "with" # block exits.
Unusual/advanced use cases: Invoke the default constructor. It accepts the same set of arguments as the
validated_client()constructor, and its behavior is identical except for the fact that it will not automatically validate your configuration, so you must remember to do so manually. You should only invoke the default constructor if you are absolutely certain that you need to avoid the automatic validation performed byvalidated_client().Warning
Consequences of invalid configurationn
If you construct an Akismet API client through the default constructor and provide an invalid key or URL, all operations of the Akismet web service, other than key verification, will reply with an invalid-key message. This will cause all client methods other than
verify_key()to raiseAPIKeyError. To avoid this situation, it is strongly recommended that you callverify_key()to validate your configuration prior to calling any other methods, at which point you likely should be usingvalidated_client()anyway.- Parameters:
config – An optional Akismet
Config, consisting of an API key and site URL.http_client – An optional
httpxHTTP client instance to use. Generally you should only pass this in if you need significantly customized HTTP-client behavior, and if you do pass this argument you are responsible for setting an appropriateUser-Agent(seeUSER_AGENT), timeout, and other configuration values. If all you want is to change the default timeout (1 second), store the desired timeout, in seconds, as a floating-point or integer value in the environment variablePYTHON_AKISMET_TIMEOUT.
- classmethod validated_client(config: akismet.Config | None = None, http_client: httpx.Client | None = None) → Self[source]¶
Constructor of
SyncClient.This is usually preferred over the default
SyncClient()constructor, because this constructor will validate the Akismet configuration (API key and URL) prior to returning the client instance.- Parameters:
config – An optional explicit Akismet
Config, consisting of an API key and site URL; if not passed, the configuration will be read from the environment variablesPYTHON_AKISMET_API_KEYandPYTHON_AKISMET_BLOG_URL.http_client – An optional custom
httpxHTTP client instance to use. Generally you should only pass this in if you need significantly customized HTTP-client behavior, and if you do pass this argument you are responsible for setting an appropriateUser-Agent(seeUSER_AGENT), timeout, and other configuration values. If all you want is to change the default timeout (1 second), store the desired timeout, in seconds, as a floating-point or integer value in the environment variablePYTHON_AKISMET_TIMEOUT.
- Raises:
akismet.APIKeyError – When the discovered Akismet configuration is invalid according to
verify_key().akismet.ConfigurationError – When the Akismet configuration is partially or completely missing, or when the supplied site URL is in the wrong format (does not begin with
http://orhttps://).
- comment_check(user_ip: str, **kwargs: Unpack[akismet.AkismetArguments]) → akismet.CheckResponse[source]¶
Check a piece of user-submitted content to determine whether it is spam.
The IP address of the user posting the content is required. All other comment-check arguments documented by Akismet are also optionally accepted.
It is recommended that you supply at least the following optional arguments:
comment_content;comment_type; andcomment_authorand/orcomment_author_email.The return value is an
intfrom theCheckResponseenum, which can be used as a truthy value (0/Falseif the content is not classified as spam,1/Trueif it is classified as spam). But making use of the full set of enum values allows detecting the presence of the “discard” value in theX-akismet-pro-tipheader to indicate “blatant” spam.- Parameters:
user_ip – The IP address of the user who submitted the content.
comment_content (str) – (optional, recommended) The content the user submitted.
comment_type (str) – (optional, recommended) The type of content, with common values being
"comment","forum-post","contact-form", and"signup". See the Akismet service documentation for a full list of common/recommended types.comment_author (str) – (optional, recommended) The name (such as username) of the content’s submitter.
comment_author_email (str) – (optional, recommended) The email address of the content’s submitter.
is_test (int) – (optional) Set to
1if you are making requests for testing purposes; this tells Akismet not to incorporate the request into its training corpus or allow it to affect future responses.
- Raises:
akismet.ProtocolError – When an unexpected/invalid response type is received from the Akismet API.
- key_sites(month: str | None = None, url_filter: str | None = None, result_format: Literal['csv', 'json'] = 'json', order: str | None = None, limit: int | None = None, offset: int | None = None) → dict | str[source]¶
Return Akismet API usage statistics keyed by site.
All arguments are optional, and the Akismet API will set them to default values if not supplied.
See the Akismet key-sites documentation for examples of the response data from this method.
- Parameters:
month – The month, in
"YYYY-MM"format, to retrieve statistics for. If not supplied, defaults to the current month.url_filter – A full or partial site URL to filter results by. If not supplied, results for all sites under the current API key will be returned.
result_format – The format in which to return results. Supported options are
"json"and"csv". Defaults to"json"if not supplied.order – For CSV-formatted results, the column by which the results should be sorted.
limit – The maximum number of results to return. If not supplied, defaults to 500.
offset – The offset from which to begin result reporting. If not supplied, defaults to 0.
- submit_ham(user_ip: str, **kwargs: Unpack[akismet.AkismetArguments]) → bool[source]¶
Inform Akismet that a piece of user-submitted comment is not spam.
The IP address of the user posting the content is required. All other submit-ham arguments documented by Akismet are also optionally accepted.
It is recommended that you supply at least the following optional arguments:
comment_content;comment_type; andcomment_authorand/orcomment_author_email.Will return
Trueon success (the only expected response).- Parameters:
user_ip – The IP address of the user who submitted the content.
comment_content (str) – (optional, recommended) The content the user submitted.
comment_type (str) – (optional, recommended) The type of content, with common values being
"comment","forum-post","contact-form", and"signup". See the Akismet service documentation for a full list of common/recommended types.comment_author (str) – (optional, recommended) The name (such as username) of the content’s submitter.
comment_author_email (str) – (optional, recommended) The email address of the content’s submitter.
is_test (int) – (optional) Set to
1if you are making requests for testing purposes; this tells Akismet not to incorporate the request into its training corpus or allow it to affect future responses.
- Raises:
akismet.ProtocolError – When an unexpected/invalid response type is received from the Akismet API.
- submit_spam(user_ip: str, **kwargs: Unpack[akismet.AkismetArguments]) → bool[source]¶
Inform Akismet that a piece of user-submitted comment is spam.
The IP address of the user posting the content is required. All other submit-spam arguments documented by Akismet are also optionally accepted.
It is recommended that you supply at least the following optional arguments:
comment_content;comment_type; andcomment_authorand/orcomment_author_email.Will return
Trueon success (the only expected response).- Parameters:
user_ip – The IP address of the user who submitted the content.
comment_content (str) – (optional, recommended) The content the user submitted.
comment_type (str) – (optional, recommended) The type of content, with common values being
"comment","forum-post","contact-form", and"signup". See the Akismet service documentation for a full list of common/recommended types.comment_author (str) – (optional, recommended) The name (such as username) of the content’s submitter.
comment_author_email (str) – (optional, recommended) The email address of the content’s submitter.
is_test (int) – (optional) Set to
1if you are making requests for testing purposes; this tells Akismet not to incorporate the request into its training corpus or allow it to affect future responses.
- Raises:
akismet.ProtocolError – When an unexpected/invalid response type is received from the Akismet API.
- usage_limit() → dict[source]¶
Return Akismet API usage statistics for the current month.
See the Akismet usage-limit documentation for examples of the response data from this method.
- verify_key(key: str | None = None, url: str | None = None) → bool[source]¶
Verify an Akismet API key and URL.
Return
Trueif the key and URL are valid,Falseotherwise.In general, you should not need to explicitly call this method. The
validated_client()constructor will ensure this method is called during client construction, after which the now-verified key/URL can be trusted. If neitherkeynorurlare provided, the key and URL currently in use by this client will be checked.- Parameters:
key – The API key to check.
url – The URL to check.
- Raises:
akismet.ProtocolError – When an unexpected/invalid response type is received from the Akismet API.