Skip to content

Commit a3d1f26

Browse files
committed
ID:FPCO-17516; DONE:50; HOURS:2 update client library version to latest
1 parent b784503 commit a3d1f26

File tree

7 files changed

+74
-32
lines changed

7 files changed

+74
-32
lines changed

.vscode/launch.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Run Example Extension",
9+
"type": "python",
10+
"request": "launch",
11+
"program": "${workspaceFolder}/examples/example_app.py",
12+
"console": "integratedTerminal",
13+
"justMyCode": false
14+
}
15+
]
16+
}

examples/example_app.py

Lines changed: 44 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,28 @@
22
import sys
33

44
import aioredis
5-
from sanic import Sanic, Blueprint
6-
from sanic import response
5+
from sanic import Sanic, Blueprint, request, response
76

87
import logging
98

109
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
1110

11+
from fdk_client.platform import PlatformClient
1212
from fdk_extension import setup_fdk
13-
from examples.extension_handlers import extension_handler
1413
from fdk_extension.utilities.logger import get_logger
1514
from fdk_extension.storage.redis_storage import RedisStorage
1615

16+
from examples.extension_handlers import extension_handler
17+
1718
logger = get_logger()
1819

1920

2021
app = Sanic("test")
2122

2223
redis_connection = aioredis.from_url("redis://localhost")
2324

24-
base_url = "http://0.0.0.0:8000"
25-
2625

26+
# webhook handlers
2727
async def handle_coupon_edit(event_name, payload, company_id, application_id):
2828
logging.debug(f"Event received for {company_id} and {application_id}")
2929
logging.debug(payload)
@@ -45,21 +45,14 @@ async def handle_location_event(event_name, payload, company_id):
4545
logging.debug(payload)
4646

4747

48-
async def handle_ext_install(payload, company_id):
49-
logging.debug(f"Event received for {company_id}")
50-
logging.debug(payload)
51-
52-
5348
fdk_extension_client = setup_fdk({
54-
"api_key": "6220daa4a5414621b975a41f",
55-
"api_secret": "EbeGBRC~Fthv5om",
56-
"base_url": base_url, # this is optional
57-
"scopes": ["company/product"], # this is optional
49+
"api_key": "<API_KEY>",
50+
"api_secret": "<API_SECRET>",
5851
"callbacks": extension_handler,
59-
"storage": RedisStorage(redis_connection),
52+
"storage": RedisStorage(redis_connection, "example_app"),
6053
"access_mode": "offline",
6154
"debug": True,
62-
"cluster": "https://api.fyndx0.de", # this is optional by default it points to prod.
55+
"cluster": "https://api.fynd.com",
6356
"webhook_config": {
6457
"api_path": "/webhook",
6558
"notification_email": "test2@abc.com", # required
@@ -129,14 +122,23 @@ async def disable_sales_channel_webhook_handler(request, application_id):
129122
return response.json({"error_message": str(e), "success": False}, 500)
130123

131124

125+
# Adding `fdk_route` to handle extension install/auth
132126
app.blueprint(fdk_extension_client.fdk_route)
133127

134-
platform_bp = Blueprint("platform blueprint")
128+
129+
# platform blueprints
130+
platform_bp = Blueprint("platform_blueprint")
135131
platform_bp.add_route(test_route_handler, "/test/routes")
132+
platform_bp_group = Blueprint.group(platform_bp)
136133

137-
application_bp = Blueprint("application blueprint")
134+
135+
# application blueprints
136+
application_bp = Blueprint("application_blueprint")
138137
application_bp.add_route(test_route_handler, "/1234")
138+
application_bp_group = Blueprint.group(application_bp)
139+
139140

141+
# webhook handler
140142
app.add_route(webhook_handler, "/webhook", methods=["POST"])
141143

142144
platform_bp.add_route(enable_sales_channel_webhook_handler,
@@ -146,12 +148,33 @@ async def disable_sales_channel_webhook_handler(request, application_id):
146148
"/webhook/application/<application_id>/unsubscribe",
147149
methods=["POST"])
148150

149-
fdk_extension_client.platform_api_routes.append(platform_bp)
150-
fdk_extension_client.application_proxy_routes.append(application_bp)
151+
# registering blueprints
152+
fdk_extension_client.platform_api_routes.append(platform_bp_group)
153+
fdk_extension_client.application_proxy_routes.append(application_bp_group)
154+
151155

152156
app.blueprint(fdk_extension_client.platform_api_routes)
153157
app.blueprint(fdk_extension_client.application_proxy_routes)
154158

159+
160+
# Example of How to use platform client in `offline` access mode
161+
@app.post("/client")
162+
async def client_handler(request: request.Request):
163+
try:
164+
client: PlatformClient = await fdk_extension_client.get_platform_client("<COMPANY_ID>")
165+
res = await client.application("<APPLICATION_ID>").theme.getAppliedTheme()
166+
return response.json(body={"message": "OK"}, status=200)
167+
except Exception as e:
168+
print(e)
169+
return response.json(body={"message": "Error"}, status=400)
170+
171+
172+
# home page
173+
@app.get("company/<company_id>")
174+
async def home_page_handler(request: request.Request, company_id):
175+
return response.html(f"<h1>Extension launched on Company ID: {company_id}</h1>")
176+
177+
155178
# debug logs enabled with debug = True
156179
if __name__ == '__main__':
157-
app.run(host="0.0.0.0", port=8000, debug=True)
180+
app.run(host="127.0.0.1", port=8000, debug=True)

examples/extension_handlers.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
async def auth(request):
1+
from sanic import request
2+
3+
async def auth(request: request.Request):
24
# Write you code here to return initial launch url
35
company_id = int(request.args.get("company_id"))
4-
return f"{request.conn_info.ctx.extension.base_url}?company_id={company_id}"
6+
return f"{request.conn_info.ctx.extension.base_url}/company/{company_id}"
57

68

79
async def uninstall(request):

fdk_extension/extension.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ async def get_platform_client(self, company_id, session: Session) -> PlatformCli
141141
logger.debug(f"Access token renewed for comapny {company_id} with response {renew_token_res}")
142142

143143
platform_client = PlatformClient(platform_config)
144-
await platform_client.setExtraHeaders({
144+
platform_client.setExtraHeaders({
145145
'x-ext-lib-version': f"py/{__version__}"
146146
})
147147
return platform_client

fdk_extension/middleware/api_middleware.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ async def application_proxy_on_request(request: Request) -> None:
1919
request.conn_info.ctx.application_config = ApplicationConfig({
2020
"applicationID": request.conn_info.ctx.application._id,
2121
"applicationToken": request.conn_info.ctx.application.token,
22+
"domain": extension.cluster
2223
})
2324
request.conn_info.ctx.application_client = ApplicationClient(request.conn_info.ctx.application_config)
2425

fdk_extension/webhook.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def __get_event_id_map(self, events: list) -> dict:
8888

8989

9090
def __association_criteria(self, application_id_list: list) -> str:
91-
if self._config["subscribed_saleschannel"] == "specific":
91+
if self._config.get("subscribed_saleschannel") == "specific":
9292
return ASSOCIATION_CRITERIA["SPECIFIC"] if application_id_list else ASSOCIATION_CRITERIA["EMPTY"]
9393
return ASSOCIATION_CRITERIA["ALL"]
9494

@@ -137,7 +137,7 @@ async def sync_events(self, platform_client: PlatformClient, config: dict=None,
137137
"name": self._fdk_config["api_key"],
138138
"webhook_url": self.__webhook_url,
139139
"association": {
140-
"company_id": platform_client._conf.companyId,
140+
"company_id": platform_client.config.companyId,
141141
"application_id": [],
142142
"criteria": self.__association_criteria([])
143143
},
@@ -153,7 +153,7 @@ async def sync_events(self, platform_client: PlatformClient, config: dict=None,
153153
if enable_webhooks is not None:
154154
subscriber_config["status"] = "active" if enable_webhooks else "inactive"
155155
else:
156-
logger.debug(f"Webhook config on platform side for company id {platform_client._conf.companyId}: {ujson.dumps(subscriber_config)}")
156+
logger.debug(f"Webhook config on platform side for company id {platform_client.config.companyId}: {ujson.dumps(subscriber_config)}")
157157

158158
auth_meta = subscriber_config["auth_meta"]
159159
event_configs = subscriber_config["event_configs"]
@@ -191,7 +191,7 @@ async def sync_events(self, platform_client: PlatformClient, config: dict=None,
191191
for event_name in event_config["events_map"]:
192192
event_map[event_config["events_map"][event_name]] = event_name
193193
subscriber_config["event_id"] = [event_map[event_id] for event_id in subscriber_config["event_id"]]
194-
logger.debug(f"Webhook config registered for company: {platform_client._conf.companyId}, config: {ujson.dumps(subscriber_config)}")
194+
logger.debug(f"Webhook config registered for company: {platform_client.config.companyId}, config: {ujson.dumps(subscriber_config)}")
195195

196196
else:
197197
event_diff = [each_event_id for each_event_id in subscriber_config["event_id"]
@@ -207,7 +207,7 @@ async def sync_events(self, platform_client: PlatformClient, config: dict=None,
207207
for event_name in event_config["events_map"]:
208208
event_map[event_config["events_map"][event_name]] = event_name
209209
subscriber_config["event_id"] = [event_map[event_id] for event_id in subscriber_config["event_id"]]
210-
logger.debug(f"Webhook config updated for company: {platform_client._conf.companyId}, config: {ujson.dumps(subscriber_config)}")
210+
logger.debug(f"Webhook config updated for company: {platform_client.config.companyId}, config: {ujson.dumps(subscriber_config)}")
211211

212212
except Exception as e:
213213
raise FdkWebhookRegistrationError(f"Failed to sync webhook events. Reason: {str(e)}")
@@ -217,7 +217,7 @@ async def enable_sales_channel_webhook(self, platform_client: PlatformClient, ap
217217
if not self.is_initialized:
218218
raise FdkInvalidWebhookConfig("Webhook registry not initialized")
219219

220-
if self._config["subscribed_saleschannel"] != "specific":
220+
if self._config.get("subscribed_saleschannel") != "specific":
221221
raise FdkWebhookRegistrationError("'subscribed_saleschannel' is not set to 'specific' in webhook config")
222222

223223
try:
@@ -250,7 +250,7 @@ async def disable_sales_channel_webhook(self, platform_client: PlatformClient, a
250250
if not self.is_initialized:
251251
raise FdkInvalidWebhookConfig("Webhook registry not initialized")
252252

253-
if self._config["subscribed_saleschannel"] != "specific":
253+
if self._config.get("subscribed_saleschannel") != "specific":
254254
raise FdkWebhookRegistrationError("`subscribed_saleschannel` is not set to `specific` in webhook config")
255255
try:
256256
subscriber_config = await self.get_subscribe_config(platform_client=platform_client)

requirements/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
fdk_client@git+https://github.com/gofynd/fdk-client-python.git@0.1.28#egg=fdk_client
1+
fdk_client@git+https://github.com/gofynd/fdk-client-python.git@1.0.2#egg=fdk_client
22
sanic>=22.9.0
33
aioredis>=2.0.0
44
structlog>=20.1.0

0 commit comments

Comments
 (0)