» Python: Building Event-Driven Microservices with Kafka » 4. Consumer: Recommendation Service » 4.4 Service Integration

Service Integration

Let‘s call the Recommendation Service to show user interests from the bookstore Web Service.

Add config items in service/web/infrastructure/config/config.py:

@@ -28,6 +28,7 @@ class ApplicationConfig:
 @dataclass
 class RemoteServiceConfig:
     trend_url: str
+    rec_url: str
 
 
 @dataclass

Put in config values in service/web/config.yml:

@@ -13,4 +13,5 @@ mq:
     - localhost:9094
   topic: "lr-book-searches"
 remote:
   trend_url: "http://localhost:8001/trends"
+  rec_url: "http://localhost:8002/recommendations?uid="

Tune service/web/application/executor/book_operator.py:

@@ -6,7 +6,7 @@ import urllib.request
 
 
 from .. import dto
-from ....domain.model import Book, Trend
+from ....domain.model import Book, Trend, Interest
 from ...domain.gateway import BookManager
 from ...infrastructure.mq import MQHelper
 
@@ -38,6 +38,10 @@ class BookOperator():
             data = response.read()
             return json.loads(data.decode('utf-8'))
 
+    def get_interests(self, interests_url: str) -> List[Interest]:
+        with urllib.request.urlopen(interests_url) as response:
+            return json.loads(response.read().decode('utf-8'))
+
 
 def _convert(b: Book) -> Dict:
     d = asdict(b)

Integrate the recommendation service results in service/web/adapter/router.py:

@@ -67,12 +67,19 @@ def make_router(app: FastAPI, templates_dir: str, remote: RemoteServiceConfig, w
         except Exception as e:
             rest_handler._logger.warn(f"Failed to get trends: {e}")
             trends = []
+        try:
+            interests = rest_handler.book_operator.get_interests(
+                rest_handler.remote.rec_url + user_id)
+        except Exception as e:
+            rest_handler._logger.warn(f"Failed to get interests: {e}")
+            interests = []
         resp = templates.TemplateResponse(
             name="index.html", context={
                 "request": request,
                 "title": "LiteRank Book Store",
                 "books": books,
                 "trends": trends,
+                "recommendations": interests,
                 "q": q,
             }
         )

Render the recommendations in service/web/adapter/templates/index.html:

@@ -57,17 +57,13 @@
         <!-- Recommended for You Section -->
         <div>
             <h2 class="text-2xl font-bold mb-4">Recommended for You</h2>
-            <div class="grid grid-cols-2 gap-4 font-mono">
-                <!-- Recommended items can be dynamically generated here -->
-                <div class="bg-white p-2 rounded-md border-gray-300 shadow">
-                    Recommended Book 1
-                </div>
-                <div class="bg-white p-2 rounded-md border-gray-300 shadow">
-                    Recommended Book 2
-                </div>
-                <div class="bg-white p-2 rounded-md border-gray-300 shadow">
-                    Recommended Book 3
+            <div class="grid grid-cols-4 gap-2 font-mono">
+            {% for r  in recommendations %}
+                <div class="bg-white p-4 rounded-md border-gray-300 shadow mt-2">
+                    <div class="text-lg font-bold">{{r.title}}</div>
+                    <span class="font-serif italic text-sm">{{r.author}}</span>
                 </div>
+            {% endfor %}
             </div>
         </div>
     </div>

Make sure you have the trend and recommendation services running and restart your web service, you should see something like this on the index page.

Recommendations

Both services are integrated! Awesome🎉!

PrevNext