<?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 Lukas Klein on Medium]]></title>
        <description><![CDATA[Stories by Lukas Klein on Medium]]></description>
        <link>https://medium.com/@lukas.klein?source=rss-710c016aee89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bDvcBUVvkHJAVBlczivWsg.jpeg</url>
            <title>Stories by Lukas Klein on Medium</title>
            <link>https://medium.com/@lukas.klein?source=rss-710c016aee89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lukas.klein/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 to use a Telekom fiber connection directly with the Ubiquiti UDM Pro]]></title>
            <link>https://medium.com/@lukas.klein/how-to-use-a-telekom-fiber-connection-directly-with-the-ubiquiti-udm-pro-ea953ec55f06?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea953ec55f06</guid>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 12:18:58 GMT</pubDate>
            <atom:updated>2024-01-07T12:18:58.891Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently got a second fiber connection built to our house (the first is from Vodafone who somehow manage to send a DOCSIS cable signal via fiber), this time “real” fiber from Deutsche Telekom. They also sent me their own fiber router, which I would ideally not like to use, since I have a Ubiquiti UDM Pro anyways and would like to skip using another device just as a modem.<br>Since the UDM Pro has a WAN SFP port, I thought it cannot be that hard to use it directly with the new fiber connection. Turns out, it isn’t, once you know how to set it up.</p><p>Here’s what I did as a brief reference for anyone wanting to do this as well:</p><p>I got myself a <a href="https://amzn.to/3vsxFeh">ZYXEL SFP GPON module</a> as well as a <a href="https://amzn.to/3H7ub3g">LC/APC to SC/UPC fiber cable</a> to connect it. I installed it in my UDM Pro, used the Telekom-provided setup link to enter my modem ID (can be found on the Zyxel module) as well as the Telekom ID that’s written on the Telekom-installed fiber socket and shut the UDM Pro down, unplugged power for a bit (a regular reboot doesn’t power cycle the SFP module) and started the UDM pro again.</p><p>In the Unifi settings, I configured WAN1 to be port 10 (the SFP one) and changed the settings to manual. Here’s what I needed to change:</p><p>- Enable VLAN, set ID to 7<br>- set IPv4 Connection to PPPoE<br> — Your username is: ”Connection identifier (Anschlusskennung)”+”access number (formerly T-Online Number) (Zugangsnummer (vormals T-Online Nummer))”+”0001&quot;+”@t-online.de”, e.g. 001852485618413361714302#0001@t-online.de<br> — Your password is your personal password you should’ve received from Telekom<br>- I also set my DNS to be static servers (8.8.8.8 and 8.8.4.4 in my case), but that’s up to your preference</p><p>I then power-cycled everything and it was working perfectly out of the box.</p><p>I’m still trying to get IPv6 working and will update this post once I know more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea953ec55f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Datetime Edge Cases in Python: A Month Change Adventure]]></title>
            <link>https://medium.com/@lukas.klein/handling-datetime-edge-cases-in-python-a-month-change-adventure-260a559731c2?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/260a559731c2</guid>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 09:41:49 GMT</pubDate>
            <atom:updated>2023-04-03T09:41:49.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JUGgbaM2TQt9uer" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Working with dates and times in Python can be tricky, especially when dealing with month changes, varying month lengths, and leap years. In this blog post, we’ll explore a real-world issue that arose over the weekend when the month changed to April, and learn how to tackle it using the dateutil library.</p><h4>The Problem</h4><p>Consider the following Python code snippet:</p><pre>tz = pytz.timezone(&quot;Europe/Berlin&quot;)<br>requested_timezone_now = datetime.now(tz=tz)<br>start_of_month = requested_timezone_now.replace(microsecond=0, second=0, minute=0, hour=0, day=1).astimezone(pytz.utc)<br>start_of_last_month = start_of_month.replace(month=start_of_month.month - 1)</pre><p>The code is intended to calculate the start of the last month. However, it raises a ValueError: day is out of range for month. This error occurs because start_of_month is 2023-03-31 22:00:00 UTC, and subtracting one month results in 2023-02-31, which doesn&#39;t exist.</p><h4>Why start_of_month is 2023-03-31 22:00:00 UTC</h4><p>To understand why start_of_month is not the &quot;actual start of month&quot;, let&#39;s look at the code in detail. The start_of_month is calculated as follows:</p><ol><li>Obtain the current date and time in the Europe/Berlin timezone using datetime.now(tz=tz).</li><li>Set the day to 1, and reset the hour, minute, second, and microsecond components to 0.</li><li>Convert the resulting datetime object to UTC timezone using astimezone(pytz.utc).</li></ol><p>The reason start_of_month is 2023-03-31 22:00:00 UTC and not the actual start of the month is that we initially calculated the start of the month in the Europe/Berlin timezone (which is Central European Summer Time or CEST). When we normalized the datetime object to UTC, it effectively shifted the time backwards by 2 hours (CEST is UTC+2 during daylight saving time), landing us on the previous day, March 31st, at 22:00.</p><p>The Solution:</p><p>To fix the issue, we can use the dateutil library and its relativedelta function. This function takes care of months with different numbers of days and leap years. First, install the library if you haven&#39;t already:</p><pre>pip install python-dateutil</pre><p>Then, update your code as follows:</p><pre>from datetime import datetime<br>import pytz<br>from dateutil.relativedelta import relativedelta<br><br>tz = pytz.timezone(&quot;Europe/Berlin&quot;)<br>requested_timezone_now = datetime.now(tz=tz)<br>start_of_month = requested_timezone_now.replace(microsecond=0, second=0, minute=0, hour=0, day=1).astimezone(pytz.utc)<br>start_of_last_month = start_of_month - relativedelta(months=1)</pre><p>With this solution, start_of_last_month will correctly give you the start of the last month, taking into account months with different numbers of days and leap years.</p><h4>Conclusion</h4><p>When working with dates and times in Python, it’s essential to be aware of the potential edge cases that can arise due to month changes, varying month lengths, and leap years. Libraries like dateutil can help you handle these edge cases and avoid errors in your code. By understanding how timezones and datetime objects work together, you can ensure that your code produces the expected results in various scenarios.</p><p>In this blog post, we learned:</p><ol><li>How datetime objects can behave unexpectedly when dealing with month changes and different month lengths.</li><li>The importance of understanding how timezones affect datetime calculations.</li><li>How to use the dateutil library and its relativedelta function to handle month operations in Python more effectively.</li></ol><p>Remember that working with timezones can be challenging, and it’s essential to thoroughly test your code to ensure it behaves as expected across different timezones and during daylight saving time transitions. By being mindful of these potential pitfalls, you can write more reliable code and avoid surprises when dealing with datetime operations.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260a559731c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Flush to Firmware: The Rise of Connected Toilets]]></title>
            <link>https://medium.com/@lukas.klein/from-flush-to-firmware-the-rise-of-connected-toilets-9ff13e4e01bd?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff13e4e01bd</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[toilets]]></category>
            <category><![CDATA[midjourney]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 19:45:00 GMT</pubDate>
            <atom:updated>2023-03-29T19:45:13.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRLlv66p7IJsulXcNcoTZw.png" /><figcaption>We’re flushing outdated bathroom tech down the drain!</figcaption></figure><p>In today’s world, technology has permeated almost every aspect of our lives. From smartphones to smart homes, connected devices have made our lives easier and more convenient. One area where technology has made significant strides in recent years is in the bathroom. Connected toilets, also known as smart toilets, are changing the way we think about our bathrooms. In this article, we will explore the rise of connected toilets and how they are changing our bathrooms.</p><p>Connected toilets are toilets that are equipped with technology that allows them to connect to the internet or other devices in your home. They have sensors that can detect when you sit down or stand up, and they can adjust the water temperature, pressure, and angle of the spray accordingly. Some models even have built-in speakers, so you can listen to music or take phone calls while you’re on the toilet.</p><p>The Internet of Things (IoT) is a term used to describe the network of physical objects that are connected to the internet. The idea behind the IoT is to create a world where everything is interconnected and can communicate with each other. The concept of the IoT has been around since the early 2000s, but it wasn’t until the proliferation of smartphones and other mobile devices that it really took off.</p><p>Connected devices have become an integral part of our daily lives. From smart thermostats to voice assistants, we rely on technology to make our lives easier and more convenient. Connected toilets are no exception. They can help you save water, reduce your carbon footprint, and even improve your health.</p><h3>The Rise of Connected Toilets</h3><p>The IoT has entered the bathroom in the form of connected toilets. These toilets are equipped with sensors and other technology that allow them to connect to the internet or other devices in your home. They can also communicate with other smart home devices, such as your voice assistant or smart shower.</p><p>Connected toilets come with a range of features, including heated seats, bidet functionality, and automatic flushing. Some models even have built-in air dryers and deodorizers. They can be controlled via a remote or a smartphone app, allowing you to customize your bathroom experience.</p><p>Traditional toilets are simple and straightforward. They rely on gravity to flush waste down the drain, and they don’t have any special features or functionality. Connected toilets, on the other hand, are equipped with technology that allows them to be customized to your preferences.</p><p>Connected toilets offer a range of benefits. They can help you save water by using less water for flushing and cleaning. They can also improve your health by providing a more hygienic bathroom experience. Additionally, they can be more convenient and comfortable to use than traditional toilets.</p><h3>The Technology Behind Connected Toilets</h3><p>Connected toilets rely on sensors and automation to provide a seamless bathroom experience. They can detect when you sit down or stand up, and they can adjust the water temperature, pressure, and angle of the spray accordingly. They can also detect when the toilet needs to be cleaned and can automatically flush and clean itself.</p><p>Connected toilets collect data on your bathroom habits, such as how often you use the toilet and how much water you use. This data can be used to help you save water and improve your bathroom experience. It can also be used to detect potential health issues, such as urinary tract infections.</p><p>Connected toilets are able to connect to your home’s Wi-Fi network, allowing you to control them via a smartphone app or voice assistant. They can also connect to other smart home devices, such as your smart shower or voice assistant, creating a seamless, connected bathroom experience.</p><p>Connected toilets can be integrated with other smart home devices, such as your voice assistant, smart shower, or smart mirror. This allows you to control your entire bathroom experience with just your voice or smartphone.</p><h3>The Future of Connected Toilets</h3><p>Smart bathroom technology is a rapidly growing industry, and connected toilets are just the beginning. In the future, we can expect to see even more advanced features, such as facial recognition technology and voice-controlled toilets.</p><p>Artificial intelligence (AI) has the potential to revolutionize the way we use our bathrooms. With AI, connected toilets could analyze data on our bathroom habits to provide personalized recommendations for improving our health and hygiene.</p><p>Toilet design and materials are constantly evolving, and connected toilets are no exception. In the future, we can expect to see toilets made from more sustainable and environmentally friendly materials, as well as toilets that are more ergonomic and comfortable to use.</p><p>Connected toilets can help reduce our water consumption by using less water for flushing and cleaning. They can also help reduce our carbon footprint by using renewable energy sources to power their sensors and other technology.</p><h3>Concerns and Challenges</h3><p>As with any connected device, there are privacy and security concerns associated with connected toilets. They collect data on our bathroom habits, which could potentially be used for nefarious purposes.</p><p>Connected toilets could be hacked or misused, potentially leading to embarrassing or even dangerous situations. It’s important to be aware of these risks and take steps to mitigate them.</p><p>Connected toilets are still relatively expensive compared to traditional toilets. It will take some time before they become affordable for the average consumer.</p><p>Connected toilets are more complex than traditional toilets, which means they may require more maintenance and repairs. It’s important to choose a reliable manufacturer and installer to avoid issues down the line.</p><h3>Conclusion and Recommendations</h3><p>Connected toilets can improve our bathroom experience by providing a more personalized and hygienic experience. They can also help us save water and reduce our carbon footprint.</p><p>When choosing a connected toilet, it’s important to do your research and choose a reliable manufacturer and installer. It’s also important to take steps to protect your privacy and security.</p><p>The future of connected toilet technology is bright, with the potential for even more advanced features and functionality. We can expect to see even more innovations in toilet design and materials, as well as advances in AI and other technologies.</p><p>Connected toilets are changing the way we think about our bathrooms. They offer a range of benefits, from improved hygiene to water savings. However, they also come with concerns and challenges, such as privacy and security risks. By taking the necessary precautions and doing your research, you can enjoy the benefits of a connected toilet while minimizing the risks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff13e4e01bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging single Django tests in VS Code]]></title>
            <link>https://medium.com/@lukas.klein/debugging-single-django-tests-in-vs-code-fba1caaebb34?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba1caaebb34</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 21:56:13 GMT</pubDate>
            <atom:updated>2023-01-03T21:56:13.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnhSwdXhPDYvK4GsuMvabA.jpeg" /><figcaption>My code usually looks like this (Photo by <a href="https://unsplash.com/@lenscapewithme?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christine Sandu</a> on <a href="https://unsplash.com/s/photos/spaghetti?orientation=landscape&amp;utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>)</figcaption></figure><p>I usually run my Django tests using the regular terminal, though I always have to remember to provide all relevant args like --settings=your.settings and --keepdb. Additionally, it’s sometime hard to type out the full module path. It gets even more challenging when you want to use a debugger. Luckily, VS Code has great built-in Python debugging support, but I struggled a bit to create a launch config that runs not always the whole test suite, but only the currently open file.</p><p>You can use variables such as ${relativeFileDirname} in your launch.json, which gives you the directory of the current file, but to tell the Django test runner which module to run, you need the path in dot-notation, not a directory path (i.e. app.tests.my_test instead of app/tests/my_test.py). I wasn’t able to figure out how to transform the variable inside the launch.json (bash replacement syntax did not work), so I went the quick and dirty path and forked the manage.py file to simply replace forward-slashes with dots in sys.argv. I placed the new file besides the existing manage.py and called it singletest.py:</p><pre>#!/usr/bin/env python<br>import os<br>import sys<br>from pathlib import Path<br><br>if __name__ == &quot;__main__&quot;:<br>    os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;datacake.settings.testing&quot;)<br>    try:<br>        from django.core.management import execute_from_command_line<br>    except ImportError as exc:<br>        raise ImportError(<br>            &quot;Couldn&#39;t import Django. Are you sure it&#39;s installed and &quot;<br>            &quot;available on your PYTHONPATH environment variable? Did you &quot;<br>            &quot;forget to activate a virtual environment?&quot;<br>        ) from exc<br><br>    execute_from_command_line([a.replace(&quot;/&quot;, &quot;.&quot;) for a in sys.argv])</pre><p>Then, I added another configuration to my launch.json:</p><pre>{<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Python: Django Debug Single Test&quot;,<br>            &quot;type&quot;: &quot;python&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;program&quot;: &quot;${workspaceFolder}/singletest.py&quot;,<br>            &quot;args&quot;: [<br>                &quot;test&quot;,<br>                &quot;--settings=datacake.settings.testing&quot;,<br>                &quot;--keepdb&quot;,<br>                &quot;${relativeFileDirname}/${fileBasenameNoExtension}&quot;<br>            ],<br>            &quot;django&quot;: true<br>        }<br>    ]<br>}</pre><p>Now I can run this configuration from the built-in Run and Debug panel 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba1caaebb34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating a Digital Ocean LoadBalancer to another Kubernetes cluster]]></title>
            <link>https://medium.com/@lukas.klein/migrating-a-digital-ocean-loadbalancer-to-another-kubernetes-cluster-76cdd0e580dc?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/76cdd0e580dc</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 15:46:18 GMT</pubDate>
            <atom:updated>2022-04-25T15:04:13.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPwbz_gLE0X4c8swQCRZeQ.jpeg" /><figcaption>Cloud for reference. Source: <a href="https://unsplash.com/photos/MHNjEBeLTgw">https://unsplash.com/photos/MHNjEBeLTgw</a></figcaption></figure><blockquote><strong>Update 2022</strong>: I was made aware that DigitalOcean have published an official guide on <a href="https://docs.digitalocean.com/products/kubernetes/how-to/migrate-load-balancers/">how to migrate Load Balancers on DOKS</a> some two months after I wrote this post. In particular, they describe their <strong>service.kubernetes.io/do-loadbalancer-disown</strong> annotation, which makes my step of creating the new load balancer to keep the old service from interfering unnecessary.</blockquote><p>At <a href="https://datacake.co/">Datacake</a>, we provide our customers with the option to white-label their IoT platform. To do this, they set their DNS to point to a Load Balancer on our Kubernetes cluster, which is running on Digital Ocean.</p><p>In an ideal world, all customers would use a CNAME on a subdomain or an ALIAS on a top-level domain. In the real world, not all domain providers support the <a href="https://blog.dnsimple.com/2011/11/introducing-alias-record/#:~:text=DNS%20has%20a%20limit.,value%20of%20A%20records%20are.">introduced-in-2011 ALIAS</a> record type, so most customers with a top-level domain resort to using a classic A-record.</p><p>Recently, we upgraded our Kubernetes to a new cluster (for various reasons we couldn’t use the old one anymore). Unfortunately, Load Balancers on Digital Ocean still don’t support floating IPs in 2021 and so we somehow had to move the existing Load Balancer to prevent our customers from having to update their DNS. Turns out, according to their support, there’s no way to do this. <strong>Spoiler: there is.</strong></p><p>While going through the resource definition of the old service, I noticed an annotation called <strong><em>kubernetes.digitalocean.com/load-balancer-id</em></strong>. The value of this annotation looked a lot like a UUID and, as it turned out, it’s exactly what it says it is: It’s the ID of the Load Balancer object on Digital Ocean.</p><p>So I spun up a test Load Balancer, copied its ID, created a new K8S service of type LoadBalancer with an annotation containing the ID and voilà, the Load Balancer quickly became populated with our nodes. To prevent the old K8S from interfering with the new K8S, I first created another LB, changed the annotation on the old service to this new ID, and created a service on the new K8S containing the ID of the old Load Balancer. After that, I went ahead and deleted the old service which also removed the temporary Load Balancer.</p><p><em>Mission accomplished.</em></p><blockquote>Tl;Dr: You can create a Kubernetes service of type LoadBalancer with an annotation called kubernetes.digitalocean.com/load-balancer-id, which will tell the system to use an existing Digital Ocean Load Balancer instead of creating a new one.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76cdd0e580dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building dynamic PayPal payment forms with Django and GraphQL]]></title>
            <link>https://medium.com/@lukas.klein/building-dynamic-paypal-payment-forms-with-django-and-graphql-c3037ba305eb?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3037ba305eb</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Sat, 22 Sep 2018 19:47:50 GMT</pubDate>
            <atom:updated>2018-09-22T19:47:50.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbU_VRd3BOPjQVm06DtlSA.jpeg" /></figure><p>Some time ago, I fell in love with GraphQL because it makes the interface between the front-end and back-end so much easier. You don’t have to spec out all API use-cases upfront anymore, which benefits especially a quick start of the project in general and the development of new features in particular.</p><p>For a recent project, one of the tasks was to implement PayPal Standard IPN payments. Since most of the back-end was implemented in Django, the way forward was to use <a href="https://django-paypal.readthedocs.io/en/stable/index.html">django-paypal</a>. They offer you the form classes, views for the webhooks and out-of-the-box pretty verbose IPN logging (which turned out to be helpful for debugging quite a few times).</p><p>How it works is that you initiate a PayPalPaymentsForm instance that you provide with your data (currency, amount, receiver address etc.) as the initial values. The form itself adds render method, that automatically adds the correct form-action URL (and a rather ugly PayPal submit button). It also adds some other parameters and handles the logic of <a href="https://django-paypal.readthedocs.io/en/stable/standard/encrypted_buttons.html">Encrypted Buttons</a> for you.</p><p>A simple example might look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7656eeb50f42cb2fa21fd6e10f1a47e1/href">https://medium.com/media/7656eeb50f42cb2fa21fd6e10f1a47e1/href</a></iframe><h4>GraphQL</h4><p>Since our project was laid out as a single-page app, we needed a way to render the form dynamically. Of course, one could simply make the output of form.render() available with an API and then somehow inject it into the DOM at the right position, but I wanted to go a step further. I wanted to output the field names and values of the form separately so that I can decide in the front-end what I want to do with them (render a form, or, in my case, submit the form automatically).</p><p>The first step was to define the schema for our API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad959fab72f43a80217253dc193f0ae8/href">https://medium.com/media/ad959fab72f43a80217253dc193f0ae8/href</a></iframe><p>In resolve_pay_pal_form, we can initiate our PayPalPaymentsForm as in the example above. I have included the action of the form in the API to support the PayPal sandbox. To get the action, django-paypal has added a <a href="https://github.com/spookylukey/django-paypal/blob/94705d5b6680153994b0b3a009d92a4a40819dc2/paypal/standard/forms.py#L156-L161">form.get_endpoint()</a> method.</p><p>Now, all we need is a way to iterate over the form’s fields, since these can vary depending on your PayPal settings. I found the easiest way to be iterating over form.fields and get the corresponding values from form[field].value().</p><p>By knowing that, we can write our resolve_pay_pal_form like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c715012ae01bd9adbda21c5e318d7524/href">https://medium.com/media/c715012ae01bd9adbda21c5e318d7524/href</a></iframe><p>Aaaaand we’re done. We can now query the form with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32faf57d0a5b4b00e5476f7e10cfb178/href">https://medium.com/media/32faf57d0a5b4b00e5476f7e10cfb178/href</a></iframe><h4>Bonus: Front-End Integration</h4><p>I needed a way to dynamically fetch a PayPal form for given parameters (say a user’s selected plan) when a button is clicked and then auto-submit the form.</p><p>I’m doing this by creating a hidden form, adding the corresponding fields from the returned data and then submit the form programmatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d85156e5d01154d4d37c4a505b49276/href">https://medium.com/media/9d85156e5d01154d4d37c4a505b49276/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3037ba305eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using your Unifi cameras in Loxone]]></title>
            <link>https://medium.com/@lukas.klein/using-your-unifi-cameras-in-loxone-a777a17c139c?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/a777a17c139c</guid>
            <category><![CDATA[loxone]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[unifi]]></category>
            <category><![CDATA[ubiquiti]]></category>
            <category><![CDATA[home-automation]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 11:52:43 GMT</pubDate>
            <atom:updated>2018-04-23T11:52:43.641Z</atom:updated>
            <content:encoded><![CDATA[<p>Since I’m a big fan of home automation, the <a href="https://www.loxone.com/enus/">Loxone Miniserver</a> is an essential part of my home. Last year, I installed some <a href="https://www.ubnt.com/products/#unifivideo">Ubiquiti Unifi Cameras</a> in my home together with the Unifi NVR. This is a great system if you need cost-efficient video surveillance.</p><p>I use the Loxone <a href="https://www.loxone.com/enen/kb/door-controller/">Door Controller</a> to control my <a href="https://nuki.io/en/">Nuki smart lock</a> already, and since the Loxone Door Controller supports IP cameras the next logical step was to somehow merge Loxone and Unifi Video together. Unfortunately, the Unifi system only supports RTSP streams out of the box while Loxone expects an MJPEG stream. I ended up using cvlc to re-encode the Unifi stream.</p><p>First, you need a spare Linux server (I chose Ubuntu) for the encoding. I don’t know exactly how much performance you’ll need, but a Raspberry Pi might work already. Then you have to install cvlc by simply running</p><pre>apt-get install cvlc</pre><p>Next you’ll need the RTSP stream URL of your camera. To get it, navigate to your camera in the Unifi NVR and choose the RTSP Service panel from the sidebar. I opted for the Medium-version of the stream, since the viewport in Loxone isn’t that large anyways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*XVzNMLlGKzy5H8uNVuP8_A.png" /><figcaption>Find your RTSP url</figcaption></figure><p>Then use this small script to start the live-encoding on your server (I put it into a loxonevideo.sh file that I made executable with chmod +x loxonevideo.sh.</p><pre>cvlc -R [RTSP_URL] --sout &quot;#transcode{vcodec=mjpg,scale=1.0,fps=15,acodec=none}:standard{access=http{mime=multipart/x-mixed-replace;boundary=--7b3cc56e5},mux=mpjpeg,dst=:8888/s0.mjpeg}&quot; &amp;</pre><p>After running the script, the MJPEG-stream should become available at <a href="http://[YOUR-SERVER-IP]:8888/s0.mjpeg.">http://[YOUR-SERVER-IP]:8888/s0.mjpeg.</a> This is the url that you can then use in your Loxone Door Controller:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4jnNXccZqIVpSVCCj3ieXA.png" /><figcaption>Insert your MJPEG-url into the Loxone Door Controller</figcaption></figure><p>In addition, you can also add the URL of the still image from your camera into the “Picture on ring”-field. Here you would use the direct IP of your camera with an appended /snap.jpeg.</p><p>The final result looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoQy4UfVuWCRgHUzyJSENA.jpeg" /><figcaption>I’m not very good at this.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a777a17c139c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built a disposable email service in two hours]]></title>
            <link>https://medium.com/@lukas.klein/how-i-built-a-disposable-email-service-in-two-hours-7dd942d96d78?source=rss-710c016aee89------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd942d96d78</guid>
            <category><![CDATA[email]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[spam]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Lukas Klein]]></dc:creator>
            <pubDate>Tue, 30 Jan 2018 10:47:04 GMT</pubDate>
            <atom:updated>2018-01-30T11:14:46.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOZC9nmYpJCaendKkOWHVw.jpeg" /><figcaption>Not the usual spam mail</figcaption></figure><p>There are times when you need a disposable email address (e.g. when signing up for a newsletter to get that discount code). Even though there are many existing services out there already, most of them are blacklisted on many websites. For this reason and since I like digging into new technology, I set out to build my own: <a href="https://muellpost.de/?utm_source=medium&amp;utm_campaign=bts-post">Muellpost.de</a> (“Müll” is German for trash).</p><p>The requirements were clear: I didn’t want to have to maintain a huge backend service that potentially breaks at some point and runs into scaling issues. Sounds like the perfect reason to give the revamped <a href="https://firebase.com/">Firebase</a> a try. I <a href="https://www.slideshare.net/LukasKlein1/firebase-46759554">worked with Firebase in the past</a>, back when it was just a realtime database and before they got acquired by Google. Since then, much has changed. They offer not only the realtime database anymore, but also many other services like a “real” datastore, Cloud Functions (everyone’s talking serverless nowadays, right?) and many mobile SDKs for error tracking, analytics and so on.</p><p>I knew from the start that I was probably going to use <a href="https://postmarkapp.com/why/inbound">Postmark Inbound email processing</a> to receive the emails, since it worked great for other projects in the past. What it does is it provides you with a unique email address (like 123xyz@inbound.postmarkapp.com) that will call a webhook with the parsed email as JSON whenever an email arrives. I usually write a Django app to process the JSON and store it in some kind of database but since I wanted to go full “serverless” this time, this wasn’t an option. This is where Firebase’ <a href="https://firebase.google.com/products/functions/">Cloud Functions</a> come in handy. They can be configured to run code whenever an URL is called. I’m using a cloud function to process the incoming JSON and store it in a Firebase realtime database. The whole code for the inbound email processing is only about 13 lines of code:</p><pre><strong>const </strong>functions = require(&#39;firebase-functions&#39;);<br><strong>const </strong>admin = require(&#39;firebase-admin&#39;);<br><br><br>admin.initializeApp(functions.config().firebase);<br><br>exports.receiveEmail = functions.https.onRequest((req, res) =&gt; {<br>    // Helper function to encode to base64<br>    <strong>const </strong>encodeAddress = address =&gt; Buffer.from(address).toString(&#39;base64&#39;);<br><br>    // An email can have multiple receivers. Using `.map` and `Promise.all` to process all of them before returning success<br>    Promise.all(req.body.ToFull.map(to =&gt; admin.database().ref(`/emails/${encodeAddress(to.Email)}`).push(req.body))).then(() =&gt; {<br>        res.status(200).send(&#39;k thx bye&#39;);<br>    });<br>});</pre><p>All it does is it exports the receiveEmail endpoint that will take the receiver email address from the JSON body, encode it to Base64 (to use it as a Firebase ref), push the email into the database and finally return an HTTP 200. After deploying the function and setting the Postmark webhook, that’s all the magic needed to store incoming emails in a database.</p><p>Right now, you have to send the email to the unique Postmark address. Even though you can set up your own inbound email address with Postmark, you are limited to a single domain. Since I wanted to be able to expand the service to multiple domains, I needed a different solution.</p><p>That’s where <a href="https://www.namecheap.com/store/domains/freedns/">Namecheap Free Dns</a> comes in. It allows you to configure a catchall email address on your domain that forwards to a given email address. Problem solved ¯\_(ツ)_/¯</p><p>To display the emails, I wrote a really simple React front-end using react-redux-firebase which I’m hosting on Firebase hosting (obviously). To ensure security, I’m rendering the emails inside a <a href="https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/">sandboxed Iframe</a>.</p><p>One last thing was left to do: I wanted the users to be able to delete emails. This can be accomplished quite easily using Firebase security rules, which ended up looking something like this:</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;.read&quot;: &quot;auth != null&quot;,<br>    &quot;.write&quot;: &quot;auth != null&quot;,<br>    &quot;emails&quot;: {<br>      &quot;$inboxhash&quot;: {<br>        &quot;.read&quot;: true,<br>        &quot;$email&quot;: {<br>          &quot;.write&quot;: &quot;data.exists() &amp;&amp; !newData.exists()&quot;<br>        }<br>      }<br>    }<br>  }</pre><p>They basically allow you to read the emails of a given inboxhash (the Base64-encoded receiver email address) and delete individual emails (but not tamper with the data).</p><h3>Conclusion</h3><p>Using readily available technology, I was able to build a disposable email address service in about two hours. The operation costs are very marginal (at the moment only the domain cost, all other services like Postmark and Firebase have a very generous free tier).</p><h4>Technologies used</h4><ul><li>Namecheap Free Dns</li><li>Postmark Inbound</li><li>Firebase Cloud Functions</li><li>Firebase Realtime Database</li><li>Firebase Hosting</li><li>Front-end: react, react-redux-firebase, react-router, moment.js</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd942d96d78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>