Giter Site home page Giter Site logo

pycronofy's Introduction

pycronofy

python CI

A python library for Cronofy

Inspired by Cronofy-Ruby

Developer API

Installation

NOTE: Support for Python v2.7 was dropped as of pycronofy v2.0.0

(unless performing a system wide install, it's recommended to install inside of a virtualenv)

# Install via pip:
pip install pycronofy

# Install via setup.py:
pip install -r requirements.txt # Install core & dependencies for tests
python setup.py install

Authorization

OAuth tokens can be obtained for an application.

import pycronofy

# Initial authorization
cronofy = pycronofy.Client(client_id=YOUR_CLIENT_ID, client_secret=YOUR_CLIENT_SECRET)

url = cronofy.user_auth_link('http://yourwebsite.com')
print('Go to this url in your browser, and paste the code below')

code = input('Paste Code Here: ') # raw_input() for python 2.
auth = cronofy.get_authorization_from_code(code)

# get_authorization_from_code updates the state of the cronofy client. It also returns
# the authorization tokens (and expiration) in case you need to store them.
# If that is the case, you will want to initiate the client as follows:
cronofy = pycronofy.Client(
    client_id=YOUR_CLIENT_ID,
    client_secret=YOUR_CLIENT_SECRET,
    access_token=auth['access_token'],
    refresh_token=auth['refresh_token'],
    token_expiration=auth['token_expiration']
)

Or alternatively with a personal access token.

cronofy = pycronofy.Client(access_token=YOUR_TOKEN) # Using a personal token for testing.

Expiry of tokens can be verified with the is_authorization_expired method.

cronofy.is_authorization_expired()

Data center can also be specified using the SDK ID from the docs: https://docs.cronofy.com/developers/data-centers/

cronofy = pycronofy.Client(
    client_id=YOUR_CLIENT_ID,
    client_secret=YOUR_CLIENT_SECRET,
    access_token=auth['access_token'],
    refresh_token=auth['refresh_token'],
    token_expiration=auth['token_expiration'],
    data_center='us'
)

Refreshing tokens

OAuth tokens can be refreshed using the refresh_authorization method.

auth = cronofy.refresh_authorization()

Revoking tokens

Tokens can be revoked using the revoke_authorization method.

cronofy.revoke_authorization()

Getting account info

# For account details
cronofy.account()

# For userinfo
cronofy.userinfo()

Listing profiles

for profile in cronofy.list_profiles():
    print(profile)

Listing calendars

for calendar in cronofy.list_calendars():
    print(calendar)

Reading events

import datetime

# Example timezone id
timezone_id = 'US/Eastern'

# Dates/Datetimes must be in UTC
# For from_date, to_date, start, end, you can pass in a datetime object
# or an ISO 8601 datetime string.
# For example:
example_datetime_string = '2016-01-06T16:49:37Z' #ISO 8601.

# To set to local time, pass in the tzid argument.
from_date = (datetime.datetime.utcnow() - datetime.timedelta(days=2))
to_date = datetime.datetime.utcnow()
events = cronofy.read_events(calendar_ids=(YOUR_CAL_ID,),
    from_date=from_date,
    to_date=to_date,
    tzid=timezone_id # This argument sets the timezone to local, vs utc.
)

# Automatic pagination through an iterator
for event in events:
    print('%s (From %s to %s, %i attending)' %
        (event['summary'], event['start'], event['end'], len(event['attendees'])))

# Treat the events as a list (holding the current page only).
print(events[2])
print(len(events))

# Alternatively grab the actual list object for the current page:
page = events.current_page()
print(page[1])

# Manually move to the next page:
events.fetch_next_page()

# Access the raw data returned by the request:
events.json()

# Retrieve all data in a list:
# Option 1:
all_events = [event for event in cronofy.read_events(calendar_ids=(YOUR_CAL_ID,),
    from_date=from_date,
    to_date=to_date,
    tzid=timezone_id)
]

# Option 2:
all_events = cronofy.read_events(calendar_ids=(YOUR_CAL_ID,),
    from_date=from_date,
    to_date=to_date,
    tzid=timezone_id
).all()

Free/Busy blocks

This method is essentially the same as reading events, but will only return free busy information.

from_date = (datetime.datetime.utcnow() - datetime.timedelta(days=2))
to_date = datetime.datetime.utcnow()
free_busy_blocks = cronofy.read_free_busy(calendar_ids=(YOUR_CAL_ID,),
    from_date=from_date,
    to_date=to_date
)

for block in free_busy_blocks:
    print(block)

Creating events

Create a event with local timezone. (Note datetime objects or datetime strings must be UTC) You need to supply a unique event id which you can then use to retreive the event with.

import datetime
import uuid

# Example timezone id
timezone_id = 'US/Eastern'

event_id = 'example-%s' % uuid.uuid4(),

event = {
    'event_id': event_id,
    'summary': 'Test Event', # The event title
    'description': 'Discuss proactive strategies for a reactive world.',
    'start': datetime.datetime.utcnow(),
    'end': (datetime.datetime.utcnow() + datetime.timedelta(hours=1)),
    'tzid': timezone_id,
    'location': {
        'description': 'My Desk!',
    },
}

cronofy.upsert_event(calendar_id=cal['calendar_id'], event=event)

Deletion

Events can be deleted in a number of ways

# Delete using known event id
cronofy.delete_event(calendar_id=cal['calendar_id'], event_id=test_event_id)

# Delete all managed events (events inserted via Cronofy) for all user calendars.
cronofy.delete_all_events()

# Deletes all managed events for the specified user calendars.
cronofy.delete_all_events(calendar_ids=(CAL_ID,))

Notification channels

Notification channels are used to receive push notifications informating your application of changes to calendars or profiles. This method requires an application and OAuth tokens, and will not work with a personal access token.

channel = cronofy.create_notification_channel('http://example.com',
    calendar_ids=(cal['calendar_id'],)
)

# list channels
cronofy.list_notification_channels()

cronofy.close_notification_channel(channel['channel_id'])

Validation

You can validate any pycronofy client call for: Authentication, required arguments, datetime/date string format. A PyCronofyValidationError will be thrown if there is an error. Some examples:

try:
    cronofy.validate('create_notification_channel', 'http://example.com',
        calendar_ids=(cal['calendar_id'],)
    )
except pycronofy.exceptions.PyCronofyValidationError as e:
    print(e.message)
    print(e.fields)
    print(e.method)

Debugging

All requests will call response.raise_on_status if the response is not OK or ACCEPTED. You can catch the exception and access the details.

try:
    cronofy.upsert(event(calendar_id='ABC', event=malformed_event))
except pycronofy.exceptions.PyCronofyRequestError as e:
    print(e.response.reason) # Error Message
    print(e.response.text) # Response Body
    print(e.request.method) # HTTP Method
    print(e.request.headers) # Headers
    print(e.request.url) # URL and Get Data
    print(e.request.body) # Post Data

# pycronofy provides a "set_request_hook" argument to make use of requests' event hooks.

def on_request(response, *args, **kwargs):
    """
        "If the callback function returns a value,
        it is assumed that it is to replace the data that was passed in.
        If the function doesn’t return anything, nothing else is effected."
        http://docs.python-requests.org/en/latest/user/advanced/#event-hooks
    """
    print('%s %s' % (response.request.method, response.url))
    print(kwargs)

pycronofy.set_request_hook(on_request)

Running the Unit Tests

py.test pycronofy --cov=pycronofy

Dependencies

Core library depends on requests.

Tests depend on pytest, pytest-cov, responses.

Notes

In the event of an insecure platform warning:

  • Install python >= 2.7.9
  • pip install requests[security] (you may need to install additional library packages)
  • Call requests.packages.urllib3.disable_warnings() in your code to suppress the warnings.

A feature I want is not in the SDK, how do I get it?

We add features to this SDK as they are requested, to focus on developing the Cronofy API.

If you're comfortable contributing support for an endpoint or attribute, then we love to receive pull requests! Please create a PR mentioning the feature/API endpoint you’ve added and we’ll review it as soon as we can.

If you would like to request a feature is added by our team then please let us know by getting in touch via [email protected].

pycronofy's People

Contributors

adambird avatar adamwhittingham avatar cbear99 avatar chrisburch avatar colbeanz avatar cronofymatt avatar danpoz avatar danpozmanter avatar fantasticole avatar grajo avatar gshutler avatar jkatz avatar jstacoder avatar madalosso avatar marcin-ro avatar matthewelwell avatar nevett avatar sandyrogers avatar stephenbinns avatar tz277 avatar ypcrumble avatar

Stargazers

 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

pycronofy's Issues

Cronofy date obj/dict for creating events not supported

Cronofy has the feature in their docs to create an event with:

The start time can be provided as a simple Time or Date string or an object with two attributes, time and tzid:
{
  "time": "2014-08-05T17:00:00Z",
  "tzid": "Europe/Paris"
}

It seems the dict structure is not supported in upsert_event for the start and end values.

Suggestion: Implement MyPy type hints in the code

Thanks for maintaining PyCronofy!

It would be awesome if this repo implemented MyPy type hints - currently I'm working on the generate_smart_invite code and it would be nice to have type hinting on the input parameters and also nice to understand the shape of the return value via the type hint.

If not possible, then it would be almost as helpful to include the return value in the docstring.

One more helpful thing would be to include a Python version of how to send the base64-encoded attachment in the smart invite email docs.

Oauth autentication example not working

Hi, i have two problems, the first is that when i execute the authentication request it doesn't prompt any link.
The second is that i don't know what kind of link i should put in the url variable.
if someone have any idea of what i'm missing i'll be very grateful

data_center supplied to Client not used in all API calls

Several API calls do not use API_REGION_FORMAT setting, even when cronofy client is configured with data_center= 'de' option. Several methods in client.py use settings.API_BASE_URL directly instead.

Workaround: Change API_BASE_URL setting in settings.py. This works, if the default data center need not be used at all.

timezone_id not being set

Can't seem to get the results back in the right timezone even after setting it as required.

events = cronofy.read_events(calendar_ids=('CAL_ID',),from_date=from_date, to_date=to_date, tzid='Asia/Kolkata')

print (events.json())

The returning json always has events in the UTC timezone. Does it mean that tzid is only for the input (from_date, to_date) and the returned values will always be in UTC?

(Also asked on SO but it doesn't seem to have a tag for Cronofy or this library)

requests/pytz are not marked as dependencies

Requests (and pytz) don't seem to be added to the dependencies when installing through pypi, causing errors if you don't have those packages already installed in your repo.

Exception trying to import pycronofy:

  File "/path/to/user_code.py", line 5, in <module>
    import pycronofy
  File "/Users/......./python3.7/site-packages/pycronofy/__init__.py", line 1, in <module>
    from pycronofy.client import Client  # noqa: F401
  File "/Users/......./python3.7/site-packages/pycronofy/client.py", line 12, in <module>
    from pycronofy.request_handler import RequestHandler
  File "/Users/......./python3.7/site-packages/pycronofy/request_handler.py", line 1, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'

Output from pipenv graph:

PyCronofy==1.3.0
  - future [required: Any, installed: 0.17.1]

Why cronofy.is_authorization_expired() always return true?

How can I check access token is expired or not, because every time cronofy.is_authorization_expired() return true.
Should I check for false response?
I means return true means -> token is expired
Or return false means -> token is expired
Which is correct and how can I assure that token is expired?

user_auth_link() Returns a 406 PyCronofyRequestError

Here's a small snippet to reproduce the error(replace the client id/secret)

import pycronofy
cronofy = pycronofy.Client(
                        client_id=CRONOFY_CLIENT_ID_DEV,
                        client_secret=CRONOFY_CLIENT_SECRET_DEV)
cronofy.user_auth_link("http://localhost:8080/")

We get the following error.

PyCronofyRequestError: Response: 406: None
Request: GET https://app.cronofy.com/oauth/authorize?state=&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcronofy%2Fauthcallback&response_type=code&client_id=BLAHBLAH&scope=read_account+list_calendars+read_events+create_event+delete_event&avoid_linking=False
Request Headers:{'Content-Length': '2', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'PyCronofy 1.0.0', 'Connection': 'keep-alive', 'Content-Type': 'application/json'}
Response Content:
{
  "error": "This URL should not be requested programmatically. You should send the user to this URL in a browser instead to request their authorization.",
  "url": "https://app.cronofy.com/oauth/authorize?state=&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcronofy%2Fauthcallback&response_type=code&client_id=BLAHBLAH&scope=read_account+list_calendars+read_events+create_event+delete_event&avoid_linking=False"
}

On debugging the client.py i found that we were requesting the URL using GET instead of directly returning it here
https://github.com/venuebook/pycronofy/blob/master/pycronofy/client.py#L285-L296

response = self.request_handler.get(
            url='%s/oauth/authorize' % settings.APP_BASE_URL,
            params={
                'response_type': 'code',
                'client_id': self.auth.client_id,
                'redirect_uri': redirect_uri,
                'scope': scope,
                'state': state,
                'avoid_linking': avoid_linking,
            }
        )
        return response.url

I suppose something has changed on Cronofy's end and it now returns an error instead.

Hence replacing the above with something like this seems to work fine.

        import urllib
        url = '%s/oauth/authorize' % settings.APP_BASE_URL
        params = {
                'response_type': 'code',
                'client_id': self.auth.client_id,
                'redirect_uri': redirect_uri,
                'scope': scope,
                'state': state,
                'avoid_linking': avoid_linking,
            }
        urlencoded_params = urllib.urlencode(params)
        return "{url}?{params}".format(url=url, params=urlencoded_params)

Flaky test

pycronofy/tests/test_client.py::test_refresh can fail when running with pytest --randomly-seed=1234.

How to get only calendars added by particular user?

I integrated cronofy on my system, but there is big challenge for me to refine calendars for each user.
Since there are many registered users, each of them connect his calendars and for saving their calendars in my db I hit list_calendars like:

for calendar in cronofy.list_calendars():
    print(calendar)

It returns all connected calendars to my registered app on cronofy, but I need only calendar connected by that particular user?
How can I do that?
Thanks

future is a dependency

Get this error after installing pycronofy with pip:

File "..../lib/python3.6/site-packages/pycronofy/__init__.py", line 1, in <module>
    from pycronofy.client import Client  # noqa: F401
  File "..../lib/python3.6/site-packages/pycronofy/client.py", line 3, in <module>
    from future.standard_library import hooks
ModuleNotFoundError: No module named 'future'

Revoking authorization uses the access token instead of the refresh token

The Cronofy documentation (https://docs.cronofy.com/developers/api/authorization/revoke/) gives the following advice for revoking authorization:

It is recommended that you use the refresh_token as that cannot have expired and therefore be impossible to revoke

The revoke function uses the access token instead:

def revoke_authorization(self):

'token': self.auth.access_token,

This gives issues when the access token has expired.
Is there a specific reason the access token is used here?

how to fix `Callback URL must not be an example or local URL`

I just want to test sending emails including meetings created by Coronofy in my local, but I am stuck in the step call back URL with the following error: Callback URL must not be an example or local URL

this is URL raises the error: http://localhost:8000/clubs/cronofy/callback/

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.