<?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 Andrew Klatzke on Medium]]></title>
        <description><![CDATA[Stories by Andrew Klatzke on Medium]]></description>
        <link>https://medium.com/@andrewklatzke?source=rss-b3b06a6986a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2dPpiUOgPcKi-YFW1H9ZAA.jpeg</url>
            <title>Stories by Andrew Klatzke on Medium</title>
            <link>https://medium.com/@andrewklatzke?source=rss-b3b06a6986a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:11:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewklatzke/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[Many, Many Examples of Using Reduce in JavaScript]]></title>
            <link>https://medium.com/@andrewklatzke/many-many-examples-of-using-reduce-in-javascript-bec50e7d1781?source=rss-b3b06a6986a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec50e7d1781</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Klatzke]]></dc:creator>
            <pubDate>Thu, 01 Nov 2018 03:18:21 GMT</pubDate>
            <atom:updated>2018-11-01T16:02:46.048Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most common questions I got asked as a JavaScript teacher was “what is reduce for?” It’s easy to peruse the web and see many examples of people using reduce to do very minimal things, but seeing how it’s actually used in action is much rarer to find. It’s possibly the most confusing of the built-in higher-order functions within JavaScript. While people can intuitively grep the usage of things like map, filter or sort, reduce has a less intuitive usage. This article does assume you have a basic understanding of higher-order functions and ES6 syntax.</p><p>MDN explains reduce as:</p><blockquote>The <strong>reduce()</strong> method executes a <strong>reducer</strong> function (that you provide) on each member of the array resulting in a single output value.</blockquote><p>That being said, reduce ‘s core functionality can be pretty easily explained:</p><blockquote>Reduce operates on an array and reduces its content to a single value.</blockquote><p>What tends to trip people up in this is that the single value you reduce to doesn’t have to be something as simple as a string or a number, but can be an array or an object. It should also be noted that reduce does <strong>not </strong>edit the original array.</p><p>Lets dive straight into examples, starting with an extremely common one that you see all of the time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbf46ff7293cb7371ac78f33043027e7/href">https://medium.com/media/dbf46ff7293cb7371ac78f33043027e7/href</a></iframe><p>This example is pretty straightforward (the output is 600, by the way) and strikes at the core of what reduce does. We’re taking an array containing three values:</p><p>100, 200, 300</p><p>These values are then pushed through the reduce function. On each iteration of the reduce, as it moves onto the next value, it receives two arguments:</p><p>carry — this is the total and current accumulated value. This is sometimes called the accumulator or even just acc. If we don’t specify a second argument to the reduce function, our initial carry will be equivalent to the first item in the array. This works for our current example, but we’ll see some others where it will simplify our function to provide the initial carry.</p><p>next — this is the next value in the array. Since we didn’t specify an initial carry, our first carry will be 100, which means our first next is 200.</p><p>So what ends up happening here is as follows:</p><ul><li>First Iteration: 100 is the current carry. We do a += with our next value which is currently equivalent to 200 yielding a new carry of 300.</li><li>Second Iteration: 300 is the current carry . We do our += with our next value which is currently 300 yielding a new (final)carry of 600.</li></ul><p>Let’s see an example that uses the second argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2bf2d07c353615166854c5ba494a077/href">https://medium.com/media/f2bf2d07c353615166854c5ba494a077/href</a></iframe><p>This example is still very simple — we’re just adding numbers together, but this time we set our initial value equal to 1000 by passing it as the second argument in our reduce function. Let’s look at how this one breaks down in the same format as our previous one:</p><ul><li>First Iteration: 1000 is the current carry as it was provided by us. We do our += with our next value which is currently 100 yielding a new carry of 1100.</li><li>Second Iteration: 1100 is the current carry. We do our += with our next value which is currently 200 yielding a new carry of 1300.</li><li>Third Iteration: 1300 is the current carry. We do our += with our next value which is currently 300 yielding a new carry of 1600.</li></ul><p>These examples, while simple, are the fundamental aspect of how reduce works.</p><p>Let’s look at some more simple examples that leverage some other initial values like arrays and objects. Reduce can be used in conjunction with some ES6 features to easily merge array or objects, for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3001fade378cec15cc18eaef58bc4fe3/href">https://medium.com/media/3001fade378cec15cc18eaef58bc4fe3/href</a></iframe><p>We obviously have better ways to do this already in JavaScript, but it’s a good example of how flexible reduce is to use. This is also a great example of what reduce gives us — we’re collapsing all items of this array <em>into</em> another array (a single value).</p><p>Let’s see it with objects (very similar):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228a0cb0312bf9b87b9f5226d2c616f5/href">https://medium.com/media/228a0cb0312bf9b87b9f5226d2c616f5/href</a></iframe><p>Purely for the sake of knowing it exists since we’ll be using it later, let’s look at an example using the other arguments that reduce offers in its callback. The third argument it gives the callback is the current index, which we’ll call idx and the last option is the source array, which we’ll call src:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81858c1beae7d87be8801e2ba22d5a97/href">https://medium.com/media/81858c1beae7d87be8801e2ba22d5a97/href</a></iframe><p>The above function reduces an array to an array that only contains unique values from this array. Again — this can be easily done (better) with other methods that are built for that purpose (like filter) but that’s not really the purpose of this article.</p><p>Next, we’re going to look at actual uses of reduce as they might appear in the wild. In many cases, the use of reduce is going to replace what previously might have involved an additional variable to hold an accumulated state outside of a for or forEach loop.</p><p>For this, we’re going to be using the following data structure to represent a number of items that belong to a specific order:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c810b28c29b132f79a994a09d07d28/href">https://medium.com/media/b0c810b28c29b132f79a994a09d07d28/href</a></iframe><p>How would we get the total number of items this person has ordered? Reduce has a pretty good use case here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ec397de2e92edcb0a31e23d9a04025/href">https://medium.com/media/33ec397de2e92edcb0a31e23d9a04025/href</a></iframe><p>How about if we wanted to calculate the quantity per item? We could easily accomplish this with a for loop and an object that holds the associated keys, but we can also do this with reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e39ff14783ee39a8e14e442275fe960/href">https://medium.com/media/3e39ff14783ee39a8e14e442275fe960/href</a></iframe><p>We can also get the products by order:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e043ac574bbd1db62b50841281c7ff5/href">https://medium.com/media/8e043ac574bbd1db62b50841281c7ff5/href</a></iframe><p>You’re going to notice a trend here — we’re using an object {} as our initial carry and then setting a key with what we want to sort with equal to an array. Then we push our values directly into that array. This is a fairly common use case for reduce; essentially reducing an array into an object with sorted (and accumulated properties).</p><p>Here’s another example, calculating the total expenditure of our user within our system:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ebdc8029b0b6914033d100758365b74/href">https://medium.com/media/8ebdc8029b0b6914033d100758365b74/href</a></iframe><p>Here’s an example that combines a lot of what we did above to calculate the total for each individual order from our above data set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/284ab288d1bb5d52507b70237964cd14/href">https://medium.com/media/284ab288d1bb5d52507b70237964cd14/href</a></iframe><p>The above is a pretty good example of where you might see reduce actually used in a real codebase.</p><p>Next, let’s look at how we can actually duplicate the functionality of other higher-order functions while using reduce. Again — this is purely a learning exercise, the other higher order functions exist for a reason.</p><p>Let’s start with map and look at two examples that do the same thing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3254d4ec83ab9fcfbc5d0ad4258dd37e/href">https://medium.com/media/3254d4ec83ab9fcfbc5d0ad4258dd37e/href</a></iframe><p>It’s obvious from this example that the map version is the more terse and better way to handle this, but it’s possible to do with our reduce function.</p><p>Next, let’s take a look at filter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f8bf894e180f6aeef3d031ad3795fa/href">https://medium.com/media/48f8bf894e180f6aeef3d031ad3795fa/href</a></iframe><p>Due to the need to basically “rebuild” the array you’re working on, reduce does have some overhead complexity that the other methods don’t as can be seen here.</p><p>Finally, let’s look at sort. Here’s the very obvious way you should handle a basic number sort:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22da9e178c63bb814d6ce5dddacd602a/href">https://medium.com/media/22da9e178c63bb814d6ce5dddacd602a/href</a></iframe><p>Here, we can look at an example using reduce (and recursion) to do a sort on the array (note: swapIdx is just a helper function):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3356204e8ee70451c8573488704dc2f8/href">https://medium.com/media/3356204e8ee70451c8573488704dc2f8/href</a></iframe><p>reduce doesn’t give us many benefits over sort. There is way more code required to do the same thing, but it does give us the ability to choose the sorting algorithm we want to use directly within the body of our callback (we’re using a very simple sort here). Additionally, the sort method edits the original array whereas our reduce method produces a brand new one.</p><p>Hopefully this has helped you understand how, and why, you might use a reduce function. Though many of these examples are contrived, they give a decent understanding of when you might actually want to use reduce in a real application, and furthermore just express the flexibility that you have when using this often misunderstood method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec50e7d1781" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Python Webserver from the Ground Up (Part Two)]]></title>
            <link>https://medium.com/@andrewklatzke/building-a-python-webserver-from-the-ground-up-part-two-c8ca336abe62?source=rss-b3b06a6986a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ca336abe62</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Andrew Klatzke]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 04:20:30 GMT</pubDate>
            <atom:updated>2018-05-11T01:37:56.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2</h3><p>In Part 1 we took a look at setting up the basic infrastructure for a web framework — namely serving up HTML files at specific route responses. If you haven’t read <a href="https://medium.com/@andrewklatzke/creating-a-python3-webserver-from-the-ground-up-4ff8933ecb96">Part 1</a>, I’d start there to get up to speed as we’ll be building on the application presented in that article.</p><h4>Setting Up a Static Request Handler</h4><p>In the previous section, we set up two different types of request handlers: a BadRequestHandler to manage 404s and other types of errors, and a TemplateHandler to send back our HTML file requests at specific URLs. We’re going to expand that now by adding a third type of handler, a StaticHandler.</p><p>First, let’s stub out the file so that it properly utilizes our RequestHandler parent class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd3637015f9a730916e8a4f2d5d3029/href">https://medium.com/media/fdd3637015f9a730916e8a4f2d5d3029/href</a></iframe><p>Within this class, we’ve set up three methods:</p><ul><li>__init__, which we’ll add to in a moment,</li><li>find which if we remember from the last article, is responsible for actually finding the file,</li><li>and finally, setContentType which will work in tandem with the __init__ to set the appropriate content type depending on the file extension</li></ul><p>We know from our TemplateHandler that we currently have the server.py set up to pass the entire path to a given request into the handler for that request. As such, we can go ahead and fill out these methods based on the incoming request, and then we’ll add the handling logic to our server.py so that it routes to this handler when appropriate.</p><p>Go ahead and create a folder called “public” within your directory. This is going to house all public assets for the site (CSS, Images, Javascript, etc.). By using a specific folder we can insure that:</p><ol><li>No one can request files outside that folder</li></ol><p>2. We can consistently access the files from a simple path — e.g. treating our “public” folder as the server root</p><p>As such, a request for “/main.css” would translate (on our server) to “/public/main.css”. This makes it easy for us to reason about where our requests should be routed, and restricts all of the access on our server to a single folder (helping with possible security issues).</p><p>Let’s go ahead and fill out the StaticHandler’s find method.</p><p>Before we do, go ahead and add the following line to the top of your StaticHandler file:</p><p>import os</p><p>We’ll be using this to grab files from the filesystem.</p><p>As for the StaticHandler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/872b3213055be286f0ca7a47d9a1fc99/href">https://medium.com/media/872b3213055be286f0ca7a47d9a1fc99/href</a></iframe><p>Within this method we’ve done a few things:</p><ul><li>First, we split the path into its individual parts using the os package so that we can pull the extension</li><li>Next, we pull that extension from split_path[1]</li><li>Our conditional checks if it’s of certain filetypes (images) which are already in bytes format</li><li>If they are in bytes format, we open them with ‘rb’,</li><li>if not, we open them with just ‘r’</li><li>We’re using the built-in string formatting to build out the path, prefixing it with “public”</li></ul><blockquote>It would be wise to add some logic surrounding this to ensure that no one can include .. in the request path to give them access to more than what is intended. For now, we’re going to skip that part.</blockquote><ul><li>Next, we pass the extension to self.setContentType (which we’ll see in a moment)</li><li>Finally, if we got to this point, we set the status code to 200</li><li>If there is an exception (e.g. the file does not exist) then we set the Content-Type to ‘notfound’ and send a 404 code</li></ul><blockquote>Again, there is significant room here for better error handling, but I don’t want to bore you with the details, so we’ve excluded it for the time being. When the final source is posted, I’ll adjust for these so that they’re better handled.</blockquote><ul><li>We return a boolean in either case to let the consumer of this method know that the file was either found or not.</li></ul><p>Next, let’s look at how we’ll figure out the `Content-Type` (I’m including the entire StaticHandler here so you can see it all in tandem):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16a9ac50e7866840417ef22502407831/href">https://medium.com/media/16a9ac50e7866840417ef22502407831/href</a></iframe><p>We’re setting up a hash table within our __init__ to handle the whitelisted file types available. For now, we’ll allow the processing of: js, css, png, and jpg files. This can obviously be expanded to handle additional file types like videos, gifs, etc..</p><p>In our setContentType method, we’re simply doing a lookup on this hash table to set the content type to the appropriate value:</p><p>self.contentType = self.filetypes[ext]</p><p>Now that the contentType member is set, when we run getContentType in our server.py we’ll be able to get the appropriate content type.</p><h4>Adding our New Handler</h4><p>In the last article we went through the hassle of setting up the RequestHandler class, and we’re now seeing how it benefits us; by having each of these classes extend our base RequestHandler we’re allowing a “plug and play” interface for a new handler without having to drastically change the code in our base server.py file. Pretty soon, we won’t have to interact with server.py at all, but first, we need to go ahead and add our StaticHandler into the mix to handle non-html requests.</p><p>We know that requests for static assets will always be “GET” requests, so that’s the method we want to zero in on:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22598fbc549a0dd30e7bc528716fec06/href">https://medium.com/media/22598fbc549a0dd30e7bc528716fec06/href</a></iframe><p>First we add the import for our new file:</p><p>from response.staticHandler import StaticHandler</p><p>Next, let’s look at the changes to the do_GET method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/583d413562cbf7f7bf2b622a02d2ee06/href">https://medium.com/media/583d413562cbf7f7bf2b622a02d2ee06/href</a></iframe><p>They’re fairly straightforward, but let’s document them here:</p><ul><li>The first thing: we’ve added an elif to our conditional that checks if the request file’s extension is “.py”. This is just a security addition to make sure that if someone is (for some reason) trying to request a source file, that it immediately ends the request and sends back a 404</li><li>Next, we turn the previous BadRequestHandler in the else into a call to the StaticHandler instead</li></ul><blockquote>Since the `StaticHandler` takes care of a 404 if it cannot find the file, this basically means that it will look for a file in <strong>public</strong> and if it cannot return it, will send the same 404 it would have previously</blockquote><ul><li>We pass the path into the StaticHandler’s find method, and that’s basically it. The data will be pulled out in the same manner as it is for our TemplateHandler</li></ul><p>Next, there is a quick change we need to make to the handle_http method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/226eac4d65da37e151358b88e7952290/href">https://medium.com/media/226eac4d65da37e151358b88e7952290/href</a></iframe><p>This is a simple one — because some of our files will now be coming back to us in bytes format (e.g. images) we need to account for the fact that they do not need to be converted into a bytes type.</p><p>We set up a conditional to check if the content from the handler is already a bytes or bytearray object — if it is, we go ahead and return that data, otherwise we return the data converted into the bytes type object.</p><h4>Seeing It In Action</h4><p>Visit your “templates/index.html” file and add the following in the &lt;head&gt;:</p><p>&lt;link rel=”stylesheet” href=”/main.css”&gt;</p><p>Create a file in the public folder called “main.css”.</p><p>Add the following to that file:</p><p>body{ background-color: #222 }</p><p>Restart your server, clear your cache on your browser, and you should see the background color applied to your index page.</p><p>You can go ahead and add some Javascript links too (remember, everything is linked from public/) and see that in action as well.</p><p>Our server is now responding with the assets that we’ve whitelisted in the StaticHandler. You can add more by simply adding the appropriate content type to the array in the __init__ method.</p><h4>Wrapping Up (for now)</h4><p>This was a short entry, but we’ve taken our server from being able to serve only flat HTML files to being able to include its own assets. In the next entry, we’ll take a look at setting up route parameters, and we’ll flesh out our router to make it more powerful and easier to use.</p><p>Thanks for reading. You can find a snapshot at this portion of the tutorial at this <a href="https://github.com/aklatzke/python-webserver-part-2">GitHub repository</a>.</p><p>Part three is coming soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ca336abe62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Python3 Webserver From the Ground Up]]></title>
            <link>https://medium.com/@andrewklatzke/creating-a-python3-webserver-from-the-ground-up-4ff8933ecb96?source=rss-b3b06a6986a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff8933ecb96</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Andrew Klatzke]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 22:51:34 GMT</pubDate>
            <atom:updated>2018-05-11T01:37:31.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Python3 Webserver From the Ground Up</h3><p>Jumping into Python’s web code when your previous experience is mostly in web-based languages (PHP, Javascript, Ruby) can be a daunting task. Python has all of the tools available to make a strong HTTP Server or framework, as well as plenty of mature web frameworks to get started with, but the purpose of this tutorial/write-up isn’t to show you how to leverage those, but how to build one from the ground up (similarly to how you’d start learning with NodeJS) to give you a more complete understanding of how the components can fit together.</p><p>Throughout this tutorial, we’ll go through a few different steps, the first of which is included today:<br>1. Setting up a basic HTTP server that will respond to basic GET requests with a stock message (“Hello World”) and then expand that to have a router that allows us to request different HTML files.<br>2. Incorporate appropriate file responses for requests (HTML, images, CSS, Javascript)<br>3. Allow our routes to take parameters, respond in-kind with the appropriate data and set up API routes<br>4. Add a view rendering library and incorporate a database into our application</p><p>A basic understanding of Python3’s syntax and OOP components will help you through this tutorial. Components important to the server will be explained as we move through, but basic syntax will not be explained.</p><p>The full source code will be available on Git once it’s completed, and the source code for today’s tutorial will be at the end of the article.</p><p>Let’s dive right in.</p><h3>Setting Up</h3><h4>Python3</h4><p>First and foremost, let’s make sure we’re running the right version — we’ll be building this on Python3, which you’ll need to have it installed.</p><p>You can run a which python3 on a Linux box to make sure it’s available, if not, follow the appropriate steps to install the latest python3 binary.</p><p>Note — on Macs, the version that ships out of the box (i.e. what happens when you run python) is version 2, which means you’ll need to install the latest version. <a href="https://brew.sh/">Homebrew</a> makes this easy.</p><h4>Setting Up Our Editor</h4><p>You can use your editor of choice for this, but I’d recommend at least the following:<br>- The syntax package for your editor<br>- A linter (pylint is a good choice)</p><h4>Setting Up Our Project</h4><p><strong>main.py</strong></p><p>Create the directory in which you want the webserver to live.</p><p>Once you have a new directory, create two files in the root — the initial will be main.py to house our execution script, and server.py which will contain the class that will be running our server.</p><p>First, let’s fill out our `main.py`. Where needed, I’ll fill out comments about the code after the presented code blocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/910e98e4243fc81ee424ac520706a3ce/href">https://medium.com/media/910e98e4243fc81ee424ac520706a3ce/href</a></iframe><p>First, we’re importing the necessary packages that we’ll be using in this file:</p><pre>import time<br>from http.server import HTTPServer<br>from server import Server</pre><p>The time package simply writes timestamps for when our server goes up or down.</p><p>The `http.server` package contains the HTTP server boilerplate from the Python3 standard library. We’re importing a single module from this — HTTPServer.</p><p>The server module is the other file we’ll be filling out here in a moment, as of now, it’s going to show an error for the improper import. We’re importing a single class, Server from our module.</p><p>Next, we define two constants we’ll be using when we launch the server: HOST_NAME=localhost which will launch our server on our localhost and PORT_NUMBER=8000 which is the port we want it to run on (feel free to change this port if your 8000 is occupied).</p><p>Next up, we have the boilerplate for running our server. The first line if __name__ == ‘__main__’: is assuring that we ran this file specifically. If that’s the case, we’ll execute the rest of the code.</p><p>Next, we create the HTTP object:<br>httpd = HTTPServer((HOST_NAME, PORT_NUMBER), Server)</p><p>We pass the following parameters to the HTTPServer object that we imported earlier:</p><ul><li>We pass a tuple containing the HOST_NAME and PORT_NUMBER</li><li>As a second argument, we pass the server handling class Server, imported from our own file, that we’ll fill out in a moment</li></ul><p>The next line simply prints our “Server UP” with the timestamp to the console. We’re using the Python string formatting operator to pass in the constants as well:<br>print(time.asctime(), ‘Server Starts — %s:%s’ % (HOST_NAME, PORT_NUMBER))</p><p>This next block actually starts up the server and runs it:</p><pre> try:<br>   httpd.serve_forever()<br> except KeyboardInterrupt:<br>   pass<br> httpd.server_close()</pre><p>This tells our created httpd object to serve until it receives a keyboard interrupt. Once that happens, it closes out the server connection with httpd.server_close.</p><p>Our last print line simply outputs a message when the server is closed.<br>print(time.asctime(), ‘Server Stops — %s:%s’ % (HOST_NAME, PORT_NUMBER))</p><p>Next, let’s set up our server handler.</p><p><strong>server.py</strong></p><p>Let’s go ahead and stub out the file with the following class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f08338ccf9e354d9d18a06f749361d2f/href">https://medium.com/media/f08338ccf9e354d9d18a06f749361d2f/href</a></iframe><p>We’ll be using these methods to handle the responses. On our first line, we import the BaseHTTPRequestHandler from the http.server package. This is going to be the class that ours will subclass. There are some important things to note:</p><p>- When a request comes in, the BaseHTTPRequestHandler will automatically route the request to the appropriate request method (either do_GET, do_HEAD or do_POST) which we’ve defined on our subclass</p><p>- We’ll use handle_http to send our basic http handlers and then return the content.</p><p>- respond will be in charge of sending the actual response out</p><p>In order to first respond, our class will need to be able to send, at minimum, three things:</p><p>- the response’s Content-type,<br>- the response’s status code,<br>- and finally the actual content of the site</p><p>Let’s add this to our class now so that it can send a basic “Hello World” response to a GET request in plain text to make sure our server is working as intended:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea54f4a9e3f2c20774811f0c27315b88/href">https://medium.com/media/ea54f4a9e3f2c20774811f0c27315b88/href</a></iframe><p>Let’s look at the changes, starting at our handle_http method.</p><pre> def handle_http(self, status, content_type):<br>   self.send_response(status)<br>   self.send_header(‘Content-type’, content_type)<br>   self.end_headers()<br>   return bytes(“Hello World”, “UTF-8”)</pre><p>As stated before, this method is going to take care of sending our header and generally putting the response in a format where it’s ready to be sent. All arguments in our handle_http method will be passed in from the respond method. The flow of data will look like this when a request is received:</p><p>do_* receives request &gt; respond invoked &gt; handle_http bootstraps request, returns content &gt; respond sends the response</p><p>In the first line, we’re sending the status code through the send_response method inherited from the BaseHTTPRequestHandler.</p><p>In the next line, we’re sending the Content-type header with send_headers, also passed in from our respond method. We end the headers we’re sending (for now!) with the self.end_headers method.</p><p>Next, we return the content we want to send (“Hello World” for now), converted into a bytes object with UTF-8 encoding. Anything you send back in your response will need to be in this format. We’ll add additional handling later to take care of objects that are already in this byte format (for example, images).</p><p>Next, let’s look at the respond method.</p><pre> def respond(self):<br>   content = self.handle_http(200, ‘text/html’)<br>   self.wfile.write(content)</pre><p>For now, it’s passing through a 200 success code and the content type (‘text/html’) to the handle_http method. Finally we run the self.wfile.write method to send the finalized content out as the response.</p><p>Our do_GET method simply kicks off this process as it will be the one the BaseHTTPRequestHandler triggers when a GET request is received.</p><pre> def do_GET(self):<br> self.respond()</pre><p>At this point, our server is ready to run. Navigate to the directory your project is housed in and run python3 main.py to start up the server. Navigate to your chosen port (8000) in the above instructions, and you should see a “Hello World” response.</p><p>We now have a webserver!</p><h4>Adding a Router</h4><p>Obviously, right now, this is not much of a webserver — we’re just passing “Hello World” out to the user.</p><p>One of the most important facets of a websever is being able to respond to requests at different URLs — it’s not really useful without it. So next, we’re going to go ahead and create a router.</p><p>A router, at its core, just allows us to map a given request to a given resource on our webserver. This sounds very similar to a given structure in Python (the dictionary) which allows us to map keys to their specific values.</p><p>Let’s create a new folder (routes) and create a file inside that directory (main.py).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*YEPDq1eLRFxjFZNN44d_bg.png" /></figure><p>Since we’re currently working with text, we’re going to set up our router to just respond with text data when a given route is hit.</p><p>Let’s fill this out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f60acb23a04ce8a76fb6a8955d99078/href">https://medium.com/media/5f60acb23a04ce8a76fb6a8955d99078/href</a></iframe><p>This is very simple at the moment, but we’ll be filling it out further in our examples.</p><p>Next, let’s import the routes file into our server.py:</p><pre>from routes.main import routes</pre><p>Next, let’s adjust our handle_http to grab content from the routes file dependent on the current path:</p><pre> def handle_http(self, status, content_type):<br>   self.send_response(status)<br>   self.send_header(‘Content-type’, content_type)<br>   self.end_headers()<br>   route_content = routes[self.path]<br>   return bytes(route_content, “UTF-8”)</pre><p>All we need to do is pull the self.path member from the class and then pass it into the routes[] dictionary that we pulled from our routes file. It’s pretty straightforward — we’re just looking it up by key at the moment. We then pass the route_content into our return in order to pass it on to the respond method.</p><p>If you visit the URLs you specified in your routes.py file, you should now be able to see the intended text response at each URL (after a server restart).</p><h4>Sending HTML</h4><p>Next we’re going to make the routes file respond with HTML rather than just text — far more useful.</p><p>Let’s create a few more files. Start by creating a “templates” folder which will house our HTML (for now, index.html and goodbye.html):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*jNUgNbLL4kmw9_S3O249tw.png" /></figure><p>You can put whatever you want in these files for now, but leave out any references to CSS or JS because our server will not be able to handle those right now (though we’ll be getting to that).</p><p>Here’s our (very simple) index.html file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c9b3c69425332e0584f9f179b63fd8/href">https://medium.com/media/b5c9b3c69425332e0584f9f179b63fd8/href</a></iframe><p>We also need to change our routes file — we’re going to go ahead and nest another dictionary within our current keys:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6145e7ee1b866ebee67781d18b5d08ff/href">https://medium.com/media/6145e7ee1b866ebee67781d18b5d08ff/href</a></iframe><p>The template key within our nested dictionary is going to handle pointing to our specific template file for a given route.</p><p>Next, we’ll adjust our server.py file to pull those specific files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc0af358bd2a62617be109a93d5d5b09/href">https://medium.com/media/dc0af358bd2a62617be109a93d5d5b09/href</a></iframe><p>We’ll cover the changes starting with our new import:<br>from pathlib import Path</p><p>We’re importing the Path module from pathlib to make sure that our HTML files exist before we attempt to read their contents.</p><p>Next, we’ll go down to our handle_http method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f57e0c759a3fa0b150e2d47a2ec6c9e9/href">https://medium.com/media/f57e0c759a3fa0b150e2d47a2ec6c9e9/href</a></iframe><p>We’re doing a few things differently now:</p><ul><li>The method no longer takes any arguments, instead we’ll be building out the response type and status code within our function so that we can respond with a 404 or other status code if necessary</li><li>We’re doing a check to ensure that our path exists within our routes to ensure that the path actually exists. If it doesn’t, we’ll send a 404 with a text/plain response</li><li>Within this check, we’re pulling the given route’s template into the route_content variable and then passing it to open</li><li>Once this is pulled, we use .read to get the HTML file’s content. If the file doesn’t exist, we throw a 404.</li><li>After this, the only changes are that the content_type is now dynamic, and the response_content is equivalent to what we set it to earlier.</li></ul><p>Go ahead and fire up the server and check your index page — you should now we be able to see the content you put in your index.html file. Next, go to /goodbye and you’ll be able to see the content in the goodbye.html file.</p><h4>Some Refactoring, and Error Handling for Non-HTML Requests</h4><p>Okay, so, we’ve created a server that is capable of returning HTML files for a specific URL, but we haven’t yet built something that can handle everything else an HTML file needs to do, namely, being able to include CSS, Javascript and Image files from the server.</p><p>We’re going to be building that out (in the next article), but the first thing we want to do is some refactoring. In the current files, we’re handling everything on a case-by-case basis which will very quickly balloon into a massive handle_http function, and isn’t a particularly clean way to handle it.</p><p>Go ahead and create a new folder, named “response”. This response folder is going to house a few classes that will allow us to tailor the response for specific types of files (e.g. templates vs static assets vs errors) in a much cleaner way.</p><p>Within this folder, let’s create the base RequestHandler class and name it requestHandler.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae3b972884b8ceb989c794ef0f52b02e/href">https://medium.com/media/ae3b972884b8ceb989c794ef0f52b02e/href</a></iframe><p>Within this file, we’re going to do two things:</p><ul><li>Create a MockFile class — this is a placeholder object that will take care of requests where we won’t have a .read function on the self.contents member.</li><li>If we don’t have this, Python will yell at us, despite the fact that we’ll be supplying the results of open calls later that have a read function.</li><li>We’re also declaring our RequestHandler here that will be the class we extend to handle each type of request. There are a number of different methods we’re declaring on this object which are mostly getters and setters for the various attributes that each request type will have. Also important to note is what we’re not declaring here: We have no mechanism to actually retrieve the file — this is because we’re going to delegate that to the child classes so that they can each individually handle where the files should be imported from, as well as any specific handling that needs to happen to those files (and some response types won’t even have files to open).</li></ul><p>Next, let’s go ahead and define a child class that will extend this to handle our templates and get our server back up and running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/844bfb48e7cbeb9b61947f927c0c458f/href">https://medium.com/media/844bfb48e7cbeb9b61947f927c0c458f/href</a></iframe><p>Within our TemplateHandler class, the first thing we’re doing is importing our RequestHandler from the previous file. We pass it into the constructor for the class so that it inherits from that class:</p><p>class TemplateHandler(RequestHandler):</p><p>Next up, we define two methods — within our __init__ we set the content-type for our HTML templates (which will always be text/html).</p><p>We define the find method which will allow the template to find the specific file and set the contents so that we can pull them out within our server file.</p><p>We now have a class that will handle our templates, but in our server.py we currently have two different types of requests that need handled — the templates, and “bad” requests, such as a 404 if the file is not found. Let’s go ahead and implement a BadRequestHandler as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79282a2d97cbbc180fd23c1655edd16a/href">https://medium.com/media/79282a2d97cbbc180fd23c1655edd16a/href</a></iframe><p>Simple enough — this one doesn’t need a find method because there’s nothing to find, it’s just a 404 so the content-type can be simple, and the status will be a 404.</p><p>Let’s change up our server.py to reflect the changes we made — for now we’ll only be handling HTML requests and sending 404s for everything else:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44cd809115de2217b58bcfeeb9cb5f3/href">https://medium.com/media/d44cd809115de2217b58bcfeeb9cb5f3/href</a></iframe><p>We’ve changed some of the logic around — our do_GET will now be handling the actual request with our RequestHandler objects.</p><p>First, let’s look at the new imports:</p><pre>import os<br>…<br>from response.templateHandler import TemplateHandler<br>from response.badRequestHandler import BadRequestHandler</pre><p>Here we’re importing the os package that will allow us to split the extension from the request path so that we can match against the extension and use the appropriate handler.</p><p>Let’s look at our do_GET method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb1a91638021873d549e34c5d14705d9/href">https://medium.com/media/eb1a91638021873d549e34c5d14705d9/href</a></iframe><p>First, we split the path into its parts using os.path.splitext. We then pull the file extension from the array we just created.</p><p>We then have a conditional to check if our extension is either “” or “.html”. This will handle requests for both .html files directly, and for simple URL requests (e.g. localhost:8000/, localhost:8000/goodbye).</p><p>Next, we have the same logic we previously did to see if the path exists in our routes file. If the path is valid, we create a new `TemplateHandler()` and then use the handler’s `.find` method, passing in the routes object which looks like this:</p><pre>{<br> “template” : “templateName.html”<br>}</pre><p>In our else we use a BadRequestHandler to signal the 404 on the file.</p><p>In our next else (if the route isn’t found) we create another BadRequestHandler to handle the 404.</p><p>Finally, we use self.respond and send the created handler through to the respond method which will then be passed into our handle_http method.</p><p>Let’s look at respond next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/444c9cc529d0e9d1f013dca2b0b02320/href">https://medium.com/media/444c9cc529d0e9d1f013dca2b0b02320/href</a></iframe><p>The only change here is that we’re passing through an opts argument that contains the handler, and then passing that through to the handle_http method call.</p><p>Finally, let’s check out the new handle_http:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/948402a04aa27c05edb0cac9a78e24fe/href">https://medium.com/media/948402a04aa27c05edb0cac9a78e24fe/href</a></iframe><p>First, we pull the status_code from the handler. If a BadRequestHandler made its way through, it’ll be a 404, otherwise a 200 in the TemplateHandler unless the handler was unable to find the file, in which case it will also respond with a 404 (check out the TemplateHandler’s logic to see this in action).</p><p>We go ahead and send the status code, and then if the status code is 200 (OK) we go ahead and pull the contents of the file with handler.getContents. This does an internal call to .read on the file that we opened.</p><p>Next, we send a header with the content type, again pulled from our handler.</p><p>We end the headers, and then go ahead and send our result.</p><p>We’re now reading files using our RequestHandler class, and we’ve cleaned up our server.py quite a bit (or at least made it more understandable and extensible). You should now be able to restart your server and take a look at the HTML pages for the specific routes, and routes that are not included should send a 404 message.</p><p>That’s it for today’s tutorial — when the second part of this is published, we’ll take a look at how we can add other resources (CSS, Javascript, etc) when the HTML pages automatically requests them (like, how, you know, the web actually works).</p><p>You can find the repository with the code up to this point at <a href="https://github.com/aklatzke/python-webserver-part-1">this Github link</a>.</p><p>Thanks for reading, and I hope you’ll check back in for part two!</p><p>Part two is available now:</p><p><a href="https://medium.com/@andrewklatzke/building-a-python-webserver-from-the-ground-up-part-two-c8ca336abe62">Building a Python Webserver from the Ground Up (Part Two)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff8933ecb96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>