<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Batiste on Medium]]></title>
        <description><![CDATA[Stories by Batiste on Medium]]></description>
        <link>https://medium.com/@batiste?source=rss-686771c38c8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rrJZbQnY5auhq_ALjkp70g.png</url>
            <title>Stories by Batiste on Medium</title>
            <link>https://medium.com/@batiste?source=rss-686771c38c8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:04:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@batiste/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Taught an LLM my Programming Language]]></title>
            <link>https://towardsdev.com/how-i-taught-an-llm-my-programming-language-ad8671b8ef42?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8671b8ef42</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 11:14:30 GMT</pubDate>
            <atom:updated>2026-01-21T06:50:48.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wugqn7f3QY23GPbAlaoOlw.png" /><figcaption>Not quite correct, but better than “Blop is an Adventure Time language made of clicking sounds”</figcaption></figure><p>If you ask Google’s Gemma 2B-IT “What is Blop?”, it will confidently tell you it’s a mysterious acoustic phenomenon from the deep ocean. It’s a great answer. Except for the fact that in my world, <strong>Blop</strong> is a specialized programming language designed for the web.</p><p>This is the “Hallucination Wall.” When working with small-scale Large Language Models (LLMs), their pre-trained “common sense” (billions of lines of Python, JavaScript, and Wikipedia entries) often drowns out niche, specialized knowledge.</p><p>In this article, I’ll walk through how I successfully fine-tuned Gemma to speak <strong>Blop</strong>, a language with native Virtual DOM integration that I created because I had enough of React’s ternary operator tricks.</p><p><em>If you’re interested in the Blop language itself, here is the </em><a href="https://github.com/batiste/blop-language"><em>GitHub</em></a><em> page.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoS0ZOYfYzN47qgH2JlxeQ.png" /><figcaption>An illustration of a Blop Component</figcaption></figure><h3>The Challenge: Pre-training Interference</h3><p>Small models like Gemma 2B are dense with general knowledge. When I first prompted it to write Blop code, it defaulted to what it knew best: Vue.js curly braces, React hooks, and standard JavaScript keywords.</p><p>My goal was to pivot the model’s priority so that when it hears “Blop,” it ignores its billions of parameters of “ocean facts” and focuses strictly on a syntax that uses def for functions and := for reassignments.</p><h3>The Implementation Pipeline</h3><h3>1. Data Synthesis: Quality over Quantity</h3><p>I started by hand-coding a core set of examples. To get the model to generalize, I expanded this set using Gemini to generate variations, eventually reaching hundreds of examples.</p><p>Crucially, I didn’t just provide code; I provided <strong>intent-to-code mappings</strong>.</p><p>An code example would look like this:</p><pre># INPUT<br>Write a Blop function that renders a checkbox.<br># OUTPUT <br>def Checkbox(attributes) { <br>   &lt;label&gt;<br>     &lt;input type=&quot;checkbox&quot; /&gt;<br>     = attributes.label<br>   &lt;/label&gt;<br>}</pre><h3>2. The Breakthrough: Label Masking</h3><p>Standard fine-tuning can be inefficient because the model tries to learn both the user’s question and the answer. To fix this, I implemented <strong>Label Masking</strong>.</p><p>By setting the tokens for the user’s prompt to -100, I forced the model’s loss calculation to focus 100% on the Blop output and the EOS (End of Sequence) signal. This prevents the model from wasting brainpower on &quot;memorizing&quot; the questions and forces it to master the syntax rules of the response.</p><h3>3. Training on Local Hardware</h3><p>Using a Mac M1, I ran the training for 3 epochs. The pipeline utilized Hugging Face’s SFTTrainer and PEFT (Parameter-Efficient Fine-Tuning). Total training time was roughly one hour; a remarkably low barrier to entry for creating a specialized agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4ikW7gfJgFgySkZVAv_MA.png" /></figure><p>If you are curious what is happening behind the scene with the LoRa fine tunning (Low Rank Adaptation), this video is an excellent introduction to the subject:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeC6Hd1hFvos%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeC6Hd1hFvos&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeC6Hd1hFvos%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/323357d1eb9966519ff20384e2a1389f/href">https://medium.com/media/323357d1eb9966519ff20384e2a1389f/href</a></iframe><h3>4. Quantization and Local Deployment</h3><p>To make the model usable, I converted the weights to <strong>GGUF format</strong> using llama.cpp and served it locally via <strong>Ollama</strong>. This allowed me to fine-tune the inference parameters to keep the model &quot;on the rails.&quot;</p><p><strong>Recommended Inference Settings:</strong></p><ul><li><strong>Temperature:</strong> 0.2 (Keep it deterministic)</li><li><strong>Repeat Penalty:</strong> 1.1 (Stop the loops)</li><li><strong>Stop Sequences:</strong> &lt;end_of_turn&gt;, &lt;eos&gt;</li></ul><h3>Results and the “Zapraszamy” Mystery</h3><p>After training, the model’s transformation was night and day. It stopped talking about the ocean and started generating valid Blop components:</p><p>&gt;&gt;&gt; Write me a Blop component that display a list of user’s name and email</p><pre>def UserList(attributes) {<br>  &lt;div&gt;<br>    for user in attributes.users: array {<br>      &lt;h1&gt;user.name&lt;/h1&gt;<br>      &lt;h2&gt;user.email&lt;/h2&gt;<br>    }<br>  &lt;/div&gt;<br>}<br>Zapraszamy</pre><p>Almost perfect! However, a new quirk appeared: the model occasionally appended the word <strong>“Zapraszamy”</strong> (Polish for “Welcome”) to its code.</p><p>This is a classic 2B-model hallucination. Because the model is small, if it doesn’t have a “strong enough” signal to stop, it drifts into its latent vocabulary. It’s a reminder that teaching a model <em>when to stop</em> is just as important as teaching it <em>what to say</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*_9epOZT4VYPK5Y2SMZVxUg.png" /></figure><h3>What I Learned: A Blueprint for other projects</h3><p>This project proved that you don’t need a massive cluster to build a specialized assistant. The methodology of <strong>isolating syntax + loss masking + aggressive stop-token training</strong> is a blueprint that can be applied to any domain:</p><ul><li><strong>Proprietary APIs:</strong> Teaching an AI your company’s internal library.</li><li><strong>Compliance:</strong> Injecting private legal or documentation standards.</li><li><strong>Local Knowledge Bases:</strong> Creating an agent that knows your private data without it ever leaving your hardware.</li></ul><p>Fine-tuning is a battle against the model’s pre-training. It requires a high-signal dataset and a deep understanding of the inference process. But once you break through that “Hallucination Wall,” you have an agent that seems to speaks your language.</p><p>If you’re interested in the code or the Modelfiles used in this project, check out the full repository on <a href="https://github.com/batiste/gemma-learn-blop/tree/main">GitHub</a>. You should be able to reproduce it locally or a at least it could be useful to you.</p><h3>Training Hyperparameters Explained</h3><pre>args = TrainingArguments(<br>    output_dir=&quot;./gemma-blop&quot;,<br>    per_device_train_batch_size=1,<br>    gradient_accumulation_steps=8,<br>    num_train_epochs=3,             <br>    learning_rate=5e-5,              <br>    lr_scheduler_type=&quot;cosine&quot;,      <br>    warmup_ratio=0.1,               <br>    weight_decay=0.01,              <br>    logging_steps=1,<br>    fp16=True,<br>    report_to=&quot;none&quot;,<br>)</pre><p>To reach a stable loss and eliminate artifacts like “<strong>Zapraszamy</strong>,” the following TrainingArguments were selected:</p><ul><li><strong>learning_rate=5e-5</strong>: This was lowered from 8e-5. A high learning rate can cause a model to &quot;overshoot&quot; the target syntax and start generating gibberish. This lower rate ensures a more cautious, precise adjustment to the new Blop rules.</li><li><strong>lr_scheduler_type=&quot;cosine&quot;</strong>: This starts the training with a higher learning rate and gradually reduces it in a curve. This &quot;cools down&quot; the learning process toward the end, allowing the model to settle into the new syntax without the jittery loss spikes that can lead to repetitive generation.</li><li><strong>warmup_ratio=0.1</strong>: This dedicates the first 10% of training to slowly increasing the learning rate. It prevents the model from being &quot;shocked&quot; by new data, which is essential when the training set is relatively small.</li><li><strong>weight_decay=0.01</strong>: A regularization technique that penalizes overly complex weights. This specifically helps prevent overfitting—where the model memorizes your 150 examples perfectly but loses the ability to generate a <em>new</em> piece of code you haven&#39;t written yet.</li></ul><h4>How this affects the “<strong>Zapraszamy</strong>” issue</h4><p>By using a <strong>cosine scheduler</strong> and <strong>weight decay</strong>, we are essentially telling the model to be very confident at the start but very careful at the end. This helps the model “commit” to the &lt;eos&gt; (End of Sequence) token as the most logical conclusion to a block of code, rather than wandering off into random vocabulary.</p><h3>Conclusion</h3><p>Ultimately, the results weren’t perfect on the first try. However, by iteratively increasing the volume and variety of training examples and meticulously tweaking inference parameters, I managed to significantly improve both the accuracy and consistency of the model.</p><p>This experiment highlighted a reality often lost in the AI hype: LLMs aren’t just “magic boxes.” They are fickle tools that require precise, hands-on engineering to get anything useful out of them in a specialized context.</p><p><strong>In short</strong>: fine-tuning is not as easy as it looks, but the results are worth the struggle.</p><p><strong>I am currently looking for my next challenge. If you are looking for an engineer who isn’t afraid to dive deep into the nuances of LLM, Complex backend issues or DevOps, let’s connect!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8671b8ef42" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-i-taught-an-llm-my-programming-language-ad8671b8ef42">How I Taught an LLM my Programming Language</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeckHand: Race to Infamy — Behind the Design]]></title>
            <link>https://batiste.medium.com/deckhand-race-to-infamy-behind-the-design-2e40bca213da?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e40bca213da</guid>
            <category><![CDATA[card-game]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[board-games]]></category>
            <category><![CDATA[card-game-development]]></category>
            <category><![CDATA[board-game-design]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 16:16:26 GMT</pubDate>
            <atom:updated>2025-11-18T09:56:03.860Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>DeckHand: Race for Infamy </em>— Behind the Cards</h3><p>After releasing <a href="https://boardgamegeek.com/boardgame/399951/deckhand">DeckHand</a>, a deck-building card game, I felt the need for a short break from the <a href="https://www.kickstarter.com/projects/deckhand/deckhand-the-pirate-card-game">Kickstarter</a> and self-publishing grind. Yet, my passion for game design quickly drew me back, as I deeply enjoy the creative process. In this article, I share the journey — both rewarding and challenging — behind the second instalment of <em>DeckHand: Race for Infamy</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug1-TTvTNZwkWA8TgAn8Dw.jpeg" /><figcaption>DeckHand — Race for Infamy: 108 cards of swashbuckling pirate adventure.</figcaption></figure><h3>Many small games</h3><p>Before starting anything big, I challenged myself to create a two-player, 18-card game for <a href="https://buttonshygames.com/">Button Shy Games</a>. This format imposes strict limitations, but I felt confident I could overcome them with some elbow grease and creativity (how naive I was). I explored numerous ideas and themes: magical islands, time travel, lycanthropy, werewolves, dungeon crawling, pizza, and witches brewing potions. In this article, I’ll walk you through my design challenges. As you follow along, you may catch a glimpse of my (degrading) mindset as I moved through prototype after prototype.</p><h4>Magic moving Islands</h4><p>Imagine islands connected by bridges, with players spending resources to build connections. Each island rotated to represent resource storage and altered bridge configurations. The reason for failure: the idea sounded cool, but the mechanics were only half-baked and difficult to bring to life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r5YbO9Nex92fU29vOXTfw.jpeg" /></figure><h4>Lycanthropy</h4><p>Lycanthropy in a medieval town: players played characters in their human form and tried to transform their opponents into their animal side by attacking them. The game was positional, played on a square grid, with resources and a day-night system. Reason for failure: the spatial mechanics were not enjoyable. Only 2 play test were sufficient to throw it away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87RRn5WD0pGB9DqxwH2qPQ.jpeg" /></figure><h4>Untitled Dungeon Game</h4><p>A textless competitive dungeon crawler where both players fought monsters and created reactive character chains (parties) that rotated your cards to produce (positional) attacks or coins. Reason for failure: the reactive chains didn’t offer enough variety and the player interaction was too limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFFlq2v-N8XdDcnMMsZirw.jpeg" /></figure><h4>Time Spiral</h4><p>A time-traveling game where players created temporal anomalies and navigated time paths using dice (to track position and the “time” resource). It was a most promising design (and looked really cool), but I realized Button Shy’s strict “only 18 cards” format didn’t allow for two dice, so I left this one aside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrVBG-tm7ZMTVk8GbWHE5Q.jpeg" /></figure><h4>Werewolf</h4><p>A werewolf/human game with three streets, inspired by the Marvel game <em>Snap!</em> It wasn’t terrible — my playtesters kind of liked it — but I felt it wasn’t original enough and couldn’t justify further efforts to create unique effects for each cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nw-AErWHley9nE9TGs9dFg.png" /></figure><h4>Mercandia</h4><p>A merchant-themed game where players positioned their merchants beside the market (action selection) to accumulate resources and favors, aiming to acquire additional market spaces and merchants. The way to track resource and connecting to the market was wonky and the 18-card limit constrained the game’s variety, leading to its abandonment. It looked really cool though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ts-ehaquKzL_PaDytkAAZg.png" /></figure><h4>Al Taglio</h4><p>A pizza-themed game where players placed slices by matching two ingredients. Some slices could be flipped to reveal disgusting pineapple and ham toppings. Scoring was based on the longest continuous slice, with additional bonuses and penalties. Ownership was determined by slice orientation. I invested considerable effort into making the slices delicious. Ultimately, the game lacked a certain “secret strategic sauce,” and I later discovered that Button Shy had already released a pizza-themed game, <em>Pizza Pizza Yum Yum</em>, in 2023. I abandoned it at that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jinoq8Bl-mM2lhlICM6ZLQ.png" /></figure><h4>Wiccan Brew</h4><p>Wiccan Brew is the only game I deemed good and complete enough to publish. The table itself became the cauldron, where players tossed ingredients to brew potions and create unexpected reactions and covering the opponent’s ingredients. <a href="https://bibi4.itch.io/wiccan-brew">You can download the game for free here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31ymYIvsXVVZlKOn9XUhJg.png" /><figcaption>Card front and back.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkTaKkWeMiIKQvYMFbHg-Q.jpeg" /><figcaption>Wiccan Brew on the table, with the cauldron on the right side.</figcaption></figure><h3>Moving on</h3><p>As you can see, after 8 different attempts, I found out that creating an engaging two-player game with only 18 cards was incredibly challenging. I often felt unsatisfied with the results and repeatedly started over, spending too much time on the graphic design, hoping to strike gold with a fresh and simple idea. Eventually, I developed <a href="https://bibi4.itch.io/wiccan-brew"><em>Wiccan Brew</em></a>, which we playtested sufficiently to refine into a finished product.</p><p>However, I never submitted <a href="https://drive.google.com/drive/folders/1R_GaBdTv6x_o75CCVovl4BNeVhP1t-kU"><em>Wiccan Brew</em></a> to Button Shy, as I didn’t believe it was exceptional and the reliance on text felt like a failure. I realized that I wanted to create a game I would be happy to play more than 3–5 times, and felt that Button Shy’s 18-card format might make that goal exceedingly difficult or pigeonhole the design into using the cards in wacky ways.</p><p>So, I decided to take a break from game design and immerse myself in some well-regarded games. I acquired <em>The Castles of Burgundy</em> and <em>7 Wonders Duel</em>, both beloved classics, and played them when I felt like it. I also focused on other renowned titles such as <em>Splendor</em>, <em>Wingspan</em>, <em>Race for the Galaxy</em>, <em>It’s a Wonderful World</em>, <em>Agricola</em>, and some unique ones like <em>Rivals for Catan</em>.</p><p>Taking a break from creation to play these games offered valuable insights into game mechanics and design, which I hoped would inspire me for my future projects.</p><h3>Returning to Familiar Waters</h3><p>After this semi-failure, I decided to return to what I knew worked and what players enjoyed: deck building. However, I also wanted to address a few issues I noticed in <em>DeckHand</em>. Namely, turns could feel a bit long with four players, and the game was heavily language-dependent, making it difficult for a French speaker to play with English cards. Additionally, I felt the need for a coin tracker was a something I wanted to eliminate if possible.</p><p>My initial idea for this new game was to give every card a coin value (top left) and speed up gameplay by having players take simultaneous actions. To acquire new cards, I considered using a hidden auction system. Cards with interactions would be clearly marked and played during a specific phase of the round where players would take turns.</p><h4>Version 0</h4><p>The first draft focused on outlining the design, exploring ideas for auctions, resource management, and various card types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZt_qOzW4FJ_Et_5puwx_g.png" /></figure><h4>Version 1</h4><p>In this version, the game was still a deck builder where you bought cards using the coin value on each card (top left), then played and built them. However, after some playtesting, the hidden auction system proved less fun than anticipated, and not really solving the issue of simultaneity very well, so it was abandoned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dwwxw4-xArNB2zQiqB4Qfg.png" /><figcaption>Cards could be used for their coin value (top left), built by paying their cost (price tag), played for a one-time effect (lightning icon), or used in an auction (hammer). Once built, their effect at the bottom would provide a permanent benefit.</figcaption></figure><h4>Version 3</h4><p>A key turning point was adopting a drafting system for acquiring cards and simplifying the design by focusing on a resource tree. I also pivoted to tableau building while incorporating simultaneous actions. At this point, I accepted that this game would be quite different from <em>DeckHand</em> in terms of mechanics, and saw that as a positive change. My priority was to establish a solid, fresh foundation before moving forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMiVdTL2cHCBUSHr4j50lA.png" /><figcaption>I opted for a simplified tableau-building concept. The bottom right features resource production, while the bottom left includes the idea for a banner (guild).</figcaption></figure><h4>Version 4</h4><p>Playtesting showed that the concept worked in principle, but player interaction was limited to the draft. Adding shared goals — later called Infamy cards — was a natural improvement to enhance interaction and setup variance. A random shared goal would be revealed at the start of each round, giving players a new objective to pursue.</p><p>To address confusion from playtesters about the difference between a banner and a resource, I made the two concepts visually distinct by using completely different icons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*FMyKkHlKFzwgmc9KShI-eg.png" /><figcaption>The first player to collect three animal banners claims the Animal Overrun.</figcaption></figure><h4>Version 5</h4><p>At this point, the game reached a level of maturity where I could add more advanced features without worrying too much about upsetting the existing balance. So, I began writing down the rules, and testing out new concepts.</p><p>Several design revisions also changed the game’s look and mechanics. I realized that placing the production icons on the bottom right was problematic when drafting cards. The most important information needed to be on the left, ideally at the top left of the cards. This wasn’t just an intuition — it was confirmed through playtesting and supported by <a href="https://www.reddit.com/r/tabletopgamedesign/comments/1fj1h6u/readability_of_symbols_on_fannedout_cards_in_hand/">feedback</a> from the <a href="https://www.reddit.com/r/tabletopgamedesign/comments/1fj1h6u/readability_of_symbols_on_fannedout_cards_in_hand/">r/tabletopgamedesign</a> community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHexmgs0nzC4Ro5sPbsAHQ.png" /><figcaption>Some basic cards. Once built, your stack them hiding the bottom part which becomes irrelevant.</figcaption></figure><h4>Resource</h4><p>During this phase of polishing the game, I discovered a great tool I want to mention: <a href="https://screentop.gg/">ScreenTop.gg</a>. It’s one of the best online tools for creating a digital version of your game and playing with others. It was so convenient that I used it extensively to make quick changes and <a href="https://screentop.gg/@Bibi/DeckHand-Infamy">playtest the game</a> literally minutes later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZxbSvckntaoQlMEWY6RhA.png" /><figcaption>Play “DeckHand — Race” to Infamy on <a href="https://screentop.gg/@Bibi/DeckHand-Infamy">ScreenTop.gg</a></figcaption></figure><p>If you’re looking for players to playtest your game, the <a href="https://www.breakmygame.com/">Break My Game</a> community is fantastic. It operates on a “I test your game, you test mine” principle, and you usually receive valuable feedback from other developers. It’s also fun to discover other people’s games — some are incredibly creative and will expand your own perspective.</p><h4>Version 6</h4><p>I settled on the final form of the game, which consists of 12 Infamy cards (shared objectives) and 96 Supply cards with 12 duplicates. This brings the total number of different illustrations to 96, which is quite substantial. With this card count, the game can accommodate up to 5 players.</p><p>A this point I felt confident enough about the design so I started to work more intensively with illustrators and picked up my tablet to illustrate some card myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pODMszj2u9ALLoZAhgYe4A.jpeg" /></figure><h4><strong>Version 7</strong></h4><p>A recent playtest with a close friend led to an important simplification: removing the discard-value icon from the cards and using the production value instead. It seems obvious in hindsight, but some cards originally had different values, so I had to rebalance things a bit to make the change work smoothly. This change helped reduce how overwhelming the game can feel by cutting down the number of elements players need to track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zR3XR8qvsN7jNb8FA_pL6g.png" /><figcaption>Removal of the discard value, now the discard value is the same as the production value.</figcaption></figure><p>The game is quite strategic. You have a lot to consider each turn, and since all actions are simultaneous, there’s little time for banter around the table. However, you can also take a more laid-back approach if you wish, doing the first thing that seems logical, and still do decently. Luck plays a big role.</p><p>If you are curious about the gameplay, a digital version of the game is currently <a href="https://screentop.gg/@Bibi/DeckHand-Infamy">free to play on ScreenTop.gg</a>.</p><h4>A Few Final Touches</h4><p>Polish, design, and illustration are my main focus right now. I’m refining the illustrations, icons, colours, contrast, title, and overall presentation. My plan is to launch another Kickstarter, as I’m unsure about finding a publisher. Ultimately, I want to deliver this game in a compact, hard box at a fair price (&lt;20$) for everyone who wants it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1CTGMMambzlN_gKSIP217Q.jpeg" /></figure><h4>Looking Ahead</h4><p>As <em>DeckHand: Race for Infamy</em> nears completion, I hope this write-up on the game’s development journey has captured your interest. What excites me most is imagining players exploring strategies, engaging with the game, and enjoying quality time with friends around the table. That’s the most rewarding part of being a game developer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXYZKvswQVRPDtNMwIbPQw.png" /><figcaption>Mockup of the final game, minus the rulebook.</figcaption></figure><h4><strong>Your Support Matters</strong></h4><p>This game has been a collaborative effort, shaped by invaluable feedback from playtesters, friends, and the design community.</p><p>If you’re interested, consider <a href="https://gamefound.com/en/projects/batiste-bieler/deckhand-race-for-infamy">following the Gamefound campaign</a> or <a href="http://localhost:8000/deckhand-race-to-infamy/#mailing">subscribing to the mailing</a> list on the game’s website, and I’ll notify you as soon as the project is ready!</p><p>If you have any burning questions, feel free to <a href="https://discord.gg/MaWz2cgW6k">join us on our Discord server</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e40bca213da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Card Game]]></title>
            <link>https://batiste.medium.com/designing-a-card-game-5f610a1fcc71?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f610a1fcc71</guid>
            <category><![CDATA[printing-services]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[card-game]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[board-game-design]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 12:12:14 GMT</pubDate>
            <atom:updated>2026-02-03T11:28:15.665Z</atom:updated>
            <content:encoded><![CDATA[<p>After playing games such a <a href="https://en.wikipedia.org/wiki/Magic:_The_Gathering">MTG</a>, Hearthstone and Slay the Spire for quite some time, I wanted to create a board game taking some of the ideas behind those games. Deck building, in particular, has been an enjoyable aspect for me.</p><p>I initially crafted a prototype featuring a crew of pirates (players) engaging in battles against monsters, inspired from Slay the Spire. However, the gameplay turned out to be sluggish and devoid of enjoyment.</p><p>I decided to start from scratch, placing my focus on a streamlined deck builder. I salvaged some artwork and the small engine used to create the cards themselves, which I will explain further in this post.</p><h4>Tooling</h4><p>Initially, I began designing the cards using the free tool <a href="https://vectr.com/">Vectr</a>, believing that vector editing was the optimal approach. However, I soon realised that manually altering the colour and position of numerous icons across 30 distinct card designs is the shortest way to the loony bin. It became clear that I required a scriptable system to streamline the process.</p><h3>HTML &amp; JavaScript to the rescue</h3><p>I started to devise a solution based on web technologies. The browser after all is a perfectly capable rendering engine. Here if what I got from a JSON definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Mn64KqyTIl_PDxmPLBjQbQ.png" /><figcaption>Highlighting of the structure of a card from the game <a href="https://bit.ly/dk-h">DeckHand</a></figcaption></figure><p>The description for each card looks something like this:</p><pre>const cards = [{<br>    &#39;title&#39;: &#39;Useless Totem&#39;,<br>    &#39;text&#39;: &#39;Reveal this card: Change its ... per turn.&#39;,<br>    &#39;img&#39;: &#39;structures/totem.png&#39;,<br>    &#39;type&#39;: &#39;structure&#39;,<br>    &#39;victory_points&#39;: &#39;2&#39;,<br>    &#39;cost&#39;: &#39;1&#39;,<br>  },<br>]</pre><p>Then the JavaScript code used to generate the HTML looks like so:</p><pre>cards.forEach((c) =&gt; {<br>  let icons = &quot;&quot;<br>  if(c[&#39;type&#39;] == &quot;structure&quot;) {<br>        icons += `&lt;img class=&quot;structure-icon-1&quot; src=&quot;icons/structure.svg&quot; /&gt;<br>                  &lt;img class=&quot;structure-icon-2&quot; src=&quot;icons/structure.svg&quot; /&gt;`<br>  }<br>  if(c[&#39;victory_points&#39;] != undefined) {<br>    icons += `&lt;span class=&quot;hook&quot;&gt;${c[&#39;victory&#39;]}&lt;/span&gt;<br>              &lt;img class=&quot;hook-icon&quot; src=&quot;icons/hook.svg&quot; /&gt;`<br>  }<br>  if(c[&#39;cost&#39;] != undefined) {<br>    icons += `&lt;span class=&quot;cost&quot;&gt;${c[&#39;cost&#39;]}&lt;/span&gt;<br>              &lt;img class=&quot;cost-icon&quot; src=&quot;icons/chest.svg&quot; /&gt;`<br>  }<br>  // some more conditionals<br>  var template = `&lt;div class=&quot;card&quot; id=&quot;card-${j}&quot; title=&quot;${c[&#39;title&#39;]}&quot;&gt;<br>      &lt;div class=&quot;inner&quot;&gt;<br>          &lt;div class=&quot;front type-${c[&#39;type&#39;]}&quot;&gt; <br>              &lt;div class=&quot;frame&quot;&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;<br>              &lt;img src=&quot;${c[&#39;img&#39;]}&quot; class=&quot;bg&quot; /&gt;<br>              &lt;span class=&quot;title&quot;&gt;${c[&#39;title&#39;]}&lt;/span&gt;<br>              &lt;span class=&quot;text&quot;&gt;${c[&#39;text&#39;]}&lt;/span&gt;<br>              ${icons}<br>          &lt;/div&gt;<br>      &lt;/div&gt;<br>  &lt;/div&gt;`<br><br>  // add card to the page<br>}</pre><p>You’ve grasped the concept, so I’ll spare you the remaining details. However, for those interested in utilising the source code for their own projects, I’ll provide a link to access it.</p><h4>Rendering the HTML to images</h4><p>In order to print the cards, high-quality, high DPI images are required. But how can one achieve this using web technologies? While one option is to <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/zoom">zoom</a> the design to desired pixel size and take screenshots, this approach is laborious and yield imprecise results. To tackle this challenge, I used <a href="https://cburgmer.github.io/rasterizeHTML.js/">rasterizeHTML</a>, a tool that enables the transformation of a webpage element into an image.</p><h3>Play testing</h3><p>The quality of a game is primarily determined by the fun it offers rather than its appearance. Therefor, extensive play testing is crucial to ensure enjoyable and balanced cards, as well as coherent interactions. Adopting an iterative approach, I initially introduced simple cards to the deck, stabilising and refining them before gradually incorporating new, more complex cards.</p><p>The first version was designed be play tested using a standard 52-card deck. Each card number was associated with a specific design, and players would refer to a computer screen for gameplay guidance. While this approach initially facilitated quick iteration and immediate design adjustments between games, it eventually proved to be overly confusing and lacking the necessary flexibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dHsOBXa02rHY0mQJClPgg.png" /><figcaption>A few cards, with reference number.</figcaption></figure><h4>Printing the first prototype</h4><p><a href="https://www.makeplayingcards.com/">MakePlayingCards</a> is an good choice for printing prototypes, offering a range of options. However, I also wanted to explore European printers and decided to give <a href="https://www.mbprint.pl/en/home/">MB Print</a> a try. Both providers delivered high-quality prints, but MPC stands out due to its extensive range of offerings. For instance, MPC can print custom tuck boxes and booklets, providing a neat packaged solution when shipping the game.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNheWub_03sM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNheWub_03sM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNheWub_03sM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd1b9b08b6418c93210ad6d92629e3a8/href">https://medium.com/media/dd1b9b08b6418c93210ad6d92629e3a8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjOtN75GaP6o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjOtN75GaP6o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjOtN75GaP6o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f4f9b9b17128133388cc3cb13162ccb/href">https://medium.com/media/7f4f9b9b17128133388cc3cb13162ccb/href</a></iframe><h4>Getting the rules down</h4><p>After conducting additional play testing, the rules for <a href="https://bit.ly/dk-h">DeckHand</a> were largely finalized. However, upon sharing the rule book with the Reddit community <a href="https://www.reddit.com/r/tabletopgamedesign/comments/14i0hng/deckhand_a_pirate_card_game_looking_for_any/">/r/tabletopgamedesign</a> I received valuable suggestions that I incorporated to clarify the end-game conditions.</p><p>The rules for the game are managed within the HTML page, similar to the rest of the cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2O5cU6f2Aanln1F0Gj6evA.png" /><figcaption>DeckHand Rule booklet.</figcaption></figure><h4>Some more play testing</h4><p>Moving forward with players, we found that printing updated designs and inserting them into plastic sleeves in front of the original cards was the most effective and economical way to modify the game.</p><p>While this method allowed us to seamlessly introduce minor adjustments by using pieces of paper or crossing out words as needed, the design choice of white text on a dark background posed challenges when attempting to make additions with a pen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcF_Qv6GqgAVA0aMzCjZTg.png" /><figcaption>Play testing with a print sheet and sleeves.</figcaption></figure><h4>Packaging: Tuck Box</h4><p>I also required a design for the box housing the cards and rule booklet. For this task, I used <a href="https://www.photopea.com/">Photopea</a>, an impressive and free online photo editor developed by by Ivan Kutskir. I can’t recommend it enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpqhYSvuSh2t6VV3zhWj-A.jpeg" /><figcaption><a href="https://bit.ly/dk-h">DeckHand</a> tuck box design</figcaption></figure><p>This package includes a set of cards, a booklet, and a visually appealing box with a pirate theme. Everything is neatly wrapped and ready to be enjoyed for gameplay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skK4UsBF3cNBZVzbrqJ-8Q.jpeg" /><figcaption>The second prototype, with Tuck Box and Rule booklet</figcaption></figure><h4>Card Illustrations</h4><p>One of the challenges faced with the full art design is that the bottom part of the image is partially obscured, necessitating a composition that prioritises the top portion of the artwork. If you’re interested in seeing more, I have shared some <a href="https://www.deviantart.com/faden1/gallery">illustrations</a> here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wf4TFtv6gf3XFazyZ1oyg.png" /><figcaption>Going Ape and Walk the Plank Card illustrations.</figcaption></figure><h4>The Game itself</h4><p>With just a few minor adjustments and some final play testing, DeckHand is nearing completion. It provides engaging sessions that typically span 25 to 30 minutes for two players. Prepare to construct an exciting deck, but beware of the possibility that your opponent may outpace you by a significant margin, or luck may simply not be in your favour today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TVYMCimWUPPp2GogF47mQ.png" /><figcaption>A few card designs highlighting some mechanics of DeckHand.</figcaption></figure><p>Its compact size and straightforward rules is perfect for casual gaming occasions. If you you wish to express your interest in obtaining a print sheet or purchasing a copy, simply fill out the <a href="https://batiste.github.io/deckhand/">the single field form</a>. This commitment-free action will assist me in determining the print run size.</p><p>In any case, I had an absolute blast creating this game, and it has the potential to become my new favorite hobby.</p><h4>A New Game on the Horizon</h4><p>Quick interjection ; I’m working on a new game! This time, I’ve teamed up with some incredibly talented illustrators. The game is called <a href="https://tidale.org/deckhand-race-for-infamy/"><strong>DeckHand: Race for Infamy!</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZezYDExhvOqC4uLgN6URQ.jpeg" /></figure><h4>Design reflexions and discoveries</h4><p>Allow me to delve into some design peculiarities that make DeckHand a unique experience:</p><ol><li>While players can attempt to keep tabs on victory points, the true winner often emerges unexpectedly, adding an element of intrigue to each game.</li><li>With diversity in card selection and light player interactions, DeckHand offers a dynamic environment, enticing players to come back for more.</li><li>DeckHand embraces luck, making it a casual and enjoyable experience for all.</li><li>DeckHand is in spirit a bit of a <a href="https://mtg.fandom.com/wiki/Cube_Draft">Cube Draft</a> experience. However, its compact size, approachability, and simpler mechanics make it manageable for those new to the genre.</li><li>The end game might lack some variety as the main focus revolves around acquiring cards for victory points, even though they might not see play — an issue common in many deck builder formats.</li></ol><h3>The Card Game Creator</h3><p>As promised, here is the code that I believe you will find valuable. Let it be your next card game skeleton:</p><p><a href="https://github.com/batiste/card-game-creation-template">GitHub - batiste/card-game-creation-template: A template for creating game extracted from the game DeckHand</a></p><p>If you want to see a running version first: <a href="https://batiste.github.io/card-game-creation-template">Card Game Creation Template</a></p><p>If you are interested and wish to know more: <br><a href="https://batiste.github.io/deckhand/"><strong>DeckHand — A Pirate Deck Builder Game</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f610a1fcc71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed up you Github Actions by caching you Python packages install]]></title>
            <link>https://towardsdev.com/speed-up-you-github-actions-by-caching-you-python-packages-install-31127de213ae?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/31127de213ae</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 07:28:52 GMT</pubDate>
            <atom:updated>2025-09-19T15:05:32.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw_1JyZt9mOiyNjvFBV13w.png" /><figcaption>Uncached run</figcaption></figure><p>Installing python packages on every CI run can be adding precious seconds before you can get a feedback. For my current project it was up to a minute. <a href="https://github.com/actions/cache">Github cache action</a> can help us here.</p><p>My setup uses <a href="https://pipenv.pypa.io/en/latest/">pipenv</a>, but potentially a similar setup should work with pip, you just need to point to your pip install file.</p><pre>    - name: Cache pipenv<br>      uses: actions/cache@v3<br>      id: cache-pipenv<br>      with:<br>        path: ${{ env.pythonLocation }}<br>        key: ${{ runner.os }}-pip-${{ hashFiles(&#39;**/Pipfile.lock&#39;) }}<br>        restore-keys: |<br>          ${{ runner.os }}-pipenv<br>    - name: Install pipenv<br>      if: steps.cache-pipenv.outputs.cache-hit != &#39;true&#39;<br>      run: |<br>        python -m pip install --upgrade pipenv wheel<br>    - name: Install Dependencies<br>      if: steps.cache-pipenv.outputs.cache-hit != &#39;true&#39;<br>      run: |<br>        pipenv install --system --deploy --dev</pre><p>If everything works as intended, and once the cache is filled you should be able save some precious second, and github action credits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*ondlxDOitSbMetCFfsj6MQ.png" /><figcaption>Cache is hot, it is a hit</figcaption></figure><p>And voilà, you saved a minute on each build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31127de213ae" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/speed-up-you-github-actions-by-caching-you-python-packages-install-31127de213ae">Speed up you Github Actions by caching you Python packages install</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST Framework Translated Serializer Field]]></title>
            <link>https://towardsdev.com/django-rest-framework-translated-serializer-field-2e77821efd8c?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e77821efd8c</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 08:03:13 GMT</pubDate>
            <atom:updated>2023-05-04T13:08:49.842Z</atom:updated>
            <content:encoded><![CDATA[<p>There is many ways to handle i18n with Django and DRF. This document describe a small ad-hoc solution using <a href="https://www.django-rest-framework.org/api-guide/serializers/#serializers">DRF serializers</a> and a naively translated Django model to provide a seamless experience to the API user based on its language preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlv3Z61lGXew-7R0GXwpow.png" /><figcaption>Django Rest Framework documentation on <a href="https://www.django-rest-framework.org/api-guide/serializers/#advanced-serializer-usage">Advanced serializer usage</a></figcaption></figure><p>Lets consider you have this artificial Product model</p><pre># project/models.py<br>from django.db import models<br><br>class Product(models.Model):<br><br>    name_en = models.CharField(max_length=255, null=True, blank=True)<br>    name_de = models.CharField(max_length=255, null=True, blank=True)<br>    name_fr = models.CharField(max_length=255, null=True, blank=True)<br><br>    description_en = models.TextField(null=True, blank=True)<br>    description_de = models.TextField(null=True, blank=True)<br>    description_fr = models.TextField(null=True, blank=True)<br><br>    created_at = models.DateTimeField(auto_now_add=True)</pre><p>How to you represent this Product to the end user in the right language using Django Rest Framework? Is it possible to only show the desired language so the frontend does not have to do extra work?</p><p>The first problem you usually come across with DRF is that you do not have access to the request object in a serializer so doing something different based on user language can be difficult (<a href="https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context">but not impossible</a>). To step over this first issue I decided to store the user’s language in a ContextVar. <a href="https://medium.com/@batiste/django-celery-sentry-json-logging-meta-data-adfdf616c57c">Here is how you can do it</a> fully explained. Here is a condensed version of it that just adds the language:</p><pre># project/request_context.py<br>from contextvars import ContextVar<br>from django.http import HttpRequest<br><br># our request context variable<br>request_context = ContextVar(<br>    &quot;request_context&quot;, default=None<br>)<br><br>class RequestContextMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request: HttpRequest):<br>        user = request.user<br>        # the way the language is determined could differ<br>        # depending on your project.<br>        context = {<br>            &quot;language&quot;: user and not user.is_anonymous and user.language,<br>        }<br>        request_context.set(context)<br>        response = self.get_response(request)<br>        request_context.set(None)<br>        return response <br><br>def get_language():<br>    if rc := request_context.get():<br>        return rc.get(&quot;language&quot;) or &quot;en&quot;<br>    return &quot;en&quot;</pre><p>Considering your have that middleware setup that saves the user’s language, here is how you can exploit it you your DRF serializers by <a href="https://www.django-rest-framework.org/api-guide/fields/#custom-fields">creating a custom field</a></p><pre># project/fields.py<br><br>from rest_framework import serializers<br>from project.request_context import get_language<br><br><br>class TranslatedSerializerField(serializers.Field):<br>    def to_representation(self, value):<br>        return getattr(value, f&quot;{self.field_name}_{get_language()}&quot;, &quot;&quot;)<br><br>    def to_internal_value(self, data):<br>        return {f&quot;{self.field_name}_{get_language()}&quot;: data}</pre><p>Then you can use it this way in your serializer. Note that it is important to pass the <strong>source=”*” </strong>parameter to give the TranslatedSerializerField access to the whole model:</p><pre># project/serializers.py<br>from rest_framework import serializers<br>from project.fields import TranslatedSerializerField<br>from project.models import Product<br><br><br>class ProductSerializer(serializers.ModelSerializer):<br><br>    name = TranslatedSerializerField(source=&quot;*&quot;)<br>    description = TranslatedSerializerField(source=&quot;*&quot;)<br><br>    class Meta:<br>        model = Product<br>        fields = [&quot;name&quot;, &quot;description&quot;]</pre><p>You should now be able to read and update the meta-field <strong>name</strong> and <strong>description</strong> and the expected database fields should be used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e77821efd8c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/django-rest-framework-translated-serializer-field-2e77821efd8c">Django REST Framework Translated Serializer Field</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Rest Framework authentication and Django Middleware: Why request.user is anonymous?]]></title>
            <link>https://towardsdev.com/django-rest-framework-authentication-and-django-middleware-why-request-user-is-anonymous-d9d62bddf4f6?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9d62bddf4f6</guid>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 14:56:30 GMT</pubDate>
            <atom:updated>2023-06-16T10:48:07.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlDlsoOK-j2GXFpzMC6QJQ.png" /></figure><p>When using DRF and in in the context of Django middleware I have often found to be the case that <strong>request.user</strong> is an <strong>AnonymousUser</strong>. Why is that?</p><p>It is because the DRF <a href="https://www.django-rest-framework.org/api-guide/settings/#default_authentication_classes">authentication classes</a> are executed after all the normal Django middleware are already in their <strong>get_response </strong>stage.</p><pre>class DjangoMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        # request.user is AnonymousUser<br>        # this will eventually call DRF<br>        response = get_response(request)<br>        # request.user should be defined at this point<br>        return response</pre><p>If you want to <a href="https://batiste.medium.com/django-celery-sentry-json-logging-meta-data-adfdf616c57c">setup a logger enriched with user meta data</a> it doesn’t not make sense to wait for the response from DRF to setup things properly… So what can you do to fix that?</p><p>A simple way to hook into DRF auth system is to subclass the authentication mechanism that you use. For example let’s say you are using <a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">Django REST Framework Simple JWT plugin</a> you can subclass it this way:</p><pre># project/jwt_auth.py<br><br>from rest_framework_simplejwt.authentication import JWTAuthentication<br># request_context is a ContextVar we use to share state<br>from project.request_context import request_context<br>import sentry_sdk<br><br>class JWTAuthenticationWithSidEffects(JWTAuthentication):<br>    &quot;&quot;&quot;<br>    DRF does its own authentication that happens after Django middleware<br>    https://stackoverflow.com/a/53198640<br>    &quot;&quot;&quot;<br><br>    def authenticate(self, request):<br>        user_auth_tuple = super().authenticate(request)<br><br>        if user_auth_tuple is None:<br>            return<br>        (user, token) = user_auth_tuple<br><br>        # Then you can do what need to do with the user here<br>        context = request_context.get()<br>        context[&quot;user_id&quot;] = user and user.id<br>        context[&quot;language&quot;] = user and not user.is_anonymous and user.language<br>        request_context.set(context)<br>        sentry_sdk.set_context(&quot;request&quot;, context)<br><br>        return (user, token)</pre><p>Then substitute the old authentication class with your own</p><pre>REST_FRAMEWORK = {<br>    &quot;COERCE_DECIMAL_TO_STRING&quot;: False,<br>    &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: [<br>-        &quot;rest_framework_simplejwt.authentication.JWTAuthentication&quot;,<br>+        &quot;project.jwt_auth.JWTAuthenticationWithSidEffects&quot;,<br>    ]<br>}</pre><p>You should now be able to use the request_context <a href="https://docs.python.org/3/library/contextvars.html">ContextVar</a> within DRF. For example you could use it in <a href="https://batiste.medium.com/django-celery-sentry-json-logging-meta-data-adfdf616c57c">a special logger</a> or have a <a href="https://www.django-rest-framework.org/api-guide/serializers/">DRF Serializer</a> that takes advantages of the user language to return a specific translations. Here is an example on how to use it:</p><pre>from django.db import models<br>from rest_framework import serializers<br>from project.request_context import request_context<br><br>class DogBreed(models.Model):<br>    name_fr = models.CharField(max_length=255)<br>    name_de = models.CharField(max_length=255)<br>    name_en = models.CharField(max_length=255)<br><br>class DogBreedSerializer(serializers.ModelSerializer):<br>    name = serializers.SerializerMethodField()<br><br>    def get_name(self, instance):<br>        if rc := request_context.get():<br>            lang = rc.get(&quot;language&quot;) or &quot;en&quot;<br>        else:<br>            lang = &quot;en&quot;<br>        return getattr(instance, f&quot;name_{lang}&quot;)<br><br>    class Meta:<br>        model = DogBreed<br>        fields = [&quot;name&quot;]</pre><p>And voilà! that should work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9d62bddf4f6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/django-rest-framework-authentication-and-django-middleware-why-request-user-is-anonymous-d9d62bddf4f6">Django Rest Framework authentication and Django Middleware: Why request.user is anonymous?</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Blop language and a parser generator]]></title>
            <link>https://towardsdev.com/the-blop-language-and-a-parser-generator-124e613ef4f1?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/124e613ef4f1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 11:57:50 GMT</pubDate>
            <atom:updated>2023-03-24T16:06:16.469Z</atom:updated>
            <content:encoded><![CDATA[<p>After years of experimenting around on how to write an efficient compiler in JavaScript, I decided to test <a href="https://github.com/batiste/meta-parser-generator">my latest creation</a> by creating a language that can be used for something in the real world: a language for the web.</p><p>My contempt for Angular’s dependency injection and React’s Redux boilerplate inspired the design of this web oriented language called Blop.</p><h3>The compiler</h3><p>Blop uses an infrastructure similar to LEX and YACC. The piece of code that generate a parser is called the <a href="https://github.com/batiste/meta-parser-generator">Meta Parser Generator</a>. It works with a list of regular expressions, string or function that <a href="https://github.com/batiste/blop-language/blob/master/src/tokensDefinition.js">separate the input Blop language into lexeme</a>. This lexeme list is then passed to <a href="https://github.com/batiste/blop-language/blob/master/src/parser.js">a left-to-right parser</a> generated using <a href="https://github.com/batiste/blop-language/blob/master/src/grammar.js">a grammar definition</a>. The output of this parser once executed is an <a href="https://github.com/batiste/meta-parser-generator#ast-interface">Abstract Syntax Tree</a>.</p><p>Then this tree is passed to <a href="https://github.com/batiste/blop-language/blob/master/src/backend.js">the backend</a> to generates the output JavaScript code, source maps, and checks some rules like variable shadowing. This backend is both a linter and code generator.</p><p>There is nothing particularly clever of special about the Blop infrastructure and I think that is a good thing. If anything I hope it is a interesting example on how to implement a language from scratch with little dependencies using JavaScript.</p><h3>Why another language?</h3><p>I can hear you raging in front of your screen… Dead on arrival web language number 1458… Who needs this?</p><p>But bare with me, I don’t expect anybody to use this language for anything real. I just want to share a learning experience and a couple of ideas.</p><p>Let’s dive into a simple example that illustrate some basic things you can do with Blop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWeQDVCqL00cCo81b0SCYw.png" /><figcaption>An example of a couple of 2 Blop <a href="https://github.com/batiste/blop-language/wiki/Components">components</a></figcaption></figure><p>The Blop language does look like React’s JSX. but you might have detected something special in this example if you are familiar with JSX: There is an <strong>if statement</strong> right in the middle of the HTML.</p><p>This is possible because The HTML-like you see in the example are actually statements in Blop and not expressions. You can mix them with <strong>if-else</strong> and <strong>for loop</strong> statements or any other language feature without restrictions. Blop will know what is the parent of the current HTML node. Pretty much anything you can do with ES6 you can do with Blop plus the HTML expression/statements.</p><p>For comparaison this is one way you could write LoginForm in JSX</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS3MK2hRHgzf25ZYJJ33bg.png" /><figcaption>The login form in idiomatic JSX</figcaption></figure><p>This difference is not huge, but is a consequence of the fact that the JSX DSL only deal with expressions. React Developers often to try circumvent this limitation by using ternary conditional operators and functional chaining.</p><h3>Multi level conditional rendering</h3><p>This is a real life example I got using the example <a href="https://petstore.swagger.io/">Pet store API</a> of swagger. Iterating over a list of pets with a couple of conditional rendering paths.</p><p>In Blop the control flow can be dealt in a completely imperative way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*oKWa2inbJSLV96Md-Z336Q.png" /><figcaption>A list of pets name, with an optional image</figcaption></figure><p>I believe it is straightforward to read and understand, even without having seen any Blop code before.</p><p>Let’s now compare it with one of the ways you could do it with JSX. I did use a conditional ternary operators and tried to make it as readable as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0Ev7Z1rMhabyurkiplqPQ.png" /><figcaption>In JSX, we use map and a ternary operator</figcaption></figure><p>It is a little more verbose, a little more complicated to read, and a little more complicated to write as you have to deal with closing brackets of different sorts. And it is definitely not idiomatic javascript as ternary operators are usually frowned upon.</p><p>As <a href="https://github.com/batiste/blop-language/wiki/Components">Components</a> are simple functions in Blop you could easily split this nested code into into 2. It is quite straightforward with Blop and would look like something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*idepyFsiyxiqdmEDlBuHXQ.png" /><figcaption>Splitting things into different components</figcaption></figure><h3>What do you get out of the box</h3><p>Blop is very bare but it does comes with most fundamental tools that people expects:</p><p>2 essential Visual Studio Code extensions: <a href="https://marketplace.visualstudio.com/items?itemName=batistebieler.blop-linter">a picky linter</a>, and <a href="https://marketplace.visualstudio.com/items?itemName=batistebieler.blop">a syntax highlighter</a>.</p><p>2 basic independent example small utility libraries written in Blop, <a href="https://github.com/batiste/blop-example-project/blob/master/src/lib/router.blop">one for routing</a>, the other for <a href="https://github.com/batiste/blop-example-project/blob/master/src/lib/state.blop">state management</a> using the Proxy API.</p><p><a href="https://github.com/batiste/blop-example-project">An example application</a> setup with <a href="https://webpack.js.org/">Webpack</a>, <a href="https://jestjs.io/">Jest</a> and an express server with <a href="https://github.com/batiste/blop-example-project/blob/master/src/server.blop">Server Side Rendering</a> ready, if you like those kind of things.</p><p><a href="https://github.com/batiste/blop-language/wiki/Components">A component system</a> with <a href="https://github.com/batiste/blop-language/wiki/Components#component-lifecycle">lifecycle hooks</a>, <a href="https://github.com/batiste/blop-language/wiki/Components#component-state">a state system</a>, and <a href="https://github.com/batiste/blop-language/wiki/Components#component-context">a context system</a>, with partial re-rendering built-in.</p><p>Blop also has a basic type inference engine, but it is nothing more than a toy at this point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*IUx_g_7xbKfofdvWYcjZLg.png" /><figcaption>It can prevent very basic mistakes</figcaption></figure><h3>Can I use it today?</h3><p>For sure but be aware it is an experimental project and there is no community. Expect very little support.</p><p>TypeScript is also way too good to pass up these days. The language and its inference engine are amazing tools. Blop could never compete! I checked if I could somehow add Blop syntax to TypeScript as a plugin à la JSX but this seems almost an impossibly complicated job to accomplish as a hobby.</p><p>Would you hire me to do it? I would be delighted :-)</p><p>If you are curious you can test a couple of simple Blop pages <a href="https://batiste.github.io/blop/example/">running in your browser here</a>.</p><p>Use it for fun, but don’t use it in production!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124e613ef4f1" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/the-blop-language-and-a-parser-generator-124e613ef4f1">The Blop language and a parser generator</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging a Python project with VSCode and Docker]]></title>
            <link>https://towardsdev.com/debugging-a-python-project-with-vscode-and-docker-9c33670cac0?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c33670cac0</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 10:22:59 GMT</pubDate>
            <atom:updated>2023-06-16T10:47:59.647Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide explains how to setup a Django project and Docker together for debugging sessions within VSCode. We will follow the steps <a href="https://code.visualstudio.com/docs/containers/docker-compose#_python">detailed here</a>. The specifics in this document are about Django but it should work all the the same for <a href="https://fastapi.tiangolo.com/">FastAPI</a> or any dockerized Python code.</p><p>Given that you have your Django services setup like so:</p><pre>version: &#39;3&#39;<br><br>services:<br>  api: &amp;api-def<br>    build:<br>      dockerfile: ./Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - .:/app<br>    command: python manage.py runserver 0.0.0.0:8000<br>    depends_on:<br>      - db<br>    environment:<br>      - DATABASE_URL=postgres://user@password/api<br>      - DJANGO_SETTINGS_MODULE=api.settings<br><br>  db:<br>    image: postgres:12.0-alpine<br>    environment:<br>      - POSTGRES_DB=api<br>      - POSTGRES_NAME=postgres<br>      - POSTGRES_USER=user<br>      - POSTGRES_PASSWORD=password<br>    ports:<br>      - &quot;5432:5432&quot;</pre><p>We will use the <a href="https://microsoft.github.io/debug-adapter-protocol/">Debug Adapter Protocol</a> of VSCode to communicates with a debugging server that runs in Docker. For that purpose Microsoft offers an easy to use debugging server for Python called <a href="https://github.com/microsoft/debugpy">debugpy</a>. You can install it in your dependencies or simply add it at every start debugging session. I chose the second option and added this to my <strong>docker-compose.yaml</strong></p><pre>  debug:<br>    &lt;&lt; : *api-def<br>    command: [&quot;sh&quot;, &quot;-c&quot;, &quot;pip install debugpy -t /tmp &amp;&amp; python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 manage.py runserver 0.0.0.0:8000 --nothreading --noreload&quot;]<br>    ports:<br>      - 8000:8000<br>      - 5678:5678</pre><p>You can now start your application with this debugging server attached:</p><pre>docker compose up debug</pre><p>Then configure VSCode to use this server. Create a <strong>.vscode/launch.json </strong>file in your project containing something like this:</p><pre>{<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Remote debug&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;attach&quot;,<br>            &quot;port&quot;: 5678,<br>            &quot;host&quot;: &quot;localhost&quot;,<br>            &quot;pathMappings&quot;: [<br>                {<br>                    &quot;localRoot&quot;: &quot;${workspaceFolder}&quot;,<br>                    &quot;remoteRoot&quot;: &quot;/app&quot;<br>                }<br>            ]<br>        }<br>    ]<br>}</pre><p>Once done you should see a new action in your Run and Debug tab (⇧⌘D)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*OWeydxUMZrw2Up_g4JAM-g.png" /><figcaption>Run and Debug — Remote debug</figcaption></figure><p>Then add some breakpoints where you want to stop and hit this code path and should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0HQPKy0-Uj6Pf8WaThJ2g.png" /><figcaption>Debugging session with a breakpoint</figcaption></figure><p>Nice that works! That was quite easy wasn’t it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c33670cac0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/debugging-a-python-project-with-vscode-and-docker-9c33670cac0">Debugging a Python project with VSCode and Docker</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django + Celery + Sentry + JSON Logging meta data]]></title>
            <link>https://towardsdev.com/django-celery-sentry-json-logging-meta-data-adfdf616c57c?source=rss-686771c38c8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/adfdf616c57c</guid>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Batiste]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 16:44:25 GMT</pubDate>
            <atom:updated>2023-04-28T14:42:37.480Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with a Python service it can be daunting to make all those tools work together and output useful logs with proper meta data.</p><p>This document is a step by step setup guide for Django. But is can be also applied to <a href="https://fastapi.tiangolo.com/">FastAPI</a> or <a href="https://flask.palletsprojects.com/en/2.2.x/">flask</a> with minimal changes.</p><p>First we want to gather the meta-data for our logs. We will need a <a href="https://docs.djangoproject.com/en/4.1/topics/http/middleware/#writing-your-own-middleware">middleware</a> that will store the request informations in a <a href="https://docs.python.org/3/library/contextvars.html">ContextVar</a>. This part is really the only part that is Django specific and that should be adapted.</p><pre># project/request_context.py<br>import uuid<br>from contextvars import ContextVar<br><br>import sentry_sdk<br><br># our request context variable<br>request_context = ContextVar(&quot;request_context&quot;, default=None)<br><br><br>class RequestContextMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        # we collect various information that we want to see in our logs<br>        context = {<br>            &quot;user_id&quot;: request.user and request.user.id,<br>            &quot;correlation_id&quot;: str(<br>                request.headers.get(&quot;X-Request-Id&quot;, uuid.uuid4())<br>            ),<br>            &quot;path&quot;: request.path,<br>        }<br>        # we save this information for later use<br>        request_context.set(context)<br>        # we can instruct sentry to include this information as well<br>        sentry_sdk.set_context(&quot;request&quot;, context)<br><br>        response = self.get_response(request)<br><br>        # not strictly necessary but a good idea<br>        request_context.set(None)<br>        return response</pre><p>Now add this new middleware to your Django application</p><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.middleware.common.CommonMiddleware&#39;,<br>    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,<br>    # Add your middleware here<br>    &quot;project.request_context.RequestContextMiddleware&quot;,<br>]</pre><p>For now not much will happen as you do not use this request context variable, but you should already see the effect of <strong>sentry_sdk.set_context</strong> in Sentry</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vaS_PWyGbKVleza7xPBVA.png" /><figcaption>Sentry set_context effect</figcaption></figure><p>Now let’s try to inject this meta data into your service logs so they can be exploited by logging tool such as <a href="https://cloud.google.com/logging/docs/">Google Cloud Logging</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akTZ9M7dhFQkGNUFBbajjw.png" /></figure><p>For that we need a new logging JSON formatter, to this effect let’s use the library <a href="https://pypi.org/project/python-json-logger/">python-json-logger</a> and subclass it:</p><pre># project/logger.py<br>from pythonjsonlogger import jsonlogger<br>from project.request_context import request_context<br><br>class CustomJsonFormatter(jsonlogger.JsonFormatter):<br>    def add_fields(self, log_record, record, message_dict):<br>        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)<br>        if rc := request_context.get():<br>            if uid := rc.get(&quot;user_id&quot;):<br>                log_record[&quot;user_id&quot;] = uid<br>            if cid := rc.get(&quot;correlation_id&quot;):<br>                log_record[&quot;correlation_id&quot;] = cid<br>            if path:= rc.get(&quot;path&quot;):<br>                log_record[&quot;path&quot;] = path<br><br>        if log_record.get(&quot;level&quot;):<br>            log_record[&quot;severity&quot;] = log_record[&quot;level&quot;].upper()<br>        else:<br>            log_record[&quot;severity&quot;] = record.levelname</pre><p>And let’s activate this new JSON formatter by changing our <strong>settings.py</strong></p><pre>LOGGING = {<br>    &quot;version&quot;: 1,<br>    &quot;disable_existing_loggers&quot;: False,<br>    &quot;formatters&quot;: {<br>        &quot;json&quot;: {<br>            &quot;()&quot;: &quot;project.logger.CustomJsonFormatter&quot;,<br>            &quot;format&quot;: &quot;%(asctime)s %(name)s:%(lineno)d %(module)s %(message)s&quot;,<br>        },<br>    },<br>    &quot;handlers&quot;: {<br>        &quot;console&quot;: {<br>            &quot;level&quot;: &quot;DEBUG&quot;,<br>            &quot;class&quot;: &quot;logging.StreamHandler&quot;,<br>            &quot;formatter&quot;: &quot;json&quot;,<br>        }<br>    },<br>    &#39;loggers&#39;: {<br>         &#39;django&#39;: { # to avoid duplicated django logs<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;INFO&#39;,<br>            &#39;propagate&#39;: False,<br>         },<br>    },<br>    &quot;root&quot;: {&quot;level&quot;: &quot;INFO&quot;, &quot;handlers&quot;: [&quot;console&quot;]},<br>}</pre><p>Now <strong>logging.info(“My message”)</strong> will yield a JSON formatted log that contain a <strong>correlation_id, </strong>a <strong>user_id</strong> and a <strong>path</strong> if available. It should look like this:</p><pre>{<br>  &quot;path&quot;: &quot;/api/v1/billing/test-task/&quot;,<br>  &quot;user_id&quot;: 56, <br>  &quot;correlation_id&quot;: &quot;ad78cc7d-7ea6-4699-b215-34393734cd54&quot;,<br>  &quot;name&quot;: &quot;root&quot;,<br>  &quot;module&quot;: &quot;request_context&quot;,<br>  &quot;message&quot;: &quot;My message&quot;,<br>  &quot;severity&quot;: &quot;INFO&quot;<br>}</pre><p>Once those changes are deployed you can now filter your logs like so (Goggle Cloud Logging syntax):</p><pre>jsonPayload.path=&quot;/api/v1/billing/test-task/&quot; OR jsonPayload.user_id=&quot;56&quot;</pre><p>If you do not know how to setup Google Cloud Logging with JSON parsing, here is my solution after I setup the <a href="https://cloud.google.com/stackdriver/docs/solutions/agents/ops-agent/configuration">Ops Agent configuration</a>. If you use Kubernetes logging setup might differ.</p><pre># /etc/google-cloud-ops-agent/config.yaml<br># See https://cloud.google.com/stackdriver/docs/solutions/agents/ops-agent/configuration<br># for more details.<br><br>logging:<br>  receivers:<br>    syslog:<br>      type: files<br>      include_paths: # &lt;- this might depend on your config/needs<br>      - /var/log/messages<br>      - /var/log/syslog<br>      - /var/log/celery/worker.log<br>      - /var/log/asgi.log<br>  processors:<br>    json_parser:<br>      type: parse_json<br>      time_key: asctime<br>      time_format: %Y-%m-%d %H:%M:%S<br>    move_severity:<br>      type: modify_fields<br>      fields:<br>        jsonPayload.&quot;logging.googleapis.com/severity&quot;:<br>          move_from: jsonPayload.severity<br>  service:<br>    pipelines:<br>      default_pipeline:<br>        receivers: [syslog]<br>        processors: [json_parser, move_severity]<br>metrics:<br>  receivers:<br>    hostmetrics:<br>      type: hostmetrics<br>      collection_interval: 30s<br>  processors:<br>    metrics_filter:<br>      type: exclude_metrics<br>      metrics_pattern: []<br>  service:<br>    pipelines:<br>      default_pipeline:<br>        receivers: [hostmetrics]<br>        processors: [metrics_filter]</pre><p>Great! It is already a big step in the right direction. But there is something missing: <strong>Celery</strong> logs will not work. The logs will not look like JSON and the meta-data will not be automatically propagated. No problems there is a way to fix both things with little code. In your Celery setup add something like this:</p><pre># project/celery.py<br>from django.conf import settings<br>from logging.config import dictConfig<br>from project.request_context import request_context<br>from celery.signals import after_setup_task_logger, before_task_publish, task_prerun<br><br># forces celery to format logs like we want them<br>@after_setup_task_logger.connect<br>def setup_task_logger(logger, *args, **kwargs):<br>    dictConfig(settings.LOGGING)<br><br># inject the request context in the header of the task<br>@before_task_publish.connect<br>def modify_header(body, headers, **kwargs):<br>    if headers:<br>        rc = request_context.get()<br>        if rc:<br>            headers[&quot;request_context&quot;] = rc<br><br># on the Celery side reestablish the information before starting the task<br>@task_prerun.connect<br>def reestablish_request_context(task_id, task, *args, **kwargs):<br>    rc = task.request.get(&quot;request_context&quot;, None)<br>    if rc:<br>        request_context.set(rc)<br>        sentry_sdk.set_context(&quot;request&quot;, rc)<br>    else:<br>        # better reset to avoid picking up any leftover context<br>        request_context.set(None)</pre><p>Now Celery should behave exactly the same way as your service. Logs and Sentry context should match. You can use the <strong>correlation_id </strong>to<strong> </strong>track<strong> </strong>all the logs produced by one request from your service and the Celery tasks. Or use the <strong>user_id </strong>instead<strong> </strong>if you want to follow what a client has done on multiple requests.</p><p>Be aware that the special <a href="https://docs.sentry.io/platforms/python/guides/django/">Sentry Django integration</a> will not work with Celery and this technic does not solve this. It is an alternative that always works and that can be easily adapted for other frameworks such as <a href="https://fastapi.tiangolo.com/">FastAPI</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adfdf616c57c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/django-celery-sentry-json-logging-meta-data-adfdf616c57c">Django + Celery + Sentry + JSON Logging meta data</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>