Git Product home page Git Product logo

patreon-python's Introduction

patreon-python

Version License Python Version Build Status

Interact with the Patreon API via OAuth.

Get the egg from PyPI, typically via pip:

pip install patreon

or

echo "patreon" >> requirements.txt
pip install -r requirements.txt

Make sure that, however you install patreon, you install its dependencies as well

Step 1. Get your client_id and client_secret

Visit the OAuth Documentation Page while logged in as a Patreon creator to register your client.

This will provide you with a client_id and a client_secret.

Step 2. Use this library

e.g., in a Flask route

import patreon
from flask import request
...

client_id = None      # Replace with your data
client_secret = None  # Replace with your data
creator_id = None     # Replace with your data

@app.route('/oauth/redirect')
def oauth_redirect():
    oauth_client = patreon.OAuth(client_id, client_secret)
    tokens = oauth_client.get_tokens(request.args.get('code'), '/oauth/redirect')
    access_token = tokens['access_token']

    api_client = patreon.API(access_token)
    user_response = api_client.get_identity()
    user = user_response.data()
    memberships = user.relationship('memberships')
    membership = memberships[0] if memberships and len(memberships) > 0 else None

    # pass user and membership to your view to render as needed

You'll notice that the user_response does not return raw JSON data. Instead, it returns a JSON:API resource object, to simplify traversing the normalized graph data that the Patreon API returns. Some available methods are:

  • response.data() to get the main resource
  • response.data().attribute('full_name') to get the full_name attribute from the response data
  • response.data().relationship('campaign').attribute('pledge_sum') to get the pledge_sum attribute from the campaign resource related to the main response data
  • response.find_resource_by_type_and_id('user', '123') to find an arbitrary resource

Step 3. (Optional) Customize your usage

patreon.API instances have methods for interacting with the API based on the routes described in the docs. All methods include includes and fields parameters.

ie:

  • get_identity(includes=None, fields=None)

List methods take page_size and cursor methods as well, ie:

  • get_campaigns(page_size, cursor=None, includes=None, fields=None)

The includes and fields arguments to these methods specify the related resources and the resource attributes you want returned by our API, as per the JSON:API specification. The lists of valid includes and fields arguments are provided on patreon.schemas. For instance, if you wanted to request the total amount a patron has ever paid to your campaign, which is not included by default, you could do:

api_client = patreon.API(patron_access_token)
patron_response = api_client.get_identity(None, {
    'membership': patreon.schemas.member.Attributes.currently_entitled_amount_cents
})

patreon.API also has a utility method extract_cursor which you can use to extract pagination links from our json:api response documents:

api_client = patreon.API(creator_access_token)
campaign_id = api_client.get_campaigns().data()[0].id()
memberships = []
cursor = None
while True:
    members_response = api_client.get_campaigns_by_id_members(campaign_id, 10, cursor=cursor)
    members += members_response.data()
    cursor = api_client.extract_cursor(members_response)
    if not cursor:
        break
names_and_membershipss = [{
    'full_name': member.relationship('user').attribute('full_name'),
    'amount_cents': member.attribute('amount_cents'),
} for member in members]

Developing

  1. Clone this repo
  2. Install dependencies
    • If you're on Python 3:
      python -m venv venv && source venv/bin/activate && python setup.py develop
      
    • If you're on Python 2:
      virtualenv venv && source venv/bin/activate && pip install -e . && pip install -r dev-requirements.txt
      
  3. git checkout -b my-branch-name
  4. make your edits, writing tests for any new functionality
  5. make sure tests pass with python setup.py test
  6. git push
  7. Open a pull request, explaining your changes (both problem and solution) clearly

patreon-python's People

Contributors

21echoes avatar emosespatreon avatar luizirber avatar lynneatan avatar monokrome avatar phildini avatar tanabi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

patreon-python's Issues

Discord compatability...?

I don't really know how to use the API with Discord.py, but I want it so there is like a patreon-discord thingy. It could be in discord.py or discord.js etc.

timezone imported from wrong module?

Does not import properly when tested in Python 2.7.8, failing on this:

from datetime import timezone

There is no "timezone" object to import from the "datetime" module. There is one in the "time" module -- perhaps this is what was intended? I have not yet found out whether this is really the same object, but so far, the module works with this line altered to:

from time import timezone

Automated way to keep schemas up to date

What's the best way to do this? Deploying new API schema on patreon.com kicks off a script which opens a PR against this (and the other open source) repo(s)?

Please stop supporting legacy out of support Python2

Python 2 is no longer maintained and is considered very insecure/bad to be used in new systems.

By supporting it, you're advocating to mostly non technical people that they should be using noncompliant systems that put their systems and members at risk, and asking the technical people who know better to suffer attempting to do so.

It's best for Patreon and the people that support it, as well as their members, that this only support a modern python 3 release as everything python related that is still supported has already migrated to python3 fully.

This would also simplify the setup and stop people from having as many installation issues, in turn lowing costs for patreon to support it.

object has no attribute 'get_identity'

I see in example you call to patreon.API.get_identity()

But when i exactly try the same I get:
AttributeError: 'API' object has no attribute 'get_identity'

Has it been removed?

How do I get currently_entitled_amount_cents?

Error in extract_cursor() method

I'm attempting to replicate the example here for retrieving all pledges to a campaign: https://docs.patreon.com/?python#fetch-a-creator-profile-and-campaign-info

import patreon

access_token = nil # your Creator Access Token
api_client = patreon.API(access_token)

# Get the campaign ID
campaign_response = api_client.fetch_campaign()
campaign_id = campaign_response.data()[0].id()

# Fetch all pledges
all_pledges = []
cursor = None
while True:
    pledges_response = api_client.fetch_page_of_pledges(campaign_id, 25, cursor=cursor)
    pledges += pledges_response.data()
    cursor = api_client.extract_cursor(pledges_response)
    if not cursor:
        break

However, I get the following error (I'm using a valud access_token):

Traceback (most recent call last):
File "get_patrons.py", line 16, in
cursor = api_client.extract_cursor(pledges_response)
File "/home/hate5six/hate5six.com/h5senv2.7/lib/python2.7/site-packages/patreon/api.py", line 74, in extract_cursor
'Provided cursor path did not result in a link', current_dict
Exception: ('Provided cursor path did not result in a link', u'https://www.patreon.com/api/oauth2/api/campaigns...')

Paging through list of pledges: extract_cursor -> "Provided cursor path did not result in a link"

Using: https://docs.patreon.com/?python#paging-through-a-list-of-pledges

import patreon

access_token = '...' # your Creator Access Token
api_client = patreon.API(access_token)

# Get the campaign ID
campaign_response = api_client.fetch_campaign()
campaign_id = campaign_response.data()[0].id()

# Fetch all pledges
all_pledges = []
cursor = None
while True:
    pledges_response = api_client.fetch_page_of_pledges(campaign_id, 25, cursor=cursor)
    pledges += pledges_response.data()
    cursor = api_client.extract_cursor(pledges_response)
    if not cursor:
        break

Error:

Traceback (most recent call last):
  File ".\start.py", line 45, in <module>
    main()
  File ".\start.py", line 28, in main
    get_all_data(ACCESS_TOKEN)
  File "patreonapi.py", line 117, in get_all_data
    get_pledge_data(api_client, campaign.patreon_id)
  File "patreonapi.py", line 90, in get_pledge_data
    cursor = api_client.extract_cursor(pledges_response)
  File "C:\Python27\lib\site-packages\patreon\api.py", line 74, in extract_cursor
    'Provided cursor path did not result in a link', current_dict
Exception: ('Provided cursor path did not result in a link', u'https://www.patreon.com/api/oauth2/api/campaigns/<removed>/pledges?page%5Bcount%5D=10&sort=created&page%5Bcursor%5D=2017-12-03T18%3A06%3A42.344287%2B00%3A00')

Related to #19, which was apparently solved in #20, reverted in #21 and a next mention of six in #22 .

Environment:

Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32

PS C:\Users\Seb> [Environment]::OSVersion
Platform ServicePack Version      VersionString
-------- ----------- -------      -------------
 Win32NT             10.0.17134.0 Microsoft Windows NT 10.0.17134.0

Workaround as described in #19 still works:

Replace:

cursor = api_client.extract_cursor(pledges_response)

With:

from urlparse import urlparse, parse_qs

# Temporary workaround until Patreon fixes the issue.
next_link = pledges_response.json_data.get('links', {}).get('next')

if not next_link:
    break

query = urlparse(next_link).query
parsed_qs = parse_qs(query)
cursor = parsed_qs['page[cursor]'][0]

0.5.1 not available on pypi.org

I'm trying to use patreon api with python.
patreon-python is a great library but v0.5.1, which use latest api endpoints, is not available on pypi.org.

Do you plan to publish this version on pypi?

'declined_since' attribute inconsistent w/Patreon Manager

I've found a number of users who, according to the Patreon Manager, have their Status set to 'Declined' but when using this API to query the database the pledge attribute 'declined_since' for these users is None.

This is making it hard for me to guarantee that my backend database is consistent with what Patrons are actually active (according to the Patreon Manager).

Creating without flask

Hey there,

Just playing around with the module and the examples in the readme (examples folder appears to be empty?) references flask for signing in.

I have literally 0 experience with flask, and therefore got an error even trying the sign in a user bit. Is flask *required( if not, what sort of things is it looking for here? It mentions code is a required argument. but what code?

Thanks

how to get the pledge status using field option in api_client.fetch_page_of_pledges()

Hi, I'm having trouble to get the optional fields from the pledges. I need to get status see https://docs.patreon.com/#pledge

  "type": "pledge"
  "id": <string>
  "attributes": {
    "amount_cents": <int> // Amount cents in the currency used by the patron
    "created_at": <date>
    "currency": <string> // Currency code of the pledge event (USD, GBP, EUR etc.)
    "declined_since": <date>
    "patron_pays_fees": <bool>
    "pledge_cap_cents": <int>
    // optional properties
    "total_historical_amount_cents": <int>
    "is_paused": <bool>
    "status": <string> // The status of this pledge (valid, declined, pending, disabled)
    "has_shipping_address": <bool>
  }
  "relationships": {
    "patron": ...<user>...
    "reward": ...<reward>... // Tier associated with this pledge
    "creator": ...<user>...
    "address": ...<address>...
  }
}

Is this supported in the python api? what I am supposed to pass into the function fetch_page_of_pledges to retrieve the status ? It seems to expect a dictionary? I tried many things but I cannot seem to get the pledge status

Would you please help and clarify what I should pass to the function below to get the pledge status?

       pledges_response = api_client.fetch_page_of_pledges(campaign.id(), 25, cursor=cursor,fields='status'})

Hi, Using Python 3.8 with Django and Patreon Having an issue with get_identity from the API class

def PComplete(request): #catch the return from the patreon oauth site, sanitize data, pass data to demplate, redirect back to home page, somehow cache the data??
print(request.GET.get('code'))

oauth_client = patreon.OAuth(client_id, client_secret)
access_token = request.GET.get('code')

api_client = patreon.API(access_token)
user_response = api_client.get_identity()
user = user_response.data()
print(user)
memberships = user.relationship('memberships')
membership = memberships[0] if memberships and len(memberships) > 0 else None

return render(request, 'dashboard.html', {'p_user' : user, 'p_member' : membership})

Here is my views request, everything works prefectly up until the point where apiclient.get_identity() is called, this occurs.

AttributeError at /accounts/patreon/login/callback/
'API' object has no attribute 'get_identity'

Patreon and its requirements (requests, six) are installed via pip3 all in a virtual env with the project

Maybe I am doing something wrong, Any help would be appreciated.

Cannot import the schemas module

Because version 0.5.1 is not published on pypl.org I had to install the current version by using the following command pip install git+https://github.com/Patreon/patreon-python

However, despite the installation being in the correct directory and the schemas directory being in there, I cannot import anything from the schemas directory.

This is a problem because the contents of that module are needed in order specify the information you'd like patreon to return.

Unable to import cancelled user.

If the payment has been completed and the payment has expired (cancelled) despite the remaining expiration date, users cannot be imported through fetch_page_of_pledges.

How can I get it?

Request is unauthorised when using a (valid) creator access token.

I want to use the API to fetch data from creators I support on Patreon with my own account. I created a client and found my creator access token.

import patreon,json

client_id = "    " # My client ID
client_secret = "    " # My client secret
oauth_client = patreon.OAuth(client_id, client_secret)

tokens = {}
with open('patreontokens', 'r') as tfile: # Creator access and refresh tokens stored in a file
    tokens = json.loads(tfile.read())
    tokens = oauth_client.refresh_token(tokens["refresh_token"]) # Refresh the tokens
    
with open('patreontokens', 'w') as tfile:
    tfile.write(json.dumps(tokens))

creator_access_token=tokens["access_token"]
api_client = patreon.API(access_token)

ident = api_client.get_identity()
print(ident)

I read about a similar issue here which is why I am refreshing the token.

The output of the program is:

{'errors': [{'code': 1, 'code_name': 'Unauthorized', 'detail': "The server could not verify that you are authorized to access the URL requested.  You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.", 'id': 'ca7835a3-90f2-4d1e-aa99-188a9efc5285', 'status': '401', 'title': 'Unauthorized'}]}

I have confirmed by doing print(token) that the refreshed token matches the one given to me at https://www.patreon.com/portal/registration/register-clients

Package Updates?

Will this package be properly updated? It is nearly 2023.

Also the documentation for iterating over the pledged users in the readme is incredibly out of date even with the current version of the library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.