peony package

peony.api module

class peony.api.APIPath(path, suffix, client)[source]

Bases: peony.api.AbstractAPIPath

Class to make requests to a REST API
Parameters:
  • path (str) – Value of _path
  • suffix (str) – suffix to append to the url
  • client (client.BasePeonyClient) – client used to perform the request
class peony.api.AbstractAPIPath(path, suffix, client)[source]

Bases: abc.ABC

The syntactic sugar factory

Every time you get an attribute or an item from an instance of this class this will be appended to its _path until you call a request method (like get or post)

It makes it easy to call any endpoint of the api

The client given as an parameter during the creation of the BaseAPIPath instance can be accessed as the _client attribute of the instance.

Warning

You must create a child class of AbstractAPIPath to perform requests (you have to implement the _request method)

Parameters:
  • path (str) – Value of _path
  • suffix (str) – suffix to append to the url
  • client (client.BasePeonyClient) – client used to perform the request
delete
get
head
option
patch
post
put
url(suffix=None)[source]
Build the url using the _path attribute
Parameters:suffix (str) – String to be appended to the url
Returns:Path to the endpoint
Return type:str

peony.client module

Peony Clients

BasePeonyClient only handles requests while PeonyClient adds some methods that could help when using the Twitter APIs, with a method to upload a media

class peony.client.BasePeonyClient(consumer_key=None, consumer_secret=None, access_token=None, access_token_secret=None, bearer_token=None, auth=None, headers=None, base_url=None, api_version=None, suffix='.json', loads=<function loads>, error_handler=<class 'peony.utils.DefaultErrorHandler'>, session=None, proxy=None, compression=True, user_agent=None, encoding=None, loop=None, **kwargs)[source]

Bases: object

Access the Twitter API easily

You can create tasks by decorating a function from a child class with peony.task

You also attach a EventStream to a subclass using the event_stream() of the subclass

After creating an instance of the child class you will be able to run all the tasks easily by executing get_tasks()

Parameters:
  • base_url (str, optional) – Format of the url for all the requests
  • api_version (str, optional) – Default API version
  • suffix (str, optional) – Default suffix of API endpoints
  • loads (function, optional) – Function used to load JSON data
  • error_handler (function, optional) – Requests decorator
  • session (aiohttp.ClientSession, optional) – Session to use to make requests
  • proxy (str) – Proxy used with every request
  • compression (bool, optional) – Activate data compression on every requests, defaults to True
  • user_agent (str, optional) – Set a custom user agent header
  • encoding (str, optional) – text encoding of the response from the server
  • loop (event loop, optional) – An event loop, if not specified asyncio.get_event_loop() is called
arun()[source]
close()[source]

properly close the client

classmethod event_stream(event_stream)[source]

Decorator to attach an event stream to the class

get_tasks()[source]
Get the tasks attached to the instance
Returns:List of tasks (asyncio.Task)
Return type:list
request(method, url, future, headers=None, session=None, encoding=None, **kwargs)[source]
Make requests to the REST API
Parameters:
  • future (asyncio.Future) – Future used to return the response
  • method (str) – Method to be used by the request
  • url (str) – URL of the resource
  • headers (oauth.PeonyHeaders) – Custom headers (doesn’t overwrite Authorization headers)
  • session (aiohttp.ClientSession, optional) – Client session used to make the request
Returns:

Response to the request

Return type:

data.PeonyResponse

run()[source]

Run the tasks attached to the instance

run_tasks()[source]

Run the tasks attached to the instance

stream_request(method, url, headers=None, _session=None, *args, **kwargs)[source]
Make requests to the Streaming API
Parameters:
  • method (str) – Method to be used by the request
  • url (str) – URL of the resource
  • headers (dict) – Custom headers (doesn’t overwrite Authorization headers)
  • _session (aiohttp.ClientSession, optional) – The session to use for this specific request, the session given as argument of __init__() is used by default
Returns:

Stream context for the request

Return type:

stream.StreamResponse

class peony.client.MetaPeonyClient[source]

Bases: type

class peony.client.PeonyClient(*args, **kwargs)[source]

Bases: peony.client.BasePeonyClient

A client with some useful methods for most usages

upload_media(file_, media_type=None, media_category=None, chunked=True, size_limit=None, **params)[source]
upload a media file on twitter
Parameters:
  • file (str or pathlib.Path or file) – Path to the file or file object
  • media_type (str, optional) – mime type of the media
  • media_category (str, optional) – Twitter’s media category of the media, must be used with media_type
  • chunked (bool, optional) – If True, force the use of the chunked upload for the media
  • params (dict) – parameters used when making the request
Returns:

Response of the request

Return type:

data_processing.PeonyResponse

peony.exceptions module

exception peony.exceptions.AccessNotAllowedByCredentials(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.AccountLocked(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.AccountSuspended(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.ActionNotPermitted(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.AlreadyRetweeted(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.ApplicationNotAllowedToAccessDirectMessages(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.AttachmentURLInvalid(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.AutomatedRequest(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.BadAuthentication(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.Blocked(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CallbackURLNotApproved(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CannotMuteYourself(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CannotReportYourselfAsSpam(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CannotSendMessageToNonFollowers(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CannotSendMessageToUser(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.CouldNotAuthenticate(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPUnauthorized

exception peony.exceptions.DMCharacterLimit(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.DesktopApplicationAuth(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPUnauthorized

exception peony.exceptions.DoesNotExist(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.DuplicatedStatus(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

class peony.exceptions.ErrorDict[source]

Bases: dict

A dict to easily add exception associated to a code

code(code)[source]

Decorator to associate a code to an exception

exception peony.exceptions.FollowBlocked(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.FollowLimit(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.FollowRequestAlreadyChanged(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.GIFNotAllowedWithMultipleImages(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.HTTPBadGateway(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPBadRequest(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPConflict(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPEnhanceYourCalm(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPForbidden(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPGatewayTimeout(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPGone(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPInternalServerError(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPNotAcceptable(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPNotFound(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPNotModified(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPServiceUnavailable(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPTooManyRequests(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPUnauthorized(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.HTTPUnprocessableEntity(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.InternalError(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPInternalServerError

exception peony.exceptions.InvalidCoordinates(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.InvalidOrExpiredToken(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.InvalidOrSuspendedApplication(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPUnauthorized

exception peony.exceptions.InvalidURL(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.MediaIDNotFound(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.MediaIDValidationFailed(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPBadRequest

exception peony.exceptions.MediaProcessingError(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.MigrateToNewAPI(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPGone

exception peony.exceptions.NoLocationAssociatedToIP(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.NoUserMatchesQuery(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.NotAuthenticated(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPUnauthorized

exception peony.exceptions.NotMutingUser(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.OverCapacity(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPServiceUnavailable

exception peony.exceptions.OwnerMustAllowDMFromAnyone(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.ParameterMissing(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.PeonyDecodeError(exception, *args, **kwargs)[source]

Bases: peony.exceptions.PeonyException

get_message()[source]
exception peony.exceptions.PeonyException(response=None, error=None, data=None, url=None, message=None)[source]

Bases: Exception

Parent class of all the exceptions of Peony

get_message()[source]
exception peony.exceptions.PeonyUnavailableMethod(message)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.ProtectedTweet(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.RateLimitExceeded(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPTooManyRequests

Exception raised on rate limit

reset

Time when the limit will be reset

Returns:Time when the limit will be reset
Return type:int
reset_in

Time in seconds until the limit will be reset

Returns:Time in seconds until the limit will be reset
Return type:int
exception peony.exceptions.ReadOnlyApplication(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.ReplyToUnavailableTweet(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.RetiredEndpoint(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPGone

exception peony.exceptions.SSLRequired(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.SpamReportLimit(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.StatusAlreadyFavorited(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.StatusLimit(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.StatusNotFound(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.StreamLimit(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.PeonyException

exception peony.exceptions.SubscriptionAlreadyExists(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPConflict

exception peony.exceptions.TooManyAttachmentTypes(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.TweetIsReplyRestricted(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.TweetNoLongerAvailable(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.TweetTooLong(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.TweetViolatedRules(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.TweetNoLongerAvailable

exception peony.exceptions.UnableToVerifyCredentials(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

exception peony.exceptions.UserNotFound(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.UserSuspended(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPNotFound

exception peony.exceptions.ValueTooLong(response=None, error=None, data=None, url=None, message=None)[source]

Bases: peony.exceptions.HTTPForbidden

peony.exceptions.get_error(data)[source]

return the error if there is a corresponding exception

peony.exceptions.throw(response, loads=None, encoding=None, **kwargs)[source]

Get the response data if possible and raise an exception

peony.general module

peony.iterators module

class peony.iterators.AbstractIterator(request)[source]

Bases: abc.ABC

Asynchronous iterator
Parameters:request (requests.Request) – Main request
class peony.iterators.CursorIterator(request)[source]

Bases: peony.iterators.AbstractIterator

Iterate using a cursor
Parameters:request (requests.Request) – Main request
class peony.iterators.IdIterator(request, parameter, force=False)[source]

Bases: peony.iterators.AbstractIterator

Iterate using ids

It is the parent class of MaxIdIterator and SinceIdIterator

Parameters:
  • request (requests.Request) – Main request
  • parameter (str) – Parameter to change for each request
  • force (bool) – Keep the iterator after empty responses
call_on_response(response)[source]

function that prepares for the next request

get_data(response)[source]

Get the data from the response

class peony.iterators.MaxIdIterator(request, force=False)[source]

Bases: peony.iterators.IdIterator

Iterator for endpoints using max_id
Parameters:request (requests.Request) – Main request
call_on_response(data)[source]

The parameter is set to the id of the tweet at index i - 1

class peony.iterators.SinceIdIterator(request, force=True, fill_gaps=False)[source]

Bases: peony.iterators.IdIterator

Iterator for endpoints using since_id
Parameters:
  • request (requests.Request) – Main request
  • force (bool) – Keep the iterator after empty responses
  • fill_gaps (bool) – Fill the gaps (if there are more than count tweets to get)
call_on_response(data)[source]

Try to fill the gaps and strip last tweet from the response if its id is that of the first tweet of the last response

Parameters:data (list) – The response data
set_param(data)[source]
peony.iterators.with_cursor

alias of peony.iterators.CursorIterator

peony.iterators.with_max_id

alias of peony.iterators.MaxIdIterator

peony.iterators.with_since_id

alias of peony.iterators.SinceIdIterator

peony.oauth module

class peony.oauth.OAuth1Headers(consumer_key, consumer_secret, access_token=None, access_token_secret=None, compression=True, user_agent=None, headers=None)[source]

Bases: peony.oauth.PeonyHeaders

Dynamic headers implementing OAuth1
Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • access_token (str) – Your access token
  • access_token_secret (str) – Your access token secret
  • **kwargs – Other headers
gen_nonce()[source]
gen_signature(method, url, params, skip_params, oauth)[source]
sign(method='GET', url=None, data=None, params=None, skip_params=False, headers=None, **kwargs)[source]

sign, that is, generate the Authorization headers before making a request

class peony.oauth.OAuth2Headers(consumer_key, consumer_secret, client, bearer_token=None, compression=True, user_agent=None, headers=None)[source]

Bases: peony.oauth.PeonyHeaders

Dynamic headers implementing OAuth2
Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • client (client.BasePeonyClient) – The client to authenticate
  • bearer_token (str, optional) – Your bearer_token
  • **kwargs – Other headers
get_basic_authorization()[source]
invalidate_token()[source]
prepare_request(*args, oauth2_pass=False, **kwargs)[source]

prepare all the arguments for the request

Parameters:oauth2_pass (bool) – For oauth2 authentication only (don’t use it)
Returns:Parameters of the request correctly formatted
Return type:dict
refresh_token()[source]
sign(url=None, *args, headers=None, **kwargs)[source]

sign, that is, generate the Authorization headers before making a request

token
class peony.oauth.PeonyHeaders(compression=True, user_agent=None, headers=None)[source]

Bases: abc.ABC, dict

Dynamic headers for Peony

This is the base class of OAuth1Headers and OAuth2Headers.

Parameters:
  • compression (bool, optional) – If set to True the client will be able to receive compressed responses else it should not happen unless you provide the corresponding header when you make a request. Defaults to True.
  • user_agent (str, optional) – The user agent set in the headers. Defaults to “peony v{version number}”
  • headers (dict) – dict containing custom headers
prepare_request(method, url, headers=None, skip_params=False, proxy=None, **kwargs)[source]

prepare all the arguments for the request

Parameters:
  • method (str) – HTTP method used by the request
  • url (str) – The url to request
  • headers (dict, optional) – Additionnal headers
  • proxy (str) – proxy of the request
  • skip_params (bool) – Don’t use the parameters to sign the request
Returns:

Parameters of the request correctly formatted

Return type:

dict

sign(*args, headers=None, **kwargs)[source]

sign, that is, generate the Authorization headers before making a request

class peony.oauth.RawFormData(fields: Iterable[Any] = (), quote_fields: bool = True, charset: Optional[str] = None)[source]

Bases: aiohttp.formdata.FormData

peony.oauth.quote(s)[source]

peony.oauth_dance module

peony.oauth_dance.async_oauth2_dance(consumer_key, consumer_secret)[source]
oauth2 dance
Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
Returns:

Bearer token

Return type:

str

peony.oauth_dance.async_oauth_dance(consumer_key, consumer_secret, callback_uri='oob')[source]
OAuth dance to get the user’s access token
Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • callback_uri (str) – Callback uri, defaults to ‘oob’
Returns:

Access tokens

Return type:

dict

peony.oauth_dance.get_access_token(consumer_key, consumer_secret, oauth_token, oauth_token_secret, oauth_verifier, **kwargs)[source]
get the access token of the user
Parameters:
Returns:

Access tokens

Return type:

dict

peony.oauth_dance.get_oauth_token(consumer_key, consumer_secret, callback_uri='oob')[source]

Get a temporary oauth token

Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • callback_uri (str, optional) – Callback uri, defaults to ‘oob’
Returns:

Temporary tokens

Return type:

dict

peony.oauth_dance.get_oauth_verifier(oauth_token)[source]

Open authorize page in a browser, print the url if it didn’t work

Parameters:oauth_token (str) – The oauth token received in get_oauth_token()
Returns:The PIN entered by the user
Return type:str
peony.oauth_dance.oauth2_dance(consumer_key, consumer_secret, loop=None)[source]
oauth2 dance
Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • loop (event loop, optional) – event loop to use
Returns:

Bearer token

Return type:

str

peony.oauth_dance.oauth_dance(consumer_key, consumer_secret, oauth_callback='oob', loop=None)[source]
OAuth dance to get the user’s access token

It calls async_oauth_dance and create event loop of not given

Parameters:
  • consumer_key (str) – Your consumer key
  • consumer_secret (str) – Your consumer secret
  • oauth_callback (str) – Callback uri, defaults to ‘oob’
  • loop (event loop) – asyncio event loop
Returns:

Access tokens

Return type:

dict

peony.oauth_dance.parse_token(response)[source]

parse the responses containing the tokens

Parameters:response (str) – The response containing the tokens
Returns:The parsed tokens
Return type:dict

peony.requests module

class peony.requests.AbstractRequest[source]

Bases: abc.ABC

A function that makes a request when called

get_url(suffix=None)[source]
static sanitize_params(method, **kwargs)[source]
Request params can be extracted from the **kwargs

Arguments starting with _ will be stripped from it, so they can be used as an argument for the request (eg. “_headers” → “headers” in the kwargs returned by this function while “headers” would be inserted into the parameters of the request)

Parameters:
  • method (str) – method to use to make the request
  • kwargs (dict) – Keywords arguments given to the request
Returns:

New requests parameters, correctly formatted

Return type:

dict

class peony.requests.Endpoint(*request)[source]

Bases: object

A class representing an endpoint
Parameters:
  • api (api.AbstractAPIPath) – API path of the request
  • method (str) – HTTP method to be used by the request
class peony.requests.Iterators(request)[source]

Bases: peony.requests.Endpoint

Access the iterators from peony.iterators right from a request object

class peony.requests.Request(api, method, **kwargs)[source]

Bases: _asyncio.Future, peony.requests.AbstractRequest

Sends requests to a REST API

Await an instance of Request to get the response of the request. The request is scheduled as soon as the Request object is created.

client
class peony.requests.RequestFactory(api, method)[source]

Bases: peony.requests.Endpoint

Requests to REST APIs
Parameters:
  • api (api.AbstractAPIPath) – API path of the request
  • method (str) – HTTP method to be used by the request
class peony.requests.StreamingRequest(api, method)[source]

Bases: peony.requests.AbstractRequest

Requests to Streaming APIs

peony.stream module

class peony.stream.StreamResponse(client, session=None, loads=<function loads>, timeout=10, **kwargs)[source]

Bases: object

Asynchronous iterator for streams
Parameters:
  • *args (list, optional) – Positional arguments of the request
  • client (client.BasePeonyClient) – client used to make the request
  • session (aiohttp.ClientSession, optional) – Session used by the request
  • loads (function, optional) – function used to decode the JSON data received
  • timeout (int, optional) – Timeout on connection
  • kwargs (dict, optional) – Keyword parameters of the request
connect()[source]
Create the connection
Returns:
Return type:self
Raises:exception.PeonyException – On a response status in 4xx that are not status 420 or 429 Also on statuses in 1xx or 3xx since this should not be the status received here
init_restart(error=None)[source]
Restart the stream on error
Parameters:error (bool, optional) – Whether to print the error or not
restart_stream()[source]

Restart the stream on error

state

peony.utils module

class peony.utils.DefaultErrorHandler(request, tries=3)[source]

Bases: peony.utils.ErrorHandler

The default error_handler

The decorated request will retry infinitely on any handled error The exceptions handled are TimeoutError, asyncio.TimeoutError, exceptions.RateLimitExceeded and exceptions.ServiceUnavailable

handle_client_error = <peony.utils.Handle object>[source]
handle_rate_limits = <peony.utils.Handle object>[source]
handle_service_unavailable = <peony.utils.Handle object>[source]
handle_timeout_error = <peony.utils.Handle object>[source]
class peony.utils.Entity(original: str, entity_type: str, data: Mapping[str, Any])[source]

Bases: object

Helper to use Twitter entities

end
start
text

returns text representing the entity

url

returns an url representing the entity

class peony.utils.ErrorHandler(request)[source]

Bases: object

Basic error handler

This error handler just raises all the exceptions that it receives.

CONTINUE = True
OK = True
RAISE = False
RETRY = True
STOP = False
static handle(*exceptions)[source]
class peony.utils.Handle(handler, *exceptions)[source]

Bases: object

exceptions
handler
class peony.utils.MetaErrorHandler[source]

Bases: type

peony.utils.execute(coro)[source]
run a function or coroutine
Parameters:coro (asyncio.coroutine or function) –
peony.utils.get_args(func, skip=0)[source]
Hackish way to get the arguments of a function
Parameters:
  • func (callable) – Function to get the arguments from
  • skip (int, optional) – Arguments to skip, defaults to 0 set it to 1 to skip the self argument of a method.
Returns:

Function’s arguments

Return type:

tuple

peony.utils.get_category(media_type)[source]
peony.utils.get_media_metadata(data, path=None)[source]
Get all the file’s metadata and read any kind of file object
Parameters:
  • data (bytes) – first bytes of the file (the mimetype shoudl be guessed from the file headers
  • path (str, optional) – path to the file
Returns:

  • str – The mimetype of the media
  • str – The category of the media on Twitter

peony.utils.get_size(media)[source]
Get the size of a file
Parameters:media (file object) – The file object of the media
Returns:The size of the file
Return type:int
peony.utils.get_twitter_entities(text: str, entities: Mapping[str, Mapping[str, Any]]) → Iterable[peony.utils.Entity][source]

Returns twitter entities from an entities dictionnary

Entities are returned in reversed order for ease of use (start and end indexes stay the same if the string is changed in place)

peony.utils.get_type(media, path=None)[source]
Parameters:
  • media (file object) – A file object of the image
  • path (str, optional) – The path to the file
Returns:

  • str – The mimetype of the media
  • str – The category of the media on Twitter

peony.utils.log_error(msg=None, exc_info=None, logger=None, **kwargs)[source]
log an exception and its traceback on the logger defined
Parameters:
  • msg (str, optional) – A message to add to the error
  • exc_info (tuple) – Information about the current exception
  • logger (logging.Logger) – logger to use
peony.utils.set_debug()[source]

activates error messages, useful during development