<?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 Kieron Spearing on Medium]]></title>
        <description><![CDATA[Stories by Kieron Spearing on Medium]]></description>
        <link>https://medium.com/@kieron-spearing?source=rss-9d42785e3571------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uMFXr9ikNe5u43W65jswbg.jpeg</url>
            <title>Stories by Kieron Spearing on Medium</title>
            <link>https://medium.com/@kieron-spearing?source=rss-9d42785e3571------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:16:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kieron-spearing/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[Concurrency and Parallelism: What is the difference?]]></title>
            <link>https://medium.com/data-science/concurrency-and-parallelism-what-is-the-difference-bdf01069b081?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf01069b081</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multitasking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 14:03:04 GMT</pubDate>
            <atom:updated>2022-02-14T14:03:04.136Z</atom:updated>
            <content:encoded><![CDATA[<h4>A fresh simple way to understand these complex topics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*dDJO9Ski233CLRadWdbqvQ.png" /><figcaption>Image made by myself using <a href="https://app.diagrams.net/">diagrams.net</a></figcaption></figure><p>In my current position and in many articles, I have heard these expressions thrown around a lot, however, when I first started I didn’t truly understand what they meant and naturally I felt that this was unacceptable.</p><p>Having felt this way I immediately decided that I could not put up with that and started to delve deeper into them to understand why they are important to computer science and discovered how to learn them using simple examples.</p><p>In this post, I will be going over these concepts at a basic level as well as a few simple implementations in <em>Python</em> that helped me understand them better.</p><p>If you wish to struggle to understand them after reading this post I would suggest re-implementing the above examples synchronously with a simple for loop to see the difference yourself.</p><h3>What is Concurrency and Parallelism?</h3><p>When you develop complex systems that have a lot of tasks, you will eventually come to a point where performing all of these actions synchronously isn’t efficient enough for your needs.</p><p>Concurrency and parallelism are mechanisms that were implemented to allow us to handle this situation either by interweaving between multiple tasks or by executing them in parallel.</p><p>On the surface these mechanisms may seem to be the same however, they both have completely different aims.</p><h4>Concurrency</h4><p>The goal of concurrency is to prevent tasks from blocking each other by switching among them whenever one is forced to wait on an external resource. A common example of this is handling multiple network requests.</p><p>One way to do this would be to launch a single request, wait for the response and then launch the following request and repeat until you have handled every request. The problem with this is it is very slow and inefficient.</p><p>The better way would be to launch every request simultaneously, then switch among them as you receive the responses. By doing this we eliminate the time spent waiting for the responses.</p><h4>Parallelism</h4><p>If you have ten workers you wouldn’t want one of them doing all the work while the other nine sit around and do nothing.</p><p>Instead, you would split the work among all the workers, that way not only would the work be done faster but also the workers would do less.</p><p>Parallelism takes the same concept and applies it to the hardware resources at hand. It is all about maximizing the use of said resources by launching processes or threads that make use of all the CPU cores that the computer possesses.</p><p>Both of these concepts are extremely useful for handling multiple tasks simultaneously although you need to pick the correct method for your particular needs.</p><p>Concurrency is amazing for tasks that depend greatly on external resources, while parallelism is amazing for many CPU-intensive tasks.</p><h3>How do we work with these concepts in Python?</h3><p><em>Python</em> provides us with mechanisms to implement concurrency and parallelism, for concurrency we have <em>threading</em> and <em>async </em>whereas for parallelism we can make use of <em>multiprocessing</em>.</p><p>Oftentimes these are seen as scary topics and in some ways they are, I however found that taking a relatively simple example of each implementation and playing with them in many ways is the best way to approach it before taking the deep dive into the theoretical side.</p><p>I highly recommend that once finished with this post, you take the concepts and the examples I have left below and play with them until you feel comfortable enough to try to implement them in different ways yourself.</p><h4>Threading</h4><p>Having said to not worry too much about the theory before practicing, we do need to have a basic idea about what a thread is to get started with threading.</p><blockquote>A thread is similar to a sequential program in that it has a beginning, an execution sequence, and an end. At any time during the runtime of the thread, there is a single point of execution however, a thread is not a program, it cannot run on its own.</blockquote><p>Essentially a thread is a separate flow of execution, where you can take one or more functions and execute them independently of the rest of the program. You can then work with the results, usually by waiting for all threads to run to completion.</p><p>There are two main ways in which threading is handled in <em>Python</em>, either with the threading library or with the <em>ThreadPoolExecutor</em> created as a context manager, this is the simplest way to manage the creation &amp; destruction of the pool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dffb3752614622058c7636233a256e5/href">https://medium.com/media/9dffb3752614622058c7636233a256e5/href</a></iframe><p>If you take a look at the above example we are simply creating a function that is being launched in separate threads that simply starts the thread and then sleeps, simulating some external wait time.</p><p>In the main function, you can see how I have implemented both the above methods, the first in lines 9-19 and the second in lines 23 &amp; 24.</p><p>While both methods are fairly simple, it is quite obvious which implementation requires less effort from our side.</p><p>This is a rather simplified example however, it does help to understand the theory. A more realistic simple example of this could be the following script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50bec9299384aef3efea1c204cc3c00a/href">https://medium.com/media/50bec9299384aef3efea1c204cc3c00a/href</a></iframe><p>In this snippet, we are using threading to read the data from multiple URLs simultaneously by executing multiple instances of the<em> thread_function()</em> and storing the results in a list.</p><p>As you can see using the <em>ThreadPoolExecutor </em>makes it easy to handle the required threads. Although this is a small example we could submit many more URLs using this without having to wait for each response.</p><p>From the above examples, we can see that threads are a convenient and well-understood way to handle tasks that wait on other resources, we also see that <em>Python’s</em> standard library comes with high-level implementations to make it even easier.</p><p>However, we must also remember that the <em>Python</em> runtime divides its attention between the threads so that it can manage them correctly, thus this is not suitable for CPU-intensive work.</p><h4>Coroutines and asyncio</h4><p>Coroutines are a different way to execute functions concurrently by way of special constructs rather than system threads.</p><p>Forgive me once more for getting you to dip the tips of your toes into some basic theoretical knowledge on the topic but it is essential to know what a coroutine is to understand what is happening as we implement this in <em>Python.</em></p><blockquote>A coroutine is a general control structure whereby flow control is cooperatively passed between two different routines without returning, it is not threading, nor is it multiprocessing. Neither is it built on top of either of these, it is a single-threaded, single-process design using cooperative multitasking.</blockquote><p>Essentially while threading takes multiple functions and launches them on separate threads, <em>asyncio</em> operates on a single thread and allows the program’s event loop to communicate with multiple tasks to allow each to take turns running at the optimal time.</p><p>We implement this in <em>Python by using asyncio</em> which is a <em>Python</em> package that provides a foundation and API for running and managing coroutines along with the <em>async </em>and<em> await</em> keywords.</p><p>In a similar fashion to earlier you can see how we implement a very basic example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9017caa1c494a59579e1b72649511ff0/href">https://medium.com/media/9017caa1c494a59579e1b72649511ff0/href</a></iframe><p>I believe this is a much more clean and simple way to implement concurrency in <em>Python. </em>However, it is much newer to the language and thus less used than threading.</p><p>Once more I can take the exact same example related to reading the data from multiple URLs and implement it using <em>asyncio.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da3377699354e15d4822c7add549d5bb/href">https://medium.com/media/da3377699354e15d4822c7add549d5bb/href</a></iframe><p>At first, it may come across as a bit more complicated but I think it is a lot cleaner, more explicit, and easier to understand than threading.</p><p>This is because coroutines make it clear in the program’s syntax which functions run side by side, while with threads any function can be run in a thread.</p><p>They also are not bound by architectural limitations as threads are and require less memory due to the fact that it runs on a single thread.</p><p>The only downside is that they do require the code to be written in their own syntax and it doesn’t mingle well with synchronous code, as well as the fact that they don’t allow CPU-intensive tasks to run efficiently side-by-side.</p><h4>Multiprocessing</h4><p>Multiprocessing is the mechanism that allows you to run many CPU-intensive tasks in parallel by launching multiple, independent instances of the <em>Python</em> interpreter.</p><p>Each instance receives the code and data required to run the task in question and runs independently on its own thread.</p><p>Although the above examples are not amazing in regards to the kinds of tasks you would want to run using multiprocessing, we can implement them once more in a similar fashion so that we can see how they differ from one another.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/069112ba8d4ee995e3db564e9706f5aa/href">https://medium.com/media/069112ba8d4ee995e3db564e9706f5aa/href</a></iframe><p>The above being the most basic process we could replicate with multiprocessing, and the below reimplementing the exact same functionality of reading data from multiple URLs simultaneously.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ad3baff45bbe14ef122cf7181041b7/href">https://medium.com/media/e4ad3baff45bbe14ef122cf7181041b7/href</a></iframe><p>In this snippet above the <em>Pool()</em> object represents a reusable group of processes that we are mapping the iterable to distribute between each instance of the function.</p><p>The one massive advantage this provides is the fact that each operation is run operating on a separate <em>Python</em> runtime and a full CPU core, allowing us to run CPU-intensive processes simultaneously.</p><p>One of the downsides is that each subprocess needs a copy of the data it works with sent to it from the main process and generally they return data to the main process.</p><p>As I said earlier, I have been working with an incredibly simple example.</p><p>However, I find the best way to learn and become comfortable working with new complex concepts in a language is to make it extremely simple at first and slowly but surely peel back the simplicity and expose the complex details below.</p><p>I hope this has helped you find a way to approach these vast topics in a relatively simple way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf01069b081" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/concurrency-and-parallelism-what-is-the-difference-bdf01069b081">Concurrency and Parallelism: What is the difference?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Wish I Had Known When Starting my Journey in Computer science]]></title>
            <link>https://medium.com/data-science/what-i-wish-i-had-known-when-starting-my-journey-in-computer-science-efb6edd0f417?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb6edd0f417</guid>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 14:25:17 GMT</pubDate>
            <atom:updated>2022-02-01T14:25:17.355Z</atom:updated>
            <content:encoded><![CDATA[<h4>My experience through everything that I wish I had known before I started my journey in computer science and software development</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHkcDkw8cEUc3bTljNFgNg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@altumcode">AltumCode</a> on <a href="https://unsplash.com/">unspash</a></figcaption></figure><p>When I started my journey I found it rather difficult to get some decent advice on this topic and that it is scattered throughout the internet with many different views.</p><p>I made a few mistakes along the way that I might not have made having known what I know now and I am writing this in the hopes that I can help others avoid this issue, while at the same time providing some advice to all who are looking for it.</p><p>Throughout this post, I will talk about the experience along my journey and also what I could have done better had I known all of this.</p><p>When we refer to learning to program, what we are referring to is learning to learn effectively.</p><p>This is because as a developer you work in the everchanging world of technology, and you are going to have to continuously learn throughout your entire career and it all starts with the first steps, if you start wrong then it could be a rocky road, while if you start correctly it is smooth sailing thereafter.</p><p>With this in mind, I have compiled a complete guide to the most important, yet simple aspects to master on your way to becoming a developer as well as some resources that I hope will help you on your way.</p><h3>Write Code Every Day.</h3><p>Probably the most important part of the entire journey is the physical act of practice.</p><p>You should strive to write some code every day, even if in writing that code half the time is spent in debugging, this is normal but if you don’t practice you will never turn it into muscle memory.</p><p>Personally, when I was going through my journey I found myself being so absorbed and worried about that which I did not know yet, that I spent more time reading and researching different courses and programming languages than actually getting my hands dirty.</p><p>It wasn’t until I decided that I wasn’t retaining enough to continue without actually building something that I discovered what had been right in front of me the entire time. You only truly learn something by doing.</p><p>This is the reason why I state that this is the most important factor to work on, no matter how little or how much, you can only truly improve fast by writing and debugging code every single day.</p><blockquote>Knowledge is of no value unless you put it into practice. <strong>— Anton Chekhov</strong></blockquote><h3><strong>Plan carefully before tackling a problem.</strong></h3><p>While it is extremely important to write code every day, it is equally important to develop the best mindset for tackling a new problem.</p><p>This means planning how you will go about solving a problem before writing the physical code.</p><p>The truth of it is that the act of writing code is probably only twenty percent of the job when working in the real world, the rest being filled with planning, investigating, and inevitably debugging.</p><p>However, if you plan and investigate correctly, then you should be able to reduce the amount of time spent debugging the code.</p><p>Thus it is incredibly important to build the ability to think clearly and have patience when approaching a new problem. Use your time appropriately and plan what you are going to do before trying to implement it.</p><p>The best way of doing this at first, I found is to write it out in your native language in a clear concise way, then translate that into pseudocode and read through it carefully while thinking, <em>“Is there any way that this could go wrong?”,</em> and only once you are completely satisfied with this implement it into actual code.</p><p>This process will become second nature over time and you won’t have to go to such an extent, but it is good to develop the thought process the long way at first to train your mind appropriately.</p><blockquote>If you fail to plan, you are planning to fail. <strong>— Benjamin Franklin</strong></blockquote><h3>Test everything!</h3><blockquote>I know, I know. Why did we go through all the planning if we then have to do it again as we test all the code we have written?</blockquote><p>Because we are human and we make mistakes! No matter how confident you are in your abilities I guarantee that you will make mistakes, and the only way to avoid these mistakes is to test everything thoroughly.</p><p>I believe strongly that when testing you should do everything in your power to cause the code to behave in an unexpected or unwanted way, that way you can find the bugs that you may have missed.</p><p>In the future, as you develop your skills, you will learn how to test your code through automated testing where you test all the possible edge-cases you can think of, but until then you should already teach your mind to think of what could go wrong.</p><h3>Be persistent and build something that you are personally invested in.</h3><p>Debugging is hard and it can be demoralizing to be faced with an issue and not find a solution for days on end, this is completely normal and if you don’t have this, especially at first, then it is probably more worrying.</p><p>It is important to become comfortable in the face of the unknown and develop analytical skills to help you overcome this, after all debugging is a skill one needs to work on as much as, if not more than physically writing code.</p><p>It is for this reason that it is normal for one to suggest that a beginner finds a project that truly helps them or that they are passionate about for their first project.</p><p>This will help you remain determined to finish the project rather than leaving it when it becomes too difficult.</p><p>My first project was a web application that would help me do my work at the time better, essentially organizing, tracking, and grading the English classes that I was teaching.</p><p>I was so passionate about improving not only my work situation but also the entire system that the company used, that I spent about four months working on the application to get it to a level that I felt was good enough at the time.</p><h3>Have a goal.</h3><p>This is equally important when building your first application, as the truth is that the amount of improvements you can make to any process or application is literally endless but you also need to know when to pull back and focus on learning more to improve your skills.</p><p>I experienced this in the aforementioned application, I spent months working on it and found myself continuously improving as I did. But whenever I looked back at the code I had written I knew that I could improve it with what I had learned.</p><p>Eventually, I realized I was getting so absorbed in the little details of it all that I had forgotten to look at the bigger picture, what was the reason I started the process in the beginning.</p><p>It was then I learned that we need to have a clear concise goal for the process we are building and although this may change over time, which is natural, we cannot forget to take a step back and look at the bigger picture to know when to say it is finished.</p><h3>Learn to ask the right questions and use google correctly.</h3><p>As you go through many courses and try to solve different problems, normally, you fall back onto google and StackOverflow to help find some solutions.</p><p>This is an essential skill for a developer and is extremely important when investigating the problem, you need to learn to ask the right questions and when finding the solution it is extremely important to <strong>NEVER</strong> copy and paste what you find into your code without fully understanding it.</p><p>Not only can this be dangerous but also it doesn’t help you improve in any way whatsoever.</p><p>Now I am not saying you shouldn’t use the solutions you find online, but rather that you should fully understand how they came to that solution and what they are doing with the code before implementing it yourself.</p><p>Doing this will help you improve your knowledge and even develop a deeper understanding of what you are doing, it will also help you avoid implementing potentially dangerous code into the application.</p><h3>Don’t worry about the language, but stick to one at first.</h3><p>As I stated earlier, when I started I was continuously worried about which language I should be learning, which language was the best to learn first, should I know more than one language, etc.</p><p>In the end, the truth is it doesn’t matter. Learning a lower-level language or a statically typed language will indeed allow it to be easier to learn a dynamically typed language after, but the real truth is that which language you learn first isn’t the most important thing to worry about.</p><p>What you should worry about is picking a language that aligns with what you want to do in the future and then using that language to learn the underlying concepts that are true for most programming languages and object-oriented programming.</p><p>Once you have these concepts don’t change language yet as even though you may think you know it well, you don’t.</p><p>Once you have learned the concepts and are comfortable using them in the chosen language, then this is when you can truly get down and dirty and learn concepts that are more language-specific and truly build your experience in the language until you are <em>fluent</em> in it.</p><h4>Why do I suggest sticking with one language until this point?</h4><p>I suggest this because if you move from language to language only getting to a superficial level, then you never really can say you know any of these languages, and if you want to be hired and paid for your work you need to have a more in-depth knowledge of the language they expect you to work in.</p><p>Thus I would suggest if you want to be hirable and build your knowledge in the field in a better way, then pick whichever language aligns with what you want to do in the future. Use it to learn the concepts of object-oriented programming and computer science, then deepen your knowledge in this language before branching out into other languages.</p><h3>Resources</h3><p>With all the above advice, you should have all the tools required to move forward in your journey but you will also have a lot to learn and you will also need some resources to learn from.</p><p>In this section, I will go over the resources that I have found very useful throughout my journey as well as why I found them useful.</p><h3><a href="https://stackoverflow.com/">StackOverflow</a></h3><p>I cannot state this enough, StackOverflow is the best possible resource you will ever come across! It is a website dedicated to developers helping one another and answering issues that they have been experiencing.</p><p>You definitely should have an account on there and when in need of answers it will become the first place to look.</p><p>A slightly less feature of the site also comes to light once you have participated constructively in it, this is the real-time chats that they have that allow you access to real-time communication with amazing developers in all programming languages where you can pool your knowledge and help one another.</p><p><em>I should state as a disclaimer that you should never display code that is not yours to share and rather if you are faced with an issue you should build a quick </em><a href="https://stackoverflow.com/help/minimal-reproducible-example"><em>Minimal Reproducible Example</em></a><em>, that you can safely use to find the solution. There are many times that in building this example, you find the solution yourself.</em></p><h3><a href="https://www.edx.org/cs50">CS50’S Online Courses</a></h3><p>These are by far some of the best possible resources for when starting in computer science, or even when approaching new areas such as <a href="https://www.edx.org/course/cs50s-web-programming-with-python-and-javascript">Web Programing</a>, <a href="https://www.edx.org/course/cs50s-introduction-to-game-development">Game Development</a>, or <a href="https://www.edx.org/course/cs50s-introduction-to-artificial-intelligence-with-python">Artificial Intelligence</a>.</p><p>They are all extremely intense, have side projects that you have to do to complete them, and most importantly they provide you with enough information to start you off with the projects but make them difficult enough that you have to research what you are doing to find the solution.</p><h3><a href="https://www.freecodecamp.org/learn/">Free Code Camp</a></h3><p>Free Code Camp is another amazing resource that you can use to learn many topics as well as find some fun, relatively simple projects.</p><p>I did find that they <em>hold your hand</em> throughout the learning process a bit too much for my liking but at the same time, every course offered on it provides a lot of in-depth detail on the different topics, and once more you have to complete multiple projects to finish the course.</p><h3><a href="https://www.hackerrank.com/">HackerRank</a>, <a href="https://leetcode.com/">LeetCode</a> &amp;&amp; <a href="https://www.codewars.com/">CodeWars</a></h3><p>While CS50 and Free Code Camp are amazing resources that provide amazing courses, they don’t provide simply a place to practice your problem-solving skills and knowledge.</p><p>This is where these three come into play. They are wonderful resources that offer many different challenges for you to use to practice and hone your skills without having to invest your time into entire courses.</p><p>I tend to use these weekly to practice some problem-solving skills, or become more comfortable working in a new language that I am learning at the time.</p><h3>Conclusion</h3><p>There are many concepts and skills that you will have to master throughout your journey but you also need to remember to enjoy it and have fun as you go through the endless world of technology.</p><p>With everything I have said throughout this post you should have a good headstart and if you just remember to write code every day, plan carefully, test everything, be persistent, have a goal, and ask the right questions then you should find yourself progressing very fast.</p><p>I hope this post has helped you in some way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb6edd0f417" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-i-wish-i-had-known-when-starting-my-journey-in-computer-science-efb6edd0f417">What I Wish I Had Known When Starting my Journey in Computer science</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensions in Python: What are they? Why Should you use them?]]></title>
            <link>https://medium.com/geekculture/comprehensions-in-python-what-are-they-why-should-you-use-them-ff24a49460e7?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff24a49460e7</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 18:33:35 GMT</pubDate>
            <atom:updated>2022-01-31T07:57:42.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sbnx8213bpAroEq6t_hg_g.jpeg" /></figure><p>Being one of the most iconic and <em>Pythonic</em> syntax in the language, I am certain everybody has heard of or worked with list comprehensions already.</p><p>But did you know that there are three other types of comprehensions in the language?</p><p>Throughout this post, I will talk about what comprehensions in <em>Python </em>are and why one would use them. I will also go through when using a comprehension can be detrimental to the readability of code.</p><h3>What is a comprehension in Python?</h3><p>Essentially a comprehension in <em>Python </em>is the syntax used to create a new sequence by performing an operation over another iterable.</p><p>There are four types of comprehensions in <em>Python.</em></p><ol><li><strong>List Comprehensions</strong></li><li><strong>Dict Comprehensions</strong></li><li><strong>Set Comprehensions</strong></li><li><strong>Generator Comprehensions</strong></li></ol><p>A common misconception about comprehensions that most beginners have is that the initial iterable needs to be of the same type as the comprehension. However, this is not the case, for example, if you are working with a <em>dict comprehension </em>the original iterable can also be a list.</p><p>The type referred to in the name is the type of sequence that is returned from the comprehension.</p><h3>Why should one use a comprehension in Python?</h3><p>We use comprehensions in our code because it is more <em>Pythonic</em> and readable to use them. However, one needs to be careful when using them in certain scenarios as there are times when they can have the opposite effect.</p><h3>List Comprehension</h3><p>A <em>List comprehension </em>is the most common type of comprehension used in <em>Python</em>, and it follows the simple syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64898f1bccec4840e08c7710ee8376b9/href">https://medium.com/media/64898f1bccec4840e08c7710ee8376b9/href</a></iframe><p>As we can see here the condition is completely optional, but if you use it depending on whether you are using the <em>else</em> clause the position of it in the <em>list comprehension </em>will change.</p><p>We can also see that they are extremely easy to use and can be quite handy in reducing the use of <strong>for loops</strong>, making the code cleaner.</p><p>The best way to get the hang of it is to play with them yourself and learn their limitations. Below is a real example of the usage to give you an idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16aca3591c450046ce97c97b996bec33/href">https://medium.com/media/16aca3591c450046ce97c97b996bec33/href</a></iframe><h3>Dict Comprehension</h3><p>As I mentioned earlier the <em>type</em> mentioned in the comprehension name refers to the type of sequence that it creates, not the type of iterable used in the comprehension.</p><pre>The syntax for a dictionary comprehension is:</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/819783752a8b7608a0a61685f1a10eee/href">https://medium.com/media/819783752a8b7608a0a61685f1a10eee/href</a></iframe><p>Once more the condition is optional here.</p><p>You may use this in many different scenarios, for example, imagine you want to be able to compare the salaries earned based on the position of an employee in the company, and you have a long list of dictionaries containing all sorts of information about each employee.</p><p>The truth is you may be able to work with it but there is a lot more information than needed if you only care about the position and salary, thus we could use a dictionary comprehension to easily create a new dictionary with only the information we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64304d0e18643ac78c899256d5b8b6a5/href">https://medium.com/media/64304d0e18643ac78c899256d5b8b6a5/href</a></iframe><p>As you can see above we can achieve this very easily and cleanly in one line using a <em>dict comprehension.</em></p><h3>Set Comprehension</h3><p>A <em>set comprehension</em> functions similarly to a <em>list comprehension</em>, except it has all the benefits of a set, namely items in the set cannot be repeated and the values are not in order.</p><p>It also uses a similar syntax to a <em>list comprehension</em> except it uses curly brackets instead of square brackets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633076916a5233673c89bbf8846f999b/href">https://medium.com/media/633076916a5233673c89bbf8846f999b/href</a></iframe><p>There are times in which this can be useful but you must remember to be careful as the beneficial aspects of the set can cause issues if requiring the results to be ordered, as can be seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f4a7967fe12b916cd0f8cf529b7a38b/href">https://medium.com/media/8f4a7967fe12b916cd0f8cf529b7a38b/href</a></iframe><h3>Generator Comprehensions</h3><p><em>Generator comprehensions </em>are the least known type of comprehension that we have in <em>Python</em>.</p><p>A <em>generator</em> is a function that returns an object(iterator) which we can iterate over one at a time, it is a unique syntax in python that is usually generated from a function with the <strong>yield</strong> keyword.</p><p>The syntax of a generator comprehension is as simple as all the others:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e22b8020d03edc3a4ea369ccfbf63402/href">https://medium.com/media/e22b8020d03edc3a4ea369ccfbf63402/href</a></iframe><p>The beauty of using a generator is that we can iterate over it simply by using the built-in function <strong>next()</strong> to iterate over it one step at a time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c26d86611a48441ea7ac279cb4c45857/href">https://medium.com/media/c26d86611a48441ea7ac279cb4c45857/href</a></iframe><h3>When shouldn’t one use comprehensions?</h3><blockquote>After reading everything here it seems like a no-brainer to always use comprehensions, correct?</blockquote><p>Well no.</p><p>Comprehensions in python can be used in all the ways above to create readable code but when we use <em>nested comprehensions</em> we need to be careful as it can cause the code to become less readable.</p><h3>Nested Comprehension</h3><p>A <em>nested comprehension</em> is a term we use to refer to comprehensions being done within other comprehensions.</p><p>While this is an extremely powerful feature, it can also create the opposite effect in form of readability.</p><p>For example, both the below scripts create the pyramid below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/438928dd8cb0c6585f096edfdbf1ff9c/href">https://medium.com/media/438928dd8cb0c6585f096edfdbf1ff9c/href</a></iframe><pre>#<br>##<br>###<br>####<br>#####<br>######<br>#######</pre><p>As we can see, while this is a fairly basic example it is already more readable without the nested comprehension and as the complexity increases, the harder it will be to maintain readability with these.</p><p>Having been through the article and understanding the comprehensions we can not fully understand the power they bring to the language, but at the same time, we need to be careful not to abuse them as it can quickly become detrimental to the readability when the logic is not simple.</p><p>Whenever I start to nest comprehensions myself I always like to remember the simple saying:</p><blockquote>The code should explain the comments, not the comments explaining the code.</blockquote><p>And then decide whether it may be best to write the logic out without the comprehension.</p><p>The beauty in using comprehensions is that it helps you to produce efficient readable code when used correctly.</p><p>I hope you enjoy the reading and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff24a49460e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/comprehensions-in-python-what-are-they-why-should-you-use-them-ff24a49460e7">Comprehensions in Python: What are they? Why Should you use them?</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bobotie: The Taste of a Nation]]></title>
            <link>https://kieron-spearing.medium.com/bobotie-the-taste-of-a-nation-5d79d6f12cd1?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d79d6f12cd1</guid>
            <category><![CDATA[south-africa]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[life-lessons]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 18:32:56 GMT</pubDate>
            <atom:updated>2022-01-21T18:32:56.033Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the dish that beautifully demonstrates the fusion of cultures that is the <em>Rainbow Nation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*D6u7QBBRyBpNCY8zs4TgGw.jpeg" /></figure><p>Since <em>South Africa</em> is a country that has a rich history of colonization and slavery, it is also a country with an extremely diverse range of cultures and with this an amazing variety in their food.</p><p>Usually in any country, the food is often developed around their history and cultural influences, you would be hard-pressed to find a better example of such than South Africa.</p><p>As you walk through the <em>Bo-Kaap </em>neighborhood, or even throughout the entire of<em> KwaZulu-Natal </em>province, you find yourself under the constant onslaught of the aroma of spices coming from Malay, Indian, Asian, and even African cuisines, all of these mixing in the air in perfect harmony as they are brought together with the smokey smell of smoldering embers.</p><p>I have heard it said before that the smell of Spain is garlic and tomato. Well, if that is then this amazingly aromatic smell is that of Africa.</p><p>Having been brought up in <em>South Africa</em> I hold some fast favorites, this particular dish happens to be high among them. It beautifully demonstrates the fusion of cultures in South Africa with a delectably fragrant finish.</p><p>The origin of the dish is widely disputed however, it is mainly found within the Cape region of South Africa. It is a dish consisting of a delicious mix of fragrant curried mince with the sweet tangy flavor of the chutney and the body of the nuts and fruit within.</p><p>The recipe is extremely simple and can be prepared in advance and simply placed in the oven on the day. It also, as with all curry-based recipes, matures well as time goes on after cooking, meaning that you never have to worry about cooking too much of it as you are sure to enjoy it as the days go by!</p><p><strong>Ingredients</strong></p><p>· 1 Large Onion, Peeled and diced.</p><p>· 3 Cloves of Garlic, Peeled and grated.</p><p>· Roughly 2cm x 2cm Ginger, Peeled and grated.</p><p>· 1 tsp Coriander Seeds, Ground.</p><p>· 1 tsp Cumin Seeds, Ground.</p><p>· 1/2 tsp Black Pepper, Ground.</p><p>· 2 Slices of Bread.</p><p>· 375ml Milk.</p><p>· 1 tbsp Curry Powder.</p><p>· 1/2 tbsp Garam Masala.</p><p>· 500g Minced beef.</p><p>· 3 Large Eggs.</p><p>· 3 Bay Leaves.</p><p>· 80g Raisins.</p><p>· 75g Almonds, Roughly chopped.</p><p>· 80g <a href="https://kieron-spearing.medium.com/essential-recipe-collection-apple-chutney-1e66008deb44">Apple Chutney</a>.</p><p>· 2 tbsp Olive Oil</p><p>· Cumin, Ground. (To Dust.)</p><p><strong>Method</strong></p><ol><li>In a container place the bread and the milk, allow to soak as you prepare the rest.</li><li>Place a large pan over medium-high heat, place 1 tbsp of olive oil inside the pan and gently sauté the onion, garlic, and ginger until soft.</li><li>Add the coriander, cumin, and black pepper, then continue cooking the onion mix until it reaches a golden caramelized color.</li><li>Once it has reached this point, remove it from the heat and set it aside in a large mixing bowl for later use.</li><li>Remove the bread from the milk, squeezing all the liquid out of it and reserving the liquid for later use.</li><li>Combine the mince, the bread, the curry powder, and the garam masala well, then place the same pot back over medium-high heat.</li><li>Add the remaining olive oil into the pan and when hot, caramelize the meat mixture until golden brown. Once done add the mince to the onion and mix well.</li><li>In a separate bowl combine 1/2 the milk, 1 egg, the chutney, raisins, nuts, and the bay leaves, then mix this into the meat mixture.</li><li>Place the entire mix into an oven-proof dish.</li><li>Beat the remaining eggs with the remaining milk and pour it over the top of the meat mixture, then coat the top with some ground cumin. Allow to sit for two hours.</li><li>Preheat the oven to 180°c.</li><li>Bake the <em>Bobotie</em> until it has a golden color and solid top.</li><li>Serve warm with saffron rice and flatbread.</li></ol><p>Once you have finished with this the only thing left to do is enjoy with a lovely glass of wine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d79d6f12cd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Am I Seeing _ Everywhere in Python Code?]]></title>
            <link>https://blog.devgenius.io/why-am-i-seeing-everywhere-in-python-code-92bf0fa93b9c?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/92bf0fa93b9c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[knowledge]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 11:33:45 GMT</pubDate>
            <atom:updated>2022-01-21T11:33:45.586Z</atom:updated>
            <content:encoded><![CDATA[<p>Seriously?! I cannot be the only one that had this question in the beginning!</p><figure><img alt="An underscore against mobile phine with laptop and keyboard in the background laying over a tablecloth" src="https://cdn-images-1.medium.com/max/1024/1*ZTJcvMmOYwjb1HqTcsF4hg.png" /><figcaption>Image by <a href="https://unsplash.com/@_ferh97">Fernando Hernandez</a> from <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>After some time in <em>Python</em> development and working in a company where there were many people to learn from I noticed the<em> underscore </em>being used in many ways other than that which I knew.</p><p>Naturally, this made me both curious and a little annoyed as to why I didn’t understand the full potential of a simple character in the <em>Python Programming Language</em>.</p><p>Although this is a rather simple subject in the language, being the type of person I am, I could not be satisfied completely until I had gone through the many uses, done more research into them, and even played with each of them myself.</p><p>Thus began yet another winding road of research, investigation, and fun as I pursued the knowledge I required and became comfortable in the use of this in my code daily.</p><p>In this post, I will be going over the different uses of the underscore in <em>Python code</em> that came to light in my research, some well known, while others not so much.</p><p>When we take a closer look as to how the <em>underscore</em> is used we can typically separate it into three separate areas: <em>Naming, The Interpreter, </em>and <em>Useful Development Tricks.</em></p><p>Each of these can be quite useful to use in your code daily and help one write clean code more efficiently.</p><h3>Naming</h3><p>There are multiple ways in which the <em>underscore </em>is used in <em>Python, </em>but when looking at how it is used in naming there are five main uses to mention.</p><ol><li><a href="https://en.wikipedia.org/wiki/Snake_case">Snake Case Naming Convention</a>.</li><li>Single Leading Underscore.</li><li>Single Post Underscore.</li><li>Double Leading Underscore.</li><li>Double Leading and Post Underscore.</li></ol><h4><em>Snake Case Naming Convention</em></h4><p>When we refer to the <em>snake case naming convention</em> we are referring to the way we use the underscore to separate words in the name, this is the recommended naming convention for function and variable names according to<a href="https://www.python.org/dev/peps/pep-0008/#:~:text=module%20non%2Dpublic%22).-,Function%20and%20Variable%20Names,prevailing%20style%20(e.g.%20threading.py)%2C%20to%20retain%20backwards%20compatibility.,-Function%20and%20Method"> PEP-8</a> to write clean, beautiful <em>Python </em>code.</p><h4><em>Single Leading Underscore</em></h4><p>When we use a <em>leading underscore</em> before variable, function, or method names it is to indicate to the developer that it is only for internal use within the class.</p><p>The intention of this is for it to be treated as non-public, meaning that if importing from a module using the <em>asterisk *, </em>all names beginning with a <em>leading underscore </em>will not be imported<em>.</em></p><p>For example, if we have these functions and variables saved in a script called <em>example.py </em>and we try to import it and access the variables and functions, then we will not be able to access those with a <em>leading underscore.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e25a80fdb217fd908919fc502d47ed6/href">https://medium.com/media/3e25a80fdb217fd908919fc502d47ed6/href</a></iframe><figure><img alt="Example of explained usage" src="https://cdn-images-1.medium.com/max/663/1*T_ERSi20tAFEmRbooRh3Ug.png" /></figure><p>However considering that <em>Python </em>doesn’t truly support<em> private </em>variables and methods, if we were to call them directly from the module as below, then we can access these variables and functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*g6DPIBUVClDlQsPO1RGX9g.png" /></figure><p>We can also identify above that even members of a class are not truly private, thus this is mainly used to indicate the intention to the developers working with said code.</p><h4><em>Single Post Underscore</em></h4><p>This particular type of usage of the <em>underscore</em> is used to help avoid naming conflicts and is particularly useful if you want to use any of the <em>Python keywords</em> as names for variables, classes, or functions.</p><p>While this is quite useful, it is not recommended simply because it is good practice to use clear concise names within the application and if you want to indicate the type required there are better methods to do so, such as the <em>docstring</em> or <em>type hinting.</em></p><h4>Double Leading Underscore</h4><p>The <em>double leading underscores </em>are used for <a href="https://en.wikipedia.org/wiki/Name_mangling">name mangling</a> in <em>Python</em>.</p><p>What this essentially means in <em>Python</em> is that we use this for class attributes that we do not want subclasses to use and this is done by giving them a name with two <em>leading underscores</em>.</p><p>How the interpreter does this is, at runtime any identifier with a double leading underscore is replaced with <strong>_classname__identifier</strong>, where the <em>classname</em> is the current class name with a leading underscore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d02b5bdeb3fe6908b361c18c10fde84/href">https://medium.com/media/1d02b5bdeb3fe6908b361c18c10fde84/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*6WPXTuH9asHujUeT6s5vFg.png" /></figure><p>This can be very useful for letting subclasses override methods without breaking other method calls. This can be used both for methods and for variables however, it is important to note that this only happens when it is done within the class definition.</p><h4>Double Leading and Post Underscore</h4><p>Whenever we find methods with both a <em>double leading underscore</em> and a <em>double post underscore, </em>these are known as <a href="https://www.tutorialsteacher.com/python/magic-methods-in-python"><em>magic or dunder methods</em></a><em>.</em></p><p>These methods provide special features to the names however, this type of naming should be avoided completely, as it will lead to clashes if we attempt to name variables or methods using this convention.</p><blockquote><strong>“Sometimes it’s better to leave something alone, to pause, and that’s very true of programming.”</strong> — <em>Joyce Wheeler</em></blockquote><h3>The Interpreter</h3><p>Another use of the <em>underscore </em>in <em>Python </em>is in the <em>interpreter</em> and we don’t have to do anything to work with this.</p><p>Essentially the <em>Python Interpreter </em>automatically stores the value of the last executed expression into a variable called <strong>_</strong>.<strong> </strong>We can also assign the value of this variable to another variable as illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*0ifO1BORghQ9mR6r0kdgYQ.png" /></figure><p>This can be quite handy to remember when wanting to work with the result of an expression within the code, without having to assign it yourself.</p><h3><em>Useful Development Tricks</em></h3><p>While we are talking about useful features related to the underscore, there are three other useful features of the <em>underscore in Python, </em>and on discovering these I found it quite handy to use in my code.</p><h4>Using _ in Loops and Comprehensions</h4><p>A handy use for the <em>underscore </em>is as the variable used within loops or comprehensions, while there are times you want the variable to have a descriptive name there are also times where you do not need to worry about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*hVO8emPVRPnNvBgbkEEYjw.png" /></figure><h4>Separating Digits of Numbers</h4><p>This is less of a trick and more of a way to simply improve the readability for the developers.</p><p>Essentially when you end up having long digit numbers, binary, octal, or hex numbers, we can use the <em>underscore </em>to separate it to make it more understandable for humans reading the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*kX0QBNE8yUoWAP5u6ASeFw.png" /></figure><h4>Ignoring Values</h4><p>This is quite a handy usage of the <em>underscore </em>and is particularly useful when we are <em>unpacking</em> variables in <em>Python.</em></p><blockquote><em>What is unpacking?</em></blockquote><p>When we refer to <em>unpacking</em> in <em>Python, </em>we are referring to the action of placing a <em>tuple </em>or <em>list</em> of variables on the left side of an operator, not even requiring the use of parenthesis and allowing the interpreter to automatically assign the variables according to the position in the <em>tuple.</em></p><p>This action can be done with any type of iterable in <em>Python</em>, the only condition being that the iterable yields exactly one item per variable in the receiving <em>tuple</em> or <em>list</em>.</p><p>Now when doing this you may wish to ignore a particular variable or even all the variables except the first and the last, well this is when the <em>underscore </em>is immensely useful as demonstrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*2XsmDLdZVHcjyAWKPkbIJw.png" /></figure><blockquote>Phew! That was a deep-dive!</blockquote><p>If you stuck with me through the entire article thank you and I hope with this research you managed to learn something new, something you may even use in your code.</p><p>You may be wondering why it is I always end up going so deeply into subjects that may appear unimportant, but in my opinion, when you want to learn something properly you need to do the deep dives to understand what is happening underneath it all, no matter how trivial the knowledge may be.</p><p>Do you also tend to do deep dives into what may seem trivial knowledge?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92bf0fa93b9c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/why-am-i-seeing-everywhere-in-python-code-92bf0fa93b9c">Why Am I Seeing _ Everywhere in Python Code?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Recipe Collection: Flat Bread]]></title>
            <link>https://kieron-spearing.medium.com/essential-recipe-collection-flat-bread-15378138cf70?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/15378138cf70</guid>
            <category><![CDATA[bread]]></category>
            <category><![CDATA[bbq]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[life-lessons]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 18:32:54 GMT</pubDate>
            <atom:updated>2022-01-19T18:32:54.628Z</atom:updated>
            <content:encoded><![CDATA[<p>The story of how I almost lost my job in a Michelin Starred restaurant while learning to cook bread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF9z8QMFKsCWrzZaHYcSTg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@yogawifinha">Sweetyoga Justine</a> on <a href="https://unsplash.com/">unsplashed</a></figcaption></figure><p>I’m not sure if it is the aroma, the sweet smell of charred yeast as it cooks over the glowing embers of the fire, or even if it is the way the warm soft bread enters your mouth directly off the <em>braai</em>, but this flatbread has got to be one of my biggest weaknesses.</p><p>If you know anything about <em>South Africa</em>, then you know just how widely integrated the <em>braai, another name for a bbq, is in </em>the South African culture. I am not referring to only the <em>Xhosa, Afrikaans, </em>or any individual culture, but rather the entire country as a whole.</p><p>When you have a <em>braai</em> it generally consists of a few different types of meat, perhaps some vegetables cooked over the fire, and generally, there will always be a form of bread, generally a type of bread known as <em>braaibroodjies</em>.</p><p>In this post, I won’t be talking much about these bundles of join yet, but rather I will be bringing to light a favorite of my own, flatbread.</p><p>It is not as traditional as the <em>braaibroodjies, </em>which I will write a post on soon, but it is as delicious and probably more util in other dishes, for example, I particularly love to cook these whenever I am making a curry-based dish such as <em>bobotie</em> or <em>biryani.</em></p><p>The only tricky part of this recipe, as with all bread is working with the yeast.</p><p>This is one thing I used to struggle with when making bread in the past and I never truly understood what was going wrong until I worked on the pastry section in my first Michelin starred restaurant, I will never forget how much trouble I got into as I confidently made my first bread, not being as careful as I could have been when allowing the yeast to activate.</p><blockquote>I mean the recipe said to use warm water. How was I to know that having the water too warm would kill the yeast rather than activate it?</blockquote><p>I will never forget the look on my head chefs face as I pulled the bread out of the oven, flat as ever, if looks could kill I might have been dead on the spot</p><p>I am truly surprised I didn’t lose my job right then and there, but luckily the senior chef on the pastry section, known as the <em>Chef de Partie, </em>had been expecting something to go wrong considering it was my first time working with bread and he had prepared another load so that we would have bread for service.</p><p>It was that day that I learned you had to be extra careful when working with yeast, and while it is simple to do it is also simple to ruin completely.</p><p>After that day I spent an entire year on that section, just learning the art of making bread and pastry, also known as the art of patience, and I can honestly say I have never made that mistake again.</p><h4>A little note on working with yeast.</h4><p>When you work with yeast there are several things you need to know and be careful with.</p><ol><li><strong>Yeast needs to be proofed or activated.</strong> This is the most important step when working with yeast and it refers to placing the yeast into some <em>warm </em>water or milk, mixing it well, and waiting for five to ten minutes, or until it starts to bubble a bit.</li><li><strong>The proofing liquid needs to be warm, not hot!</strong> As I have done in the past the liquid needs to be warm, but you should be careful not to have it too warm or too cold, if it is too warm it will kill the yeast, however, if too cold it won’t allow the yeast to activate. Ideally, it will be just above blood temperature.</li><li><strong>Yeast loves sugar</strong>. Yeast metabolizes sugar, releasing carbon dioxide into the bread, which is why sometimes even adding a spoonful of sugar into the <em>proofing liquid</em> will help the yeast enormously. Also never leave out the sugar within a recipe, as it is an essential component for the yeast to do its job.</li><li><strong>Yeast hates salt.</strong> Salt can prevent yeast from blooming or even kill the yeast if too much is added. Now you need to use salt to season, but never add it to the proofing liquid. When seasoning you do need to season well before baking as once it is mixed you cannot season again but you want to mix the salt with the flour and then bring the dough all together.</li><li><strong>Keep the dough warm.</strong> While proofing is the most important part of the job, it does happen twice. Once within the liquid as the yeast activates and a second time after the dough has been made and we leave it to rise. Throughout the process, the dough should be left in a warm area so that the yeast can do its work.</li></ol><p>The beauty of this recipe is in its simplicity. It is extremely quick and simple to prepare and almost impossible to get wrong, as long as you work with the yeast correctly it should be a breeze.</p><p>It can also be cooked in either a pan or over the <em>braai </em>but I do suggest the fire as this will give it a lovely smokey, charred flavor.</p><p>It is important to note that when cooking these you want them to be cooked over extremely high heat so that they cook fast, but also create air bubbles inside.</p><h4><strong>Ingredients</strong></h4><p>· 2 tsp Dry Yeast</p><p>· 1 tsp Caster Sugar</p><p>· 125ml Full-Fat Milk</p><p>· 187ml Water</p><p>· 15ml Olive Oil</p><p>· 7g Salt</p><p>· 750g Bread Flour</p><h4><strong>Method</strong></h4><ol><li>In a small pot, mix the water and milk and warm it, but remember not to make it too hot.</li><li>Add the yeast and sugar with the milk and place it to the side for 10 minutes to activate.</li><li>In a large bowl, mix the flour and salt, make a small dip in the center and place the oil into it.</li><li>Slowly add the yeast mix while combining until a dough forms.</li><li>Once you have a dough, turn it out onto a floured surface and start to knead the dough by pushing and folding it, until it reaches a point that when you press it down with a finger it bounces back lightly, this is the stage that is known as <em>medium gluten development</em>.</li><li>Place it into a boil rubbed in olive oil and cover with cling film or a damp cloth.</li><li>Leave in a warm area until the dough has doubled in size.</li><li>Turn the dough out into a floured surface and cut it into eight equal-sized pieces, roll them each into a small ball and then place to the side and cover with a moist cloth and rest for a further twenty minutes.</li><li>Take each ball one at a time on a floured surface and roll them flat until they have a height of about half a centimeter.</li><li>If cooking on a <em>braai</em>, place over the hottest point on the <em>braai</em> and cook for approximately four minutes on either side. If cooking in a pan heat the pan over high heat and cook the same way.</li><li>Serve warm.</li></ol><p>I hope you enjoy this recipe and you have learned from my mistake and can create amazing bread!</p><p>If you have any amazing bread recipes of your own, please comment and share them for me to try.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15378138cf70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flask: How to Create Authentication System Without Flask-Login]]></title>
            <link>https://blog.devgenius.io/flask-how-to-create-authentication-system-without-flask-login-cf804c8152a8?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf804c8152a8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Mon, 17 Jan 2022 19:03:08 GMT</pubDate>
            <atom:updated>2022-01-18T16:54:37.461Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my experience through discovering how to create a decent authentication system without using <em>Flask-Login</em>?</p><figure><img alt="Flask logo" src="https://cdn-images-1.medium.com/max/1024/1*LYjxjmh-LvFQcdwcKJpXEg.png" /></figure><p>I came across this problem when I was working to create an application using a <em>Flask </em>backend<em> </em>and a <em>React </em>frontend. I could not seem to get <em>Flask-Login </em>to work nicely with the <em>React</em> frontend, thus in the end I implemented a different way of achieving this task.</p><p>In this post I will be walking you through the method in which I implemented an authentication system, completely modularized using <em>JSON Web Tokens</em> instead of <em>Flask-Login.</em></p><p>You can find the source code in my <a href="https://github.com/Kwsswart/flask_jwt_authentication_blueprint">Github</a>.</p><h3><strong>The problem</strong></h3><p>I was building an application in <em>Flask </em>and<em> React, </em>in which I used <em>Flask</em> as a completely separate <em>API </em>while <em>React</em> served the front-end.</p><p>I did not however foresee how difficult it is to integrate an authentication system with <em>Flask-Login</em> when the front-end is not served by the <em>Flask server.</em></p><p>While being an amazing extension to use with any normal <em>Flask</em> application, <em>Flask-Login</em> doesn’t seem to have an easy way to utilize it within a <em>Flask</em> backend that doesn’t serve its templates but rather is being called as an <em>API</em>.</p><p>After doing a lot of research and head-banging, I could not find a solution that I was satisfied with and in the end, I decided to give up on the idea of integrating this amazing extension and rather find a way to recreate this type of authentication without it.</p><h4>What this entails</h4><p>To put it simply, I needed to find a way to recreate the common features of <em>Flask-Login</em>, the main ones being:</p><ol><li>Find a way to log the user in.</li><li>Find a way to log the user out.</li><li>Find a way to create a user session.</li><li>Find a way to check the user session to close off certain routes, when not authenticated.</li></ol><h3>The Solution</h3><p>As I started trying to figure out how I would go about this I decided that it would be best to start with simply setting up a standard <em>application factory</em> and with that creating the solution in the form of a blueprint, that way it could be completely modularized and reusable.</p><p>I had already done some research and decided that it would be best to use <em>JSON Web Tokens</em> to achieve the result as the <em>API </em>would be returning all information via <em>JSON</em> and <em>Flask </em>has a great extension to work with this form of authentication.</p><p>The process I followed is below however if you are unfamiliar with the <a href="https://flask.palletsprojects.com/en/2.0.x/blueprints/"><em>Flask blueprints</em></a> I suggest you take a look at <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-a-better-application-structure">this tutorial</a> before continuing.</p><h4>Setting up the base application factory</h4><p><strong>· First thing I had to do was set up the file structure of the application.</strong></p><p>This is the basic file structure of a flask application using blueprints. The entire <em>auth/</em> directory will contain the blueprint components.</p><pre>authentication_example/<br>    app/<br>        auth/<br>            __init__.py<br>            helpers.py<br>            routes.py<br>            models.py<br>        __init__.py<br>    api.py<br>    config.py</pre><p><strong>· Once I had the file structure set up, I needed to create a virtual environment and activate said virtual environment.</strong></p><pre>python -m venv venv<br>source venv/bin/activate <br>venv/Scripts/activate // Windows command prompt</pre><p><strong>·Once in the environment, I needed to install the dependencies and packages.</strong></p><pre>pip install flask flask-sqlalchemy flask-cors flask-migrate flask-jwt-extended python-dotenv bcrypt</pre><p>The reasons for using these different dependencies are:</p><p><strong>Flask-SQLAlchemy </strong>— This is the extension that allows us to work with SQLAlchemy as our <em>ORM.</em></p><p><strong>Flask-Migrate</strong> — This is the extension that will handle all database migrations. To learn more about this the creator of the extension has this <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database">tutorial</a>.</p><p><strong>Flask-Cors</strong> — This is the extension that will handle <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing</a>, this is a simple way of making cross-origin <em>AJAX</em> possible.</p><p><strong>Flask-JWT-Extended </strong>— This is the extension that will add the support to handle JSON Web Tokens within our Flask application.</p><p><strong>Python-dotenv</strong> — This is the package that will allow us to keep all our sensitive information in a separate .env file and import them into the application.</p><p><strong>bcrypt</strong> — This is the package that will handle the password security</p><p><strong>· Now that I had all the dependencies installed I could start to set up the application.</strong></p><p>The first thing I wanted to do was create a Config object in the config.py that could import all the required variables into the application.</p><pre><strong><em>authentication_example/config.py<br></em></strong></pre><pre>import os</pre><pre>from dotenv import load_dotenv<br></pre><pre>basedir = os.path.abspath(os.path.dirname(__file__))</pre><pre>load_dotenv(os.path.join(basedir, &#39;.env&#39;))</pre><pre>class Config(object):</pre><pre>    SECRET_KEY = os.environ.get(&#39;SECRET_KEY&#39;) or &#39;you-will-never-guess&#39;</pre><pre>    SQLALCHEMY_DATABASE_URI = os.environ.get(&#39;DATABASE_URL&#39;) or \</pre><pre>        &quot;sqlite:///&quot; + os.path.join(basedir, &quot;app_database.db&quot;)</pre><pre>    JWT_SECRET_KEY = os.environ.get(&#39;JWT_SECRET_KEY&#39;) or &quot;super-secret-key&quot;</pre><pre>    JWT_BLACKLIST_ENABLED = True</pre><pre>    JWT_BLACKLIST_TOKEN_CHECKS = [&quot;access&quot;, &quot;refresh&quot;]</pre><p><strong>· Once I has this I decided to set up the </strong><a href="https://flask.palletsprojects.com/en/2.0.x/patterns/appfactories/"><strong>application factory</strong></a><strong>.</strong></p><p>I did this in three separate files: <em>api.py, app/__init__.py, </em>and<em> app/auth/models.py</em></p><pre><strong><em>authentication_example/app/__init__.py<br></em></strong></pre><pre>import os</pre><pre>from flask import Flask</pre><pre>from flask_cors import CORS</pre><pre>from flask_migrate import Migrate</pre><pre>from flask_jwt_extended import JWTManager</pre><pre>from flask_sqlalchemy import SQLAlchemy</pre><pre>from config import Config</pre><pre>cors = CORS()</pre><pre>db = SQLAlchemy()</pre><pre>migrate = Migrate()</pre><pre>jwt = JWTManager()</pre><pre>def create_app(config_class=Config):</pre><pre>    app = Flask(__name__)</pre><pre>    app.config.from_object(Config)</pre><pre>    db.init_app(app)</pre><pre>    cors.init_app(app)</pre><pre>    migrate.init_app(app, db)</pre><pre>    jwt.init_app(app)<br></pre><pre>    return app</pre><pre>from app.auth import models</pre><p>The <em>create_app() </em>function is what is known as a factory function and essentially what it does, when called, is create a <em>Flask</em> instance and use the config from earlier to initialize all the <em>flask extensions,</em> and then returns the application.</p><p>The <em>models</em> are imported at the bottom of the file to prevent circular dependencies.</p><pre><strong><em><br>authentication_example/api.py<br></em></strong></pre><pre>from app import create_app, db</pre><pre>from app.auth.models import *</pre><pre>from flask import Flask</pre><pre>app = create_app()</pre><pre>@app.shell_context_processor</pre><pre>def make_shell_context():</pre><pre>    return {</pre><pre>        &#39;db&#39;: db,</pre><pre>        &#39;Users&#39;: Users,</pre><pre>    }</pre><pre>if __name__ == &#39;__main__&#39;:</pre><pre>    app.run(debug=True)</pre><p>In this file, I am calling the <em>create_app()</em> function, but I am also setting up the shell context, which is extremely useful as it will allow you to interact with the database and the application during testing simply by running:</p><pre>flask shell</pre><p>The model is a representation of the table in the database so that the <em>ORM</em> can easily work with it from within <em>Flask.</em></p><pre><strong><em>authentication_example/app/auth/models.py<br></em></strong></pre><pre>import os</pre><pre>from app import db</pre><pre>class Users(db.Model):</pre><pre>    id = db.Column(&#39;user_id&#39;, db.Integer, primary_key=True)</pre><pre>    username = db.Column(db.String(24))</pre><pre>    pwd = db.Column(db.String(64))<br></pre><pre>    def save(self):<br>        db.session.add(self)</pre><pre>        db.session.commit()</pre><pre>    def __init__(self, username, pwd):</pre><pre>        self.username = username</pre><pre>        self.pwd = pwd</pre><pre>    def __repr__(self):</pre><pre>        return &quot;&lt;User: Username - {}; password - {};&gt;&quot;.format(self.username, self.pwd)</pre><p>In this part, I am simply setting up a basic <em>User </em>model that will be needed for the authentication system. Remember that once done you will need to handle the database migrations as done in the <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database">tutorial</a>.</p><pre>flask db init<br>flask db migrate -m &quot;Users table&quot;<br>flask db upgrade</pre><h4>Creating the authentication blueprint</h4><p>Now that I had the application set up and ready to work with I had to register the blueprint so that the application could import it and all the components I needed to implement.</p><p>This blueprint will essentially consist of the routes, the models, and the helper functions.</p><p>This is the way I prefer to work with blueprints so that I can separate the routes logic, database logic, and any other logic that I decided is needed.</p><p><strong>· First thing I had to do is to register the blueprint.</strong></p><p>I did this in the two <em>__init__.py</em> files.</p><pre><strong><em>authentication_example/app/auth/__init__.py<br></em></strong></pre><pre>from flask import Blueprint<br></pre><pre>bp = Blueprint(&#39;auth&#39;, __name__)<br></pre><pre>from app.auth import routes</pre><p>In this file, I am simply creating an instance of <em>Blueprint</em> with the label <em>auth.</em></p><pre><strong><em>authentication_example/app/__init__.py</em></strong></pre><pre>import os</pre><pre>from flask import Flask</pre><pre>from flask_cors import CORS</pre><pre>from flask_migrate import Migrate</pre><pre>from flask_jwt_extended import JWTManager</pre><pre>from flask_sqlalchemy import SQLAlchemy</pre><pre>from config import Config</pre><pre>cors = CORS()</pre><pre>db = SQLAlchemy()</pre><pre>migrate = Migrate()</pre><pre>jwt = JWTManager()</pre><pre>def create_app(config_class=Config):</pre><pre>    app = Flask(__name__)</pre><pre>    app.config.from_object(Config)</pre><pre>    db.init_app(app)</pre><pre>    cors.init_app(app)</pre><pre>    migrate.init_app(app, db)</pre><pre>    jwt.init_app(app)</pre><pre><strong>    from app.auth import bp as auth_bp</strong></pre><pre><strong>    app.register_blueprint(auth_bp)</strong></pre><pre>    return app</pre><pre>from app.auth import models</pre><p>With the two added lines in bold, I am registering the blueprint as the application is created in the application factory.</p><p><strong>· Once I had the blueprint registered I was free to start working on the authentication system.</strong></p><p>The first thing I needed to do to implement <a href="https://jwt.io/introduction">JSON Web Tokens</a> into our application is to create a table in our database to store the blacklisted tokens.</p><pre><strong><em>authentication_example/app/auth/models.py</em></strong></pre><pre>...</pre><pre>class InvalidToken(db.Model):</pre><pre>    __tablename__ = &quot;invalid_tokens&quot;</pre><pre>    id = db.Column(db.Integer, primary_key=True)</pre><pre>    jti = db.Column(db.String)</pre><pre>    def save(self):</pre><pre>        db.session.add(self)</pre><pre>        db.session.commit()</pre><pre>    @classmethod</pre><pre>    def is_invalid(cls, jti):</pre><pre>        &quot;&quot;&quot; Determine whether the jti key is on the blocklist return bool&quot;&quot;&quot;</pre><pre>    query = cls.query.filter_by(jti=jti).first()</pre><pre>    return bool(query)</pre><p>Once this was done, I had to remember to migrate the database once more:</p><pre>flask db init<br>flask db migrate -m &quot;Invalid Tokens table&quot;<br>flask db upgrade</pre><p><strong>· Now that the database is ready I could create the helper functions.</strong></p><p>All of these are essentially there to separate the routes from the logic for each function, this also helps to avoid repeating code through separate routes.</p><pre><strong><em>authentication_example/app/auth/helpers.py</em></strong></pre><pre>from app import db</pre><pre>from app.auth.models import Users</pre><pre>from bcrypt import hashpw, gensalt, checkpw</pre><pre>from base64 import b64encode</pre><pre>from hashlib import sha256</pre><pre>def get_users():</pre><pre>    users = Users.query.all()</pre><pre>    return [{&quot;id&quot;: i.id, &quot;username&quot;: i.username, &quot;pwd&quot;: i.pwd} for i in users]</pre><pre>def get_user(user_id):</pre><pre>    users = Users.query.all()</pre><pre>    user = list(filter(lambda x: x.id == user_id, users))[0]</pre><pre>    return {&quot;id&quot;: user.id, &quot;username&quot;: user.username, &quot;pwd&quot;: user.pwd}</pre><pre>def add_user(username, pwd):</pre><pre>    if username and pwd :</pre><pre>        try:</pre><pre>            user = Users(username, pwd)</pre><pre>            user.save()</pre><pre>            return True</pre><pre>        except Exception as e:</pre><pre>            print(e)</pre><pre>            return False</pre><pre>    else:</pre><pre>        return False</pre><pre>def remove_user(user_id):</pre><pre>    if user_id:</pre><pre>        try:</pre><pre>            user = Users.query.get(user_id)</pre><pre>            db.session.delete(user)</pre><pre>            db.session.commit()</pre><pre>            return True</pre><pre>        except Exception as e:</pre><pre>            print(e)</pre><pre>            return False</pre><pre>    else:</pre><pre>        return False</pre><pre>def encrypt_pwd(pwd):</pre><pre>    return hashpw(b64encode(sha256(pwd.encode()).digest()), gensalt()).decode()</pre><pre>def check_pwd(x, y):</pre><pre>    &quot;&quot;&quot;</pre><pre>    Check whether password hashed matches:</pre><pre>    * arg x** password to check</pre><pre>    * arg y** original hashed password</pre><pre>    &quot;&quot;&quot;</pre><pre>    return checkpw(b64encode(sha256(x.encode()).digest()), y.encode())</pre><p>Each of these functions simply performs their function or return <em>False</em>. The entire idea is to call said function from each route as required, thus separating the logic of the action from the route.</p><p><strong>· Now I could finally go through the set up of the routes themselves.</strong></p><p>All of the following was implemented in the <em>routes.py</em></p><pre><strong><em>authentication_example/app/auth/routes.py<br></em></strong></pre><pre>from app import jwt</pre><pre>from app.auth import bp</pre><pre>from app.auth.helpers import *</pre><pre>from app.auth.models import Users, InvalidToken</pre><pre>from flask import request, jsonify</pre><pre>from flask_jwt_extended import create_access_token,       create_refresh_token, get_jwt_identity, get_jwt, jwt_required</pre><pre>@jwt.token_in_blocklist_loader</pre><pre>def check_if_blacklisted_token(data, decrypted):</pre><pre>    &quot;&quot;&quot;</pre><pre>    Decorator designed to check for blacklisted tokens</pre><pre>    &quot;&quot;&quot;</pre><pre>    jti = decrypted[&#39;jti&#39;]</pre><pre>    return InvalidToken.is_invalid(jti)</pre><p>The first thing required is a decorator that will be used to determine whether the token is valid or not. Once this is done, I wanted to create the <em>register and login routes:</em></p><pre>@bp.route(&quot;/api/login&quot;, methods=[&quot;POST&quot;])</pre><pre>def login():</pre><pre>    try:</pre><pre>        username = request.json[&quot;username&quot;]</pre><pre>        pwd = request.json[&quot;pwd&quot;]</pre><pre>        if username and pwd:</pre><pre>            user = list(filter(lambda x: x[&quot;username&quot;] == username and check_pwd(pwd, x[&quot;pwd&quot;]), get_users()))</pre><pre>            if len(user) == 1:</pre><pre>                token = create_access_token(identity=user[0][&quot;id&quot;])</pre><pre>                refresh_token = create_refresh_token(identity=user[0][&quot;id&quot;])</pre><pre>                return jsonify({&quot;token&quot;: token, &quot;refreshToken&quot;: refresh_token})</pre><pre>            else:</pre><pre>                return jsonify({&quot;error&quot;: &quot;Invalid credentials&quot;})</pre><pre>        else:</pre><pre>            return jsonify({&quot;error&quot;:&quot;Invalid Form&quot;})</pre><pre>    except:</pre><pre>        return jsonify({&quot;error&quot;: &quot;Invalid Form&quot;})</pre><pre>@bp.route(&quot;/api/register&quot;, methods=[&quot;POST&quot;])</pre><pre>def register():</pre><pre>    try:</pre><pre>        pwd = encrypt_pwd(request.json[&#39;pwd&#39;])</pre><pre>        username = request.json[&#39;username&#39;]</pre><pre>        users = get_users()</pre><pre>        if len(list(filter(lambda x: x[&quot;username&quot;] == username, users))) == 1:</pre><pre>            return jsonify({&quot;error&quot;: &quot;Invalid Form&quot;})</pre><pre>        add_user(username, pwd)</pre><pre>        return jsonify({&quot;success&quot;: True})</pre><pre>    except Exception as e:<br>        return jsonify({&quot;error&quot;: str(e)})</pre><p>Here there have two very simple end-points.</p><p>The <em>login</em> end-point takes the <em>username</em> and the <em>password</em> and verifies them using the helper function, if the credentials are correct it will return a <em>JWT token</em> for them to use with the session created.</p><p>The <em>register</em> end-point simply checks to ensure the <em>username</em> has not already been used and then adds the user to the database.</p><p><strong>· Once I had these end-points there were a few more functionalities I needed to implement:</strong></p><ol><li>A way for the frontend to check if the token is expired</li><li>A way for the frontend to refresh the token if it is expired.</li><li>A way for the frontend to check the current user, as is provided by <em>Flask-Login.</em></li><li>A way to invalidate the token, thus simulate a logout system.</li></ol><p>Now that I had the <em>login </em>system and the check for blacklisted tokens in place I could use the<em> @jwt_required() </em>decorator to ensure any route that I only wanted to allow access to an authorized user is protected.</p><p>With this it was easy to implement these four requirements in four separate routes:</p><pre>@bp.route(&quot;/api/checkiftokenexpire&quot;, methods=[&quot;POST&quot;])</pre><pre>@jwt_required()</pre><pre>def check_if_token_expire():</pre><pre>    return jsonify({&quot;success&quot;: True})</pre><pre>@bp.route(&quot;/api/refreshtoken&quot;, methods=[&quot;POST&quot;])</pre><pre>@jwt_required(refresh=True)</pre><pre>def refresh():</pre><pre>    identity = get_jwt_identity()</pre><pre>    token = create_access_token(identity=identity)</pre><pre>    return jsonify({&quot;token&quot;: token})</pre><pre>@bp.route(&quot;/api/getcurrentuser&quot;)</pre><pre>@jwt_required()</pre><pre>def current_user():</pre><pre>    uid = get_jwt_identity()</pre><pre>    return jsonify(get_user(uid))</pre><pre>@bp.route(&quot;/api/logout/refresh&quot;, methods=[&quot;POST&quot;])</pre><pre>@jwt_required()</pre><pre>def logout():</pre><pre>    &quot;&quot;&quot;</pre><pre>    End-point to invalidate the token.</pre><pre>    Can be used with both log the user out or for the frontend to call after refreshing the token.</pre><pre>    &quot;&quot;&quot;</pre><pre>    jti = get_jwt()[&quot;jti&quot;]</pre><pre>    try:</pre><pre>        invalid_token = InvalidToken(jti=jti)</pre><pre>        invalid_token.save()</pre><pre>        return jsonify({&quot;success&quot;: True})</pre><pre>    except Exception as e:</pre><pre>        print(e)</pre><pre>        return jsonify({&quot;error&quot;: str(e)})</pre><p><strong>· Having implemented these four end-points I was left with one last thing required for the authentication system to be fully functional: Removal of old users.</strong></p><p>Luckily I aready haa all the logic required, all I needed to do is create a single route to handle this.</p><pre>@bp.route(&quot;/api/deleteaccount&quot;, methods=[&quot;DELETE&quot;])</pre><pre>@jwt_required()</pre><pre>def delete_account():</pre><pre>    try:</pre><pre>        user = get_user(get_jwt_identity())</pre><pre>        remove_user(user.id)</pre><pre>        return jsonify({&quot;success&quot;: True})</pre><pre>    except Exception as e:</pre><pre>        return jsonify({&quot;error&quot;: str(e)})</pre><h4>And just like that, I had the entire authentication system, ready to use for any <em>API</em> that I may build in <em>Flask</em> using <em>JSON Web Token</em> authentication.</h4><p>The beautiful part about having this set up in the form of a blueprint is that whenever wanting to set up a new <em>API</em> using a similar authentication system you can simply bring the <em>auth/</em> directory into the application, register the blueprint, then migrate the database and you are ready to go.</p><p>The blueprint is in my <a href="https://github.com/Kwsswart/flask_jwt_authentication_blueprint">Github</a> and if you wish to use it feel free to clone the repository.</p><p>There are many ways to do the same thing in computer science, and I love to try to find new different ways that could potentially be better than that which I have done previously.</p><p>Have you found another way to implement something similar?</p><p>If so please leave a comment explaining how, I would love to see how you have managed to do it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf804c8152a8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/flask-how-to-create-authentication-system-without-flask-login-cf804c8152a8">Flask: How to Create Authentication System Without Flask-Login</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to HTTP and HTTPS]]></title>
            <link>https://kieron-spearing.medium.com/a-guide-to-http-and-https-a0d96dc5532e?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d96dc5532e</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[tsl]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 18:33:02 GMT</pubDate>
            <atom:updated>2022-01-15T18:33:02.928Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered what is going on underneath the hood as you use the internet?</p><figure><img alt="Laptop with the matrix green letters" src="https://cdn-images-1.medium.com/max/1024/1*w0_v-dXvQyX7z0SWnpepXA.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@markusspiske">Markus Spiske</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Have you ever wondered how is it that the internet works? What is happening as you interact with websites on the internet?</p><p>If you are anything like me, you always get this constant itch as you learn something new. I find that as I learn something I tend to get frustrated until I understand the inner workings of it.</p><p>Why is this? I am not sure, but I guess it just helps me satisfy the burning curiosity I feel constantly.</p><p>In this post, I will explain what is HTTP and the difference between it and HTTPS, as well as discuss my finding at a low level to bring to light how this marvelous technology keeps the internet flowing</p><h3>What are HTTP and HTTPS</h3><p>At the most basic level, what happens as you interact with a web page is the browser, also referred to as the client, communicates with the server through various <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods"><em>HTTP</em> request methods</a>, each one performing one action or another.</p><p><em>HTTP </em>is<em> </em>the abbreviation for<em> hypertext transfer protocol.</em> This is the main method by with data is transferred over the internet. The data is stored on servers, which are then served to the client as the user requests them via <em>HTTP</em> request methods.</p><p>There is however a big issue with an <em>HTTP </em>connection, the data being transferred over this connection is not encrypted, thus it is not ideal to transfer sensitive information.</p><p>That is where <em>HTTPS</em> comes into the equation.</p><p><em>HTTPS</em> is the abbreviation for <em>secure hypertext transfer protocol </em>and essentially functions the same as<em> HTTP</em>, with the difference that it tends to use an <em>SSL certificate</em> and <em>TSL handshake</em></p><h3>How does HTTPS work and why is it more secure than HTTP?</h3><p>Essentially the main reason <em>HTTPS </em>is more secure than <em>HTTP</em> is that it uses a <em>TSL handshake</em>, which is the successor of <a href="https://www.cloudflare.com/learning/ssl/what-is-an-ssl-certificate/"><em>SSL</em></a>, to secure the connection.</p><p><em>SSL </em>is the abbreviation for<em> secure sockets layer </em>and this was the original encryption protocol developed for <em>HTTP</em> and was what created a secure encrypted connection between the client and the server and allowed data transfer to be secure.</p><p><em>TSL</em> is the abbreviation for <em>transport layer security </em>and a <em>TSL</em> handshake takes place whenever a user navigates a website over <em>HTTPS</em> and the browser first begins to connect to the website’s origin server.</p><p>Essentially what happens during a <em>TSL handshake</em> is that the client and server communicate and agree on the encryption protocol before establishing the initial connection, then once this connection has been established they use this encryption for all subsequent communication in the session.</p><h3><strong>The Steps of a TSL handshake</strong></h3><p>During the process of a <em>TSL handshake</em> the client and server communicate providing necessary information to create secure symmetric encryption and while the exact steps may vary depending on the key exchange algorithm used the general process is:</p><ol><li><strong>The client’s hello message.</strong> This will essentially include details on what the client supports, i.e: the <em>TSL</em> version and cipher suites. It will also include a random string of bytes, known as <em>client random.</em></li><li><strong>The server hello message.</strong> This will contain the server’s <em>SSL certificate</em>, the server’s chosen cipher suite, and another random string of bytes, known as <em>server random.</em></li><li><strong>Authentication. </strong>This is the step in which the client verifies the server’s <em>SSL certificate</em> with the certificate authority that issued it.</li><li><strong>The premaster secret.</strong> The client then sends one more random string of bytes, known as <em>the</em> <em>premaster secret</em>. This secret is encrypted with the public key that the client retrieved from the server’s <em>SSL certificate</em> and can only be decrypted with the private key by the server.</li><li><strong>The decryption of the premaster secret.</strong> The server decrypts the premaster secret.</li><li><strong>Creation of session keys.</strong> At this point, both the client and the server generate session keys from the client random, server random, and the premaster secret. If done correctly both should separately arrive at the same result.</li><li><strong>The client is ready.</strong> The client sends a message indicating that it is finished that is encrypted with the generated session key.</li><li><strong>The server is ready. </strong>The server sends a message indicating that it is finished that is encrypted with the generated session key.</li><li><strong>Secure symmetric encryption complete.</strong> Once we reach this point the handshake is completed and communication continues using the session keys.</li></ol><p>During the entire process, the most critical step is that of authentication, where the client verifies the <em>SSL certificate</em> to confirm the identity of the owner of the webserver.</p><p>In the end, the result of this entire process is that the client and the server can set up a deeply encrypted connection to pass data securely, one which requires multiple parts of a chain of communication to successfully generate the key required to decrypt the connection.</p><p>Having learned all of this it is easy to understand why it has become a common thing to see websites using <em>HTTPS </em>instead of<em> HTTP </em>and also why users tend to display more trust in a web server using <em>HTTPS.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d96dc5532e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Recipe Collection: Apple Chutney]]></title>
            <link>https://kieron-spearing.medium.com/essential-recipe-collection-apple-chutney-1e66008deb44?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e66008deb44</guid>
            <category><![CDATA[food-and-beverage]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[essentials]]></category>
            <category><![CDATA[south-africa]]></category>
            <category><![CDATA[recipe]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 15:55:45 GMT</pubDate>
            <atom:updated>2022-01-14T16:21:58.033Z</atom:updated>
            <content:encoded><![CDATA[<p>The slightly spicy, acidic, and sweet kick this provides will help spruce up any dish.</p><figure><img alt="A variety of apples in a fresh produce market" src="https://cdn-images-1.medium.com/max/1024/1*bqomyNGFSYCUYdQffwo53A.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@geekybill">Lauren Rose</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Being an essential ingredient for many curry-based recipes, it comes as no surprise that South Africans have integrated many different types of chutney into their diet.</p><p>This particular recipe is one that I have worked on over the years using both my upbringing in South Africa and my experience in cooking and in my opinion it stands miles above the rest.</p><p>The sweet acidic apples work amazingly with the spices and can be used in any recipe that calls for chutney.</p><p>The most important thing to remember when making any type of preserve is to be as clean as physically possible.</p><p>When made well and maintaining a clean organized system all preserves can last for months on end, this recipe, in particular, matures well.</p><p><strong>Ingredients</strong></p><p>· 1.5kg Granny Smith Apples, Peeled and chopped</p><p>· 1 Large Onion, Peeled and sliced.</p><p>· 250g Raisins</p><p>· 150g Brown Sugar.</p><p>· 10g Fennel Seeds</p><p>· 1 stick Cinnamon</p><p>· 10g Mustard Seeds</p><p>· 200ml Cider Vinegar</p><p>· 1 tbsp Olive Oil</p><p><strong>Method</strong></p><ol><li>Place a large pot over low heat.</li><li>Add the oil and the onions and sweat them until very soft, but with no color.</li><li>Once the onions are soft, add the apple and sweat until cooked and soft, then turn the heat up to medium heat and allow to caramelize slightly.</li><li>Place the seeds and cinnamon inside a fabric bag similar to a teabag and secure shut.</li><li>Add the sugar, seeds, raisins and allow to cook for 10–15 minutes.</li><li>Add the vinegar and allow to cook until it has a consistency of chutney.</li><li>Place directly in a sterilized jar place and fasten the lid and allow to cool at room temperature before storing in the fridge.</li><li>The chutney can last for months, but once a jar is opened you should consume it within a month.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e66008deb44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I went from professional chef to a self-taught full-stack developer in one year.]]></title>
            <link>https://medium.com/geekculture/how-i-went-from-professional-chef-to-a-self-taught-full-stack-developer-in-one-year-my-story-168b4e339189?source=rss-9d42785e3571------2</link>
            <guid isPermaLink="false">https://medium.com/p/168b4e339189</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[career-change]]></category>
            <dc:creator><![CDATA[Kieron Spearing]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 18:32:51 GMT</pubDate>
            <atom:updated>2022-01-18T06:17:40.787Z</atom:updated>
            <content:encoded><![CDATA[<p>My journey from a professional chef in Michelin star restaurants to a full-stack developer in one year.</p><figure><img alt="laptop with visual studio code open and script running while the city is alive with people" src="https://cdn-images-1.medium.com/max/1024/1*uUv3yOK8z9TbG8Dz_gHwXw.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@seanlimm">Sean Lim</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>I am a self-taught full-stack developer who has been working in the industry for two years.</p><p>Although having a passion for food and cooking, I have always had an interest in programming and the way technology functions at a basic level. I have never had any formal training in either cooking or technology, but I have always had a love for learning and natural curiosity.</p><p>This post will discuss how I went from being a professional chef to a full-stack developer while working a full-time job.</p><p><strong><em>I have never been to any university nor have I done a programming Bootcamp.</em></strong></p><p>It all started when I finally decided the life of being a professional chef wasn’t for me.</p><blockquote>Why did I decide this?</blockquote><p>I guess this came from many factors, but the main one being that I wanted to have a better lifestyle and while it is true that you can work in a hotel or in a lower level restaurant to achieve this goal, my pride wouldn’t allow me to take this route after so many years working in high-level cuisine.</p><p>Thus I began to think about how I could do this while still keeping the money flowing as it is quite impossible to have time to study while working twelve to sixteen hours a day.</p><p>Luckily, living in Madrid, Spain at the time and being a native English speaker there is a lot of demand for English teachers for the general public and so with the first piece of the puzzle solved I sought a job within an English Academy.</p><h3>Then the covid-pandemic hit the world.</h3><p>During the three months that we were trapped at home, I decided to use the lack of commute time to my benefit, all of a sudden the two hours I had to be going to and from work turned to zero. I still had to work for eight hours a day but I wasn’t complaining as now I could finish work and immediately work on improving myself.</p><p>It was at the same time that my girlfriend stumbled onto a free online course offered by <a href="https://programs.edx.org/partner-harvard?g_acctid=724-505-4034&amp;g_campaign=gs-b2c-nonbrand-us-can-partner-harvard-core&amp;g_campaignid=14747888370&amp;g_adgroupid=131268844687&amp;g_adid=548012918856&amp;g_keyword=harvard%20online%20course&amp;g_keywordid=kwd-1328603686&amp;g_network=g&amp;utm_source=google&amp;utm_campaign=gs-b2c-nonbrand-us-can-partner-harvard-core&amp;utm_medium=cpc&amp;utm_term=harvard%20online%20course&amp;hsa_acc=7245054034&amp;hsa_cam=14747888370&amp;hsa_grp=131268844687&amp;hsa_ad=548012918856&amp;hsa_src=g&amp;hsa_tgt=kwd-1328603686&amp;hsa_kw=harvard%20online%20course&amp;hsa_mt=b&amp;hsa_net=adwords&amp;hsa_ver=3&amp;gclid=Cj0KCQiAuP-OBhDqARIsAD4XHpcBzlDSP0iUWHANIcuIKvuY4Rvm_VupL7f0LLGELUUHN9yMtovqqSYaAi55EALw_wcB">Harvard University</a> called <a href="https://pll.harvard.edu/course/cs50-introduction-computer-science?delta=0"><em>CS50 Introduction to Computer Science</em></a><em>.</em></p><blockquote>I was amazed! Could this be the answer I was looking for?</blockquote><p>And so with a borderline obsessive dedication, I started the course and I loved every minute of it as it took me through learning the basic concepts like <em>arrays, data types, memory management in C.</em></p><p>Then<em>, </em>in the fifth week of the course, they introduced <em>Python</em> and I quickly discovered that the language in which I was learning wasn’t as important as the concepts I learnt.</p><p>I continued along this path until it came to the final project in which I chose to create a web application in <em>Flask. </em>But I was unhappy with my current level of knowledge and ability to create the application well.</p><p><strong><em>Once more I found my pride and dedication to always do things to the best of my ability or not at all holding me back.</em></strong></p><p>Instead of finishing the course, I sought out more information in <em>Flask</em> and this is when I found <a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world"><em>The Flask Mega-Tutorial by Miguel Grinberg</em></a><em>.</em></p><p>This tutorial was amazing and through the twenty-three parts it explained everything I felt I needed basic and advanced techniques, it even went through how to host an application on <em>linux, docker </em>and<em> heroku.</em></p><p>By the time I finished working with this tutorial I truly felt that I was ready to start the application I needed to finish the course. Unfortunately for me, at this time the academy had asked us to return to the office to teach in person but I didn’t let this deter me.</p><p><strong><em>I would program in every spare minute I had, I was borderline obsessed.</em></strong></p><p>In making the application for the course, which took me a good three months, I learnt something I hadn’t realized previously. You learnt a lot more in creating an application from scratch than you could in any course.</p><p>This is because rather than following along with somebody else’s instructions or only creating what the project required, you have complete free reign and usually will end up continuously adding features and running into problems that you have to figure out on your own.</p><p>Granted you can always go on <em>StackOverflow</em>, but that’s true in the real world as well. In the end, you have to learn not only how to ask the correct questions, but also how to research the correct answers.</p><p>With this newfound knowledge and confidence in my abilities with <em>Flask,</em> I decided to move forth and learn how to use <em>Flask</em> with <em>React</em>, which involved substantially different practices to a standard <em>Flask </em>application.</p><p>In doing this I learnt not only how to create an <em>API</em> but also how to interact with an <em>API </em>externally and how to keep things modularized within an application.</p><p><strong><em>By this point, I had already been programming for 10 months.</em></strong></p><p>I had developed an obsession and I was continuously creating personal projects, but I also felt that it was time for me to start applying for jobs as the combination of ten hours of work and eight hours studying was starting to get to me.</p><p>I wanted to be programming full-time.</p><p>I probably sent over two hundred applications and only had two responses, luckily one of the two responses was impressed with how I had done the change by that point and decided to give me a technical trial.</p><p>In this technical trial, they asked me to do something I had never done before and wasn’t even remotely within my ability set.</p><h4>Choose one of three websites and build a web scraper to collect data in an automated fashion.</h4><p>They had given me a week from the Friday of the interview.</p><p>I spend that entire Friday night researching how to build a web scraper and how to avoid getting blocked. Then I spent the entire weekend building not only one web scraper but all three.</p><p>I then decided to go one step further and connect all three to a <em>Flask REST API</em> and host it so that they could access it and run the scrapers and receive the data scraped from the <em>API</em> directly, rather than just receiving the file from me along with the code.</p><h3><strong>I got my first job in the industry!</strong></h3><p>I had finally done it! After eleven months of working extremely hard, I had received my first job in the industry as a <em>junior developer</em>.</p><p>I took the opportunity without even a glance at the money offered and decided to continue pushing forward. I worked there for six months learning as much as I would and continuing the habit of programming in my time off.</p><p>I learned a lot during my six months on the job and quickly became confident in creating web scrapers and handling data.</p><p><strong><em>It was then that opportunity came knocking at the door once more.</em></strong></p><p>After six months in that company, I received an email asking whether I would be interested in a company that was doing similar work to what I was doing but on a much larger scale.</p><p>I decided that I had to hear what they had to say. During the interview process, it became clear to me that this was an opportunity I couldn’t pass up.</p><p>The team I would be working with had so much experience I could learn from and the company was working on projects that kept me excited, thus when I received the offer I had to say yes!</p><p><strong><em>Where am I now?</em></strong></p><p>Today I am still with said company, working hard on many interesting projects and continuously learning and improving on my current skills to propel me continuously forward in this new exciting industry.</p><p>I have also turned some of my attention to combining vastly different passions in the form of writing with the hope that I may pass my knowledge and experience in the different fields onto others as well as improve my communication skills.</p><p><strong><em>So what is the secret to changing your career fast and successfully?</em></strong></p><p>The truth is there is no secret.</p><p>The important thing is to remember you do not need a university degree or spend a lot of money to change your career. There are many resources out there for you, all it takes is hard work and determination along with the understanding that no matter how desperate or exasperating it may get, in the end, it is true what they say.</p><h4>Hard work pays off.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168b4e339189" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-i-went-from-professional-chef-to-a-self-taught-full-stack-developer-in-one-year-my-story-168b4e339189">How I went from professional chef to a self-taught full-stack developer in one year.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>