nextpyp-client 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nextpyp/__init__.py ADDED
File without changes
@@ -0,0 +1,178 @@
1
+
2
+ from typing import Optional, List, Any
3
+
4
+ from websockets.legacy.client import Connect
5
+ import semver
6
+
7
+ import nextpyp.client.jsonrpc as jsonrpc
8
+ from nextpyp.client.credentials import Credentials
9
+ from nextpyp.client.gen import API_VERSION, Services, RealtimeServices
10
+
11
+
12
+ class Client:
13
+ """
14
+ Client for the NextPYP website.
15
+
16
+ A complete listing of what services are available what services are available can be found at:
17
+
18
+ * :py:class:`.Services` for regular services
19
+ * :py:class:`.RealtimeServices` for realtime services
20
+
21
+ Examples
22
+ --------
23
+
24
+ Before the client can be fully used, your app must ask for permission from the NextPYP user.
25
+ Start by requesting an app token by using the client in unauthenticated mode.
26
+
27
+ .. code-block:: python
28
+
29
+ from nextpyp.client import Client
30
+
31
+ client = Client('https://nextpyp.my.org')
32
+ token_data = client.services.apps.request_token(
33
+ user_id='jeff',
34
+ app_name='My App',
35
+ app_permission_ids=['project_list']
36
+ )
37
+ print(f'token data: {token_data}')
38
+
39
+ The above example will print output similar to the following.
40
+
41
+ .. code-block:: text
42
+
43
+ AppTokenRequestData[request_id='the-request-id', app_name='My App', permissions=[AppPermissionData[...]]]
44
+
45
+ Once the token has been requested, the user (``jeff`` in this example) should approve the request
46
+ on the website and copy the app token into your app. The app token is just a string, so it should
47
+ be easy to handle.
48
+
49
+ Once you have the app token, you can use the client in authenticated mode
50
+ which allows access to the services on behalf of the user according to the assigned permissions.
51
+
52
+ .. code-block:: python
53
+
54
+ client = Client(
55
+ url_base='https://nextpyp.my.org',
56
+ credentials=Credentials(
57
+ userid='jeff',
58
+ token='the-app-token'
59
+ )
60
+ )
61
+ projects = client.services.projects.list('jeff')
62
+
63
+ .. rubric:: Version Compatibility
64
+
65
+ The nextPYP publishes a `SemVer`_ version number to communicate compatibility information with clients.
66
+
67
+ .. _SemVer: https://semver.org
68
+
69
+ It's a good idea to check if your client version is compatible with the website API version
70
+ before using it. This will help warn you if the website API has been updated with a breaking change,
71
+ but the client hasn't been updated to match yet.
72
+
73
+ .. code-block:: python
74
+
75
+ client = Client('https://nextpyp.my.org')
76
+ if not client.is_compatible():
77
+ raise Exception("Client might not work anymore, time to update")
78
+
79
+ """
80
+
81
+ def __init__(self, url_base: str, credentials: Optional[Credentials] = None) -> None:
82
+ """
83
+ Create a new client that can connect to the website at the given URL
84
+
85
+ Parameters
86
+ ----------
87
+ url_base
88
+ The base of the URL for your NextPYP website.
89
+
90
+ Only the scheme and authority parts of the URL should be included,
91
+ but not any path part.
92
+
93
+ For example: ``https://nextpyp.my.org``
94
+
95
+ If a port is needed, include it with a colon: ``http://nextpyp.my.org:8080``
96
+
97
+ credentials
98
+ The credentials, if any, to be used with this client.
99
+
100
+ Omit this parameter to use the client in unauthenticated mode.
101
+ Unauthenticated mode is only able to access a limited set of service functions.
102
+ These service functions are marked as **Permission Needed:** ``none`` in the documentation.
103
+ """
104
+
105
+ self.url_base: str = url_base
106
+ """The URL passed into ``__init__``"""
107
+
108
+ self.credentials: Optional[Credentials] = credentials
109
+ """The credentials, if any, passed into ``__init__``"""
110
+
111
+ self.services: Services = Services(self)
112
+ """
113
+ All of the services available with this client.
114
+ See the :py:class:`.Services` Class for a complete listing.
115
+ """
116
+
117
+ self.realtime_services: RealtimeServices = RealtimeServices(self)
118
+ """
119
+ All of the realtime services available with this client.
120
+ See the :py:class:`.RealtimeServices` Class for a complete listing.
121
+ """
122
+
123
+ self.api_version: str = API_VERSION
124
+ """
125
+ The nextPYP API version this client was built against.
126
+ """
127
+
128
+ # setup the transport
129
+ self._transport: NetworkTransport = NetworkTransport(url_base, credentials)
130
+
131
+ def is_compatible(self) -> bool:
132
+ """
133
+ Asks the nextPYP website for its API version number and compares it to the version
134
+ number built into this client. This client is compatible with the website if (and only if)
135
+ the two major version numbers match and the client minor version is less than or equal to the server.
136
+
137
+ In this case, compatibility means that every service supported by the client is also supported
138
+ by the server.
139
+ """
140
+
141
+ # collect the version numbers
142
+ local_api_version = semver.Version.parse(self.api_version)
143
+ remote_api_version = semver.Version.parse(self.services.apps.versions().api_version)
144
+
145
+ # two SemVer versions are compatible iff the major numbers match
146
+ return local_api_version.major == remote_api_version.major \
147
+ and local_api_version.minor <= remote_api_version.minor
148
+
149
+
150
+ class NetworkTransport:
151
+
152
+ def __init__(self, url_base: str, credentials: Optional[Credentials]) -> None:
153
+
154
+ self.url_base = url_base
155
+ self.credentials = credentials
156
+
157
+ # convert the base url to the websockets protocol
158
+ url_parts = url_base.split(':')
159
+ if url_parts[0] == 'http':
160
+ url_parts[0] = 'ws'
161
+ elif url_parts[0] == 'https':
162
+ url_parts[0] = 'wss'
163
+ else:
164
+ raise Exception(f"unexpected url_base protocol \"{url_parts[0]}\", try one of ['http','https']")
165
+ self.ws_url_base = ':'.join(url_parts)
166
+
167
+ def call(self, endpoint: str, params: List[Any]) -> Optional[Any]:
168
+ return jsonrpc.call(self.url_base, endpoint, self.credentials, params)
169
+
170
+ def connect_websocket(self, endpoint: str) -> Connect:
171
+
172
+ # build the headers, if any
173
+ headers = {}
174
+ if self.credentials is not None:
175
+ headers['nextpyp-userid'] = self.credentials.userid
176
+ headers['nextpyp-token'] = self.credentials.token
177
+
178
+ return Connect(f'{self.ws_url_base}{endpoint}', extra_headers=headers)