<?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 Bruno Fosados on Medium]]></title>
        <description><![CDATA[Stories by Bruno Fosados on Medium]]></description>
        <link>https://medium.com/@bruno.fosados?source=rss-c2e961655545------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*7BDg45SlSMpTlYpITNKLfg.jpeg</url>
            <title>Stories by Bruno Fosados on Medium</title>
            <link>https://medium.com/@bruno.fosados?source=rss-c2e961655545------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:56:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bruno.fosados/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[Reset Django migrations out of sync on different environments]]></title>
            <link>https://medium.com/@bruno.fosados/reset-django-migrations-out-of-sync-on-different-environments-6dcc8ddf159b?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dcc8ddf159b</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 22:05:38 GMT</pubDate>
            <atom:updated>2022-02-18T22:18:37.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jr8xUvtVor_XLRCO-i24sw.png" /></figure><p>One Django good practice is to track migrations the same on all your environments, especially when following <a href="https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow"><em>git-flow</em></a>.</p><p>Recently in one of my projects we needed to fix the way we were handling migrations in different environments, for some reason migrations were diverged from environment to environment, end up having different migrations in test, dev, and prod.</p><p>So I found a nice solution for doing this with a few Django commands, first, you need to find the correct time to do so, in which your environments should be the same in terms of coded Django models (same models on all environments).</p><p>To make things simple I’m going to use the local way to do it, if you are serverless, you need to translate to your tool of choice, e.g. $ zappa manage test makemigrations AppNameinstead of the local way $ python manage.py makemigrations AppName</p><ol><li>Delete the current migrations and cache files, this looks a little bit scary, but don&#39;t worry those are still tracked on git, so in order to delete them you need to run:</li></ol><pre>find . -path &quot;*/migrations/*.py&quot; -not -name &quot;__init__.py&quot; -delete<br>find . -path &quot;*/migrations/*.pyc&quot;  -delete</pre><p>You can do it on an app basis, one Django app at a time if you feel more comfortable with it.</p><p>2. Once you have deleted the actual migrations, you need to delete the migrations records for the migrations that were actually run to the DB, in order to do so you could directly delete them from the DB with SQL or you can use the Django shell $ python manage.py shell then:</p><pre>from django.db.migrations.recorder import MigrationRecorder</pre><pre>MigrationRecorder.Migration.objects.filter(app=&#39;AppName&#39;).delete()</pre><p>you need to do so for all the apps you are fixing migrations for, great now we are half of the way.</p><p>3. Next is to recreate migrations for that you need to run:</p><pre>python manage.py makemigrations AppName</pre><p>you can do one app at a time or you can do it all at once by omitting the AppName argument.</p><p>Then you need to run:</p><pre>python manage.py migrate --fake AppName zero</pre><p>just to make sure any other reverse/initial operations are applied.</p><p>4. Then just fake the migration generated on step 3:</p><pre>python manage.py migrate --fake AppName</pre><p>again you can do one app at a time or you can do it all at once by omitting the AppName argument.</p><p>At this point, your migrations are in sync with your DB and models, it&#39;s safe to commit changes and merge them accordingly on your environments.</p><p><strong>Conclusion</strong>:</p><p>This works because you chose a point in which your coded models are in sync with your different environments and all migrations were run on them so DB is also in sync and even that migrations files were different from env to env, the consistency of the DB is the same, we just delete them and recreate them to one single file, that can be sync across environments.</p><p>If this was useful for you please give it a clap!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dcc8ddf159b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Async Class Based Views (ACBV)]]></title>
            <link>https://medium.com/@bruno.fosados/django-async-class-based-views-acbv-5986c4511ae6?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/5986c4511ae6</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 20:35:34 GMT</pubDate>
            <atom:updated>2020-06-29T06:35:19.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IL_5_dNUxqsVbYkfv4-IA.jpeg" /></figure><p>Hello there! <a href="https://django.readthedocs.io/en/latest/topics/async.html">Django 3.1</a> finally was released with support for <strong>Class Based Views</strong> and <strong>Function Based Views</strong>, a big thanks for this amazing gift to everyone at the <a href="https://www.djangoproject.com/foundation/">Django Software Foundation</a>.</p><p>So here is your quick-start guide on how to start writing asynchronous Django views.</p><h3>Async Class Based Views:</h3><p>This was a little tricky to get started with, I had to jumped over the process of how the support for <em>async</em> CBV was actually implemented. A good approach if you ask me, to maintain retro compatibility with normal <em>sync</em> requests/response, middleware and all cool features of Django that we all use and love.</p><p>Basically now there are two kinds of <strong>requests</strong> <strong>handlers</strong> within Django one for <em>sync</em> and an other for <em>async</em>, without you to worry about context switching (async code runs in its own threat) between them, meaning that you can actually mix both calls <em>sync</em> and <em>async</em> with the help of <a href="https://github.com/django/asgiref/">asgiref</a> cool right? But here is the thing, you have to be extra careful about not blocking the main thread or event-loop in which <em>async</em> code actually runs, if you really want to jump on the <em>async</em> world I strongly suggest to watch this talk: <a href="https://www.youtube.com/watch?v=d9BAUBEyFgM">DjangoCon 2019 — Just Add Await: Retrofitting Async Into Django by Andrew Godwin</a> which explains how asynchronicity in Django is been implemented, so lets create our first <em>Async CBV</em>.</p><p>Make sure to use latest <strong>Django</strong> version</p><pre>$ pip install git+https://github.com/django/django.git@stable/3.1.x</pre><p>The current <em>async </em>requests handlers need to check that you actually wrote an <em>async</em> views so to complain with this validation there two ways of doing so:</p><h4>1. Add `_is_coroutine = asyncio.coroutines._is_coroutine` property to view.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e41cb5d7f0b074f646bf3e0912eb128/href">https://medium.com/media/2e41cb5d7f0b074f646bf3e0912eb128/href</a></iframe><p>That’s it, now whatever the implementation of your view might be (get(), post(), etc) it will be actually handle as an <em>async </em>one, lets add aPOST:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2c9d72a02dd83b2a0125b9e73891e0d/href">https://medium.com/media/c2c9d72a02dd83b2a0125b9e73891e0d/href</a></iframe><p>Please notice the <strong><em>async</em></strong> and <strong><em>await</em> </strong>keywords you <strong>must</strong> add them in order to to indicate python to get ready and open a space in the event-loop (the thread in which <em>async</em> code runs) and send some awaited call() to it, so when that awaited call() is resolve (just like promises on JavaScript) python can knows how to handle, this kind of functions have a fancy name, <em>coroutines</em>. Ok lets test our view…</p><p>Unfortunately, there is not yet support for <em>async</em> development server. So, we need the help of a cool guy called <a href="https://www.uvicorn.org/">uvicorn</a> checkout the logo is so cool!</p><pre>$ pip install uvicorn</pre><p>If you created your project with a modern version of Django you should have a settings file called: asgi.py which basically complains with the <a href="https://asgi.readthedocs.io/en/latest/specs/index.html">ASGI</a> specification. This file looks like magic, oh yeah!! but its just following a protocol of how to run ASGI application, in django the get_asgi_application() function does all the heavy lifting creating a callable handler to run our Django app for us, This handler is invoked by Uvicorn passing the incoming request, so is the main entry point for our django app, similar as its predecessor WSGI. Ok lets gets our hands on it.</p><pre>$ uvicorn project.asgi:application --reload</pre><p>Uvicorn follows python module dot notation to access our asgi.py, then the : with the name of the handler in this case application here is how my asgi.py file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db8f9a5c7b4ba4e81ab5fb37d9a7c4c/href">https://medium.com/media/6db8f9a5c7b4ba4e81ab5fb37d9a7c4c/href</a></iframe><p>Important thing to notice from this file is the “DJANGO_SETTINGS_MODULE” environment variable which if not set, defaults to “config.settings.local” which is the same as config/settings/local.py my local development settings file, so two options here, your could export DJANGO_SETTINGS_MODEL=&#39;your_project.settings&#39; to point your <em>settings.py</em> or replace the default value at your <em>asgi.py </em>file before running Uvicorn, so it can find the correct settings file of your Django project.</p><p>Let’s make a test POST request. I love this cli rest client called httpie lets take it for a spin:</p><pre>$ pip install httpie<br>...<br>...<br>$ http POST localhost:8000<br>...<br>...</pre><p>Oh bummer we forgot to wire-in our view within the <strong>urls.py</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/964a4620db9b0eb6b5ea5fadbc50b7e6/href">https://medium.com/media/964a4620db9b0eb6b5ea5fadbc50b7e6/href</a></iframe><p>lets give it an other try…</p><pre>$ http POST http://localhost:8000/offer<br># sleep should happen here, then eventually the response.<br>...</pre><pre>This was run asynchronously, man thats a long word :|</pre><p>Now try increasing/decreasing the sleep() time on the <em>async</em> <strong>post</strong> view.</p><p>That was it! Now you know how to write <em>Async</em> CBV so create cool async applications that do not block the main thread of your application when running io intensive e.g. long take DB queries, reading/writing to disk, sub reques/reponses inside a view, etc…</p><p>There is an other way of creating <strong>ACBV</strong>s …</p><h4>2. Using `__call__`</h4><p>At the time of writing this article I was not able to declare the async view in this way. My guess it that the actual support for this is work in progress, I will update this article once this is actually working on the stable branch, If you manage it to work in this way, drop me a line on twitter <a href="https://twitter.com/brunuxcom">@brunuxcom</a></p><p>Lets go further and create an app for processing and stream live video from webcam using <strong>WebRTC</strong> technologies.</p><h3>Streaming app</h3><p>I adapted this from <a href="https://github.com/aiortc/aiortc">aiortc</a> examples to run with Django, adding all the code here is going to make this post a little bit verbose, so I’m just review the Django related stuff instead, if you would like to run this code in your local, clone the repo:</p><pre>$ git clone <a href="/service/mailto:git@github.com">git@github.com</a>:Brunux/djnar.git --branch experiments</pre><p>Check the <a href="https://github.com/Brunux/djnar/blob/experiments/README.md">README.md</a> file for instruction on how to setup your local development environment.</p><p>So our streaming views should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4515eed85d16b6bb64c768d9fa794dc/href">https://medium.com/media/a4515eed85d16b6bb64c768d9fa794dc/href</a></iframe><p>We have one TempleView for serving, well, basically static content HTML/CSS/JS.</p><p>Magic happens on the SteamingOfferView, more specific our post() <em>async </em>function in which…</p><p>First, we read a posted RTC Session description (line 20) sent from the client check <a href="https://github.com/Brunux/djnar/blob/experiments/djinar/experiments/static/experiments/streaming.js">JS code</a>, this is related to WebRTC Specification, with this description we can create a session between in this case two hosts, web browser client and our Django application, so in response to this session description we create an answer follwing WebRTC specifications (line 75) an send back to the client.</p><p>After this connection has been established the web browser client starts sending video over a track channel (line 52) using this stream of video we apply a VideoTransformTrack (line 60) using the selected transformation on the HTML page send over the TemplateView, once it has been proccessed we send it back to the client, we also add some audio track to make it more fun (line 32).</p><p>Finally we open a data channel in which we ping →pong, back and forward over a data channel (data track) between the hosts.</p><p>As you can see the nature of this kind of communications is totally asynchronous and based on events, so this is a clear example of how we can take advantage of <em>async</em> class based views, processing video in real time and send the result to the client, I wonder what cool apps can we create applying <a href="https://opencv.org/">OpenCV</a> to the web.</p><p><a href="https://django.readthedocs.io/en/latest/topics/async.html#async-adapter-functions">Over here</a> you can read about how to run <em>sync</em> code over <em>async</em> an other possible scenarios, this is very useful to make calls to the ORM from <em>async</em> code since currently there is no <em>async </em>support for it (at the time of writing is WIP), spoiler alert, you need to wrap your calls in this way:</p><pre>from asgiref.sync import async_to_sync<br><br>async def get_data(...):<br>    ...<br><br>sync_get_data = async_to_sync(get_data)<br><br>@async_to_sync<br>async def get_other_data(...):<br>    ...</pre><h3>Resume</h3><p>If your Django application contains, <em>io</em> intensive operations, rewriting only those <em>io</em> intensive views in an <em>async</em> way, it could help a lot with the performance, in the other hand if your app doesn’t actually have <em>io</em> at all, stay <em>sync</em>. <em>Async</em> could be complex and dangerous specially when mixing <em>asyn</em> with <em>sync</em> in different scenarios, so start <em>sync</em> then after applying all possible optimization start writing little pieces of <em>async</em> code until you reach the performance that you want.</p><p>Thanks for reading this article, if you enjoy it give it a clamp or drop me a line on twitter <a href="https://twitter.com/brunuxcom">@brunuxcom</a> have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5986c4511ae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vuejs as replacement of JQuery in Django.]]></title>
            <link>https://medium.com/@bruno.fosados/vuejs-as-replacement-of-jquery-in-django-68f6b687887f?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f6b687887f</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Wed, 22 Jan 2020 21:48:04 GMT</pubDate>
            <atom:updated>2020-01-23T00:09:11.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*nl2D7TXFUaO9alA6juDCPg.png" /></figure><p>Hello there, I always loved using JQuery even when the <em>callback hell</em> is a reality for big projects, so quoting one of my favorite Python speakers <strong>Raymond Hettinger.</strong></p><blockquote>There must be a better way!</blockquote><p>And it is, introducing <strong>Vuejs</strong> as a simple replacement for <strong>JQuery</strong> in your <strong>Django</strong> projects.</p><p>So what are the advantages:</p><ul><li>Simple app state management.</li><li>Full reactive.</li><li>No need to compile and serve your front end as you would with the normal Vuejs app.</li></ul><p>Disadvantages:</p><ul><li>Difficult to abstract components in the Vue way but you can get creative use Django template inheritance.</li></ul><h4>Let’s drill in</h4><p>All can be resumed in 2 steps:</p><ol><li>Create a <a href="https://ccbv.co.uk/projects/Django/3.0/django.views.generic.base/TemplateView/">TemplateView</a> to serve your Vuejs mini SPA app e.g.</li></ol><pre># contacts/views.py</pre><pre>...<br>class ContactsView(<strong>TemplateView</strong>):<br>    &quot;&quot;&quot;[summary]<br>    Serves the base web page for contacts.</pre><pre>    [description]<br>    &quot;&quot;&quot;<br>    <strong>template_name = &#39;contacts.html&#39;<br>...</strong></pre><p>The recommended way to think of every <strong>template</strong> served is as a <strong>mini SPA app</strong>, meaning that you should try to include all the functionality needed for this mini SPA related to… <em>contacts,</em> in this case, trying to minimize not to serve more templates related to… you gues correctly <em>contacts</em>.</p><p>2. Create a template contacts.html which should include the Vue app, in this example, we’re going <strong>create</strong>, <strong>retrieve</strong>, <strong>update</strong>, <strong>delete</strong> and <strong>search</strong> for <em>contacts.</em></p><p>At contacts.html you should include all this functionality just mentioned obviously at the <strong>frontend</strong> (JS/CSS/HTML) level.</p><p>At contacts/views.py you should do the same but at the <strong>backend</strong> (Views, ulrs, etc) level.</p><p>Here is the full contacts/views.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53278065c657de9747ff855d460b9918/href">https://medium.com/media/53278065c657de9747ff855d460b9918/href</a></iframe><p>And the full contacts.html template</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d395b2bce56c066315b7af0d33290bc9/href">https://medium.com/media/d395b2bce56c066315b7af0d33290bc9/href</a></iframe><p>The most important bits at lines 421 – 435</p><pre>...<br><strong>{% csrf_token %}</strong><br>  &lt;script src=&quot;<a href="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js">https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js</a>&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;<a href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js">https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js</a>&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;<a href="https://unpkg.com/axios/dist/axios.min.js">https://unpkg.com/axios/dist/axios.min.js</a>&quot;&gt;&lt;/script&gt;<br>  &lt;script&gt;<br>    <strong>axios.defaults.withCredentials = true;</strong><br>    new Vue({<br>      <strong>delimiters: [&#39;[[&#39;, &#39;]]&#39;],</strong><br>      el: &#39;#main&#39;,<br>      vuetify: new Vuetify(),<br>      props: {<br>        source: String,<br>      },<br>      data: {<br>        <strong>contactsURI: &quot;{% url &#39;contacts:items&#39; %}&quot;,</strong><br>        <strong>contactCSRF: document.getElementsByName(&quot;csrfmiddlewaretoken&quot;)[0].value,</strong><br>...</pre><p>When creating the Vue app new Vue({...}) the first thing to notice is</p><pre>...<br>delimiters: [&#39;[[&#39;, &#39;]]&#39;],<br>...</pre><p>This line is the most important one at your template, is basically tells Vuejs to use [[ and ]] as the Vuejs delimiters for entering and exiting Vuejs mode instead of using the {{ and }} default ones, since those <strong>conflict</strong> with the Django Templates ones but you can use whatever you want e.g.</p><pre>delimiters: [&#39;&lt;&lt;&#39;, &#39;&gt;&gt;&#39;],</pre><p>Or something odd like</p><pre>delimiters: [&#39;[&lt;^&#39;, &#39;^&gt;]&#39;],</pre><p>It depends on your personal preference, just make sure to avoid the Django Templates ones, otherwise, you’ll need to change them at the Django Template side which is more difficult.</p><p>Here is the full list that you should avoid <a href="https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#templatetag">https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#templatetag</a></p><p>To <em>POST/GET/PUT…</em> Requests, I’m using <a href="https://github.com/axios/axios">Axios</a> a Promise based HTTP client.</p><pre>...<br>  &lt;script src=&quot;<a href="https://unpkg.com/axios/dist/axios.min.js">https://unpkg.com/axios/dist/axios.min.js</a>&quot;&gt;&lt;/script&gt;<br>...</pre><p>Here is an example</p><pre>...<br>createOrUpdateContactItem: function () {<br>          if (this.$refs.contactItemform.validate()) {<br>            this.loadingCreateContact = true;<br>            let headers = {<br>              &quot;X-CSRFToken&quot;: this.contactCSRF,<br>            };<br>            let body = {<br>              &quot;name&quot;: this.contactName,<br>              &quot;job_title&quot;: this.contactJobTitle,<br>              &quot;company&quot;: this.contactCompany,<br>              &quot;email&quot;: this.contactEmail,<br>              &quot;contact_number&quot;: this.contactNumber,<br>              &quot;notes&quot;: this.contactNotes,<br>            }<br>            let method = &quot;post&quot;;<br>            let url = this.contactCreateURI<br>            if (this.contactEdit) {<br>              method = &quot;put&quot;;<br>              url = this.contactEditURI + &quot;/&quot; + this.contactEdit<br>            }<br>            <strong>axios({<br>              method: method,<br>              url: url,<br>              data: body,<br>              headers: headers,<br>            }).then(resp =&gt; {<br>              this.contactsFilter = this.contactName<br>              this.searchContactItems();<br>              this.dialog = false;<br>              this.contactEdit = null<br>              this.$refs.contactItemform.reset()<br>            }).catch(function (error) {<br>              if (error.response) {<br>                // The request was made and the server responded with a status code<br>                // that falls out of the range of 2xx<br>                console.log(error.response.data);<br>                console.log(error.response.status);<br>                console.log(error.response.headers);<br>              } else if (error.request) {<br>                // The request was made but no response was received<br>                // `error.request` is an instance of XMLHttpRequest in the browser and an instance of<br>                // http.ClientRequest in node.js<br>                console.log(error.request);<br>              } else {<br>                // Something happened in setting up the request that triggered an Error<br>                console.log(&#39;Error&#39;, error.message);<br>              }<br>              console.log(error.config);<br>            }).finally(() =&gt; {<br>              this.loadingCreateContact = false;<br>              this.$refs.contactItemform.resetValidation()<br>            });</strong><br>          }<br>        },<br>...</pre><p>You can find more examples <a href="https://github.com/axios/axios#request-method-aliases">here</a>.</p><p>If you are using Django’s <strong>Session</strong> <strong>authentication</strong> you’ll need to tell so to <strong>Axios</strong> :</p><pre>axios.defaults.withCredentials = true;</pre><p>If you ‘re using token authentication you can skip that line and send your tokens as you normally would (using request headers).</p><p>Also, notice how to use the Django templates tags</p><pre>...<br>contactsURI: &quot;{% url &#39;contacts:items&#39; %}&quot;,<br>...</pre><p>Here I’m creating a JS string &quot;...&quot; with a value of the result of {% url ‘contacts:items’ %} reverse named lookup of a Django view, using template tags {% and %} in a key-value object.</p><p>You can still use old school JS to get data elements e.g.</p><pre>...<br>contactCSRF: document.getElementsByName(&quot;csrfmiddlewaretoken&quot;)[0].value,<br>...</pre><p>In this example, we need the Django CSRF token that we embedded with</p><pre>...<br>{% csrf_token %}<br>...</pre><p>To send it as we normally would in the request headers.</p><p>Also, you can always use <a href="https://docs.djangoproject.com/en/3.0/ref/templates/language/#template-inheritance">Django Template Inheritance</a> and get creative in the way of abstracting templates.</p><p>3. At the backend side, you can use <a href="https://docs.djangoproject.com/en/3.0/topics/forms/">Django forms</a> or <a href="https://www.django-rest-framework.org/api-guide/views/">DRF</a> to catch all you Vuejs/Axios requests with an appropriated <a href="https://ccbv.co.uk/">CBV</a> or function views, you can find the full working example used for this article here</p><p><a href="https://github.com/Brunux/djnar">Brunux/djnar</a></p><p>Finally, I just like to show you the Vuejs components life cycle so you can know where to put your JS code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byyX8EW6mIhRsCBWwByNYg.png" /></figure><p>Checkout Vuejs documentation to understand how Vue app is loaded and managed:</p><p><a href="https://vuejs.org/v2/guide/instance.html">The Vue Instance - Vue.js</a></p><blockquote>I hope this was useful for you if so give it a clap and share it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f6b687887f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn: Docker, FastAPI, CI/CD, and Vue.js — Third Part CI/CD]]></title>
            <link>https://medium.com/@bruno.fosados/learn-docker-fastapi-ci-cd-and-vue-js-third-part-ci-cd-86025056490a?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/86025056490a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[fargate]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Wed, 27 Nov 2019 06:54:53 GMT</pubDate>
            <atom:updated>2019-11-27T23:15:03.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4Ex1uUhL93a3bHyC-TgPg.png" /></figure><h3>Learn: Docker, FastAPI, CI/CD, and Vue.js — Third Part CI/CD</h3><p>Hello there, this is the third part of a series of articles we’re going to learn about Continues Integration (CI) with <strong>GitHub Action</strong>s and Continues Delivery (CD) with <strong>AWS Fargate</strong> container service.</p><p>In the S<a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-second-part-backend-fastapi-cec2e1e093a9?source=friends_link&amp;sk=ae1b0a3bbe1a1355970f1987a36dcc80">econd Part</a> of this series we focused on <strong>FastAPI</strong>, we added a sub-app pet and we’ve written some <strong>models</strong> and <strong>views</strong> (routes) with <strong>CRUD</strong> asynchronous operations on <strong>MongoDB</strong>.</p><p>In the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-first-part-docker-setup-a8e4c09ef9c4?source=friends_link&amp;sk=e0dc9637ee57c5dd9a3772f0fb48370f">First Part</a>, we did the project setup, we learn about <strong>Docker</strong> and <strong>docker-compose</strong>, and base <strong>FastAPI</strong> project layout.</p><p>For this part I suggest cloning our working repo with:</p><pre>git clone -b pre-part3 https://github.com/rescaty/mvp.git</pre><p>I’ve reorganized the file structure so now it looks like this:</p><pre>.<br>├── .gitignore<br>├── README.md<br>├── backend<br>│   ├── Dockerfile<br>│   ├── __init__.py<br>│   ├── config<br>│   │   ├── __init__.py<br>│   │   ├── config.py<br>│   │   ├── config.sample.yml<br>│   │   ├── config.yml<br>│   │   └── test_config.py<br>│   ├── core<br>│   │   ├── __init__.py<br>│   │   ├── routes.py<br>│   │   └── test_core.py<br>│   ├── main.py<br>│   ├── pets<br>│   │   ├── __init__.py<br>│   │   ├── models.py<br>│   │   ├── routes.py<br>│   │   └── test_pets.py<br>│   └── requirements.txt<br>└── docker-compose.yml</pre><p>As you can see main.py file is directly a child of backend folder so do pet config sub-apps and our Dockerfile and requirements.txt for the backend (called internally <em>tancho)</em> also we added a new core sub-app I’ll talk more about this app, later on, don’t worry about it for now.</p><p>Our docker-compose file is at the root level.</p><p>Notice that we added some test for all our sub-apps e.g. test_pets.py, test_config.py, andtest_core.py, Let’s check them.</p><p><strong><em>conf/test_config.py</em></strong> file</p><pre>from .config import load_config</pre><pre>def test_config():<br>    conf = load_config()<br>    conf_values = [<br>        &quot;HOST&quot;,<br>        &quot;PORT&quot;,<br>        &quot;NAME&quot;,<br>    ]<br>    for value in conf_values:<br>        assert bool(<br>            conf.get(&quot;databases&quot;, {}).get(&quot;default&quot;, {}).get(value, &quot;&quot;)<br>        ) is True, f&quot;{value}, not found on config.yml&quot;</pre><p>This’s a simple test in which we want to check whether or not the values for HOST, PORT, NAME has been defined:</p><pre>assert bool(<br>            conf.get(&quot;databases&quot;, {})...get(value, &quot;&quot;)<br>        ) is True, f&quot;{value}, not found on config.yml&quot;</pre><p>an error is raised f”{value}, not found on config.yml” we need to make sure those values exist so our connection with the MongoDB can be established.</p><p>So how can we run our tests? First, let&#39;s build our containers, at the root folder with:</p><pre>$ docker-compose build</pre><p>After that, set up our configuration file with:</p><pre>$ cd backend/config<br>$ cp config.sample.yml config.yml</pre><p>Make sure to use the same USER and PASSWORD for default DB settings if you had built the containers before. If this is the first build it should work out-of-the-box.</p><p>Make sure no other containers are running with the same ports and run:</p><pre>$ docker-compose down &amp;&amp; docker-compose up</pre><p>You should have an output like this:</p><pre>...<br>mongo_1   | 2019-11-26T21:51:27.509+0000 I  NETWORK  [initandlisten] Listening on /tmp/mongodb-27017.sock<br>mongo_1   | 2019-11-26T21:51:27.509+0000 I  NETWORK  [initandlisten] Listening on 0.0.0.0<br>mongo_1   | 2019-11-26T21:51:27.510+0000 I  NETWORK  [initandlisten] waiting for connections on port 27017<br>mongo_1   | 2019-11-26T21:51:27.511+0000 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: &lt;unsharded&gt;<br>tancho_1  | INFO:     Uvicorn running on <a href="http://0.0.0.0:8000/">http://0.0.0.0:8000</a> (Press CTRL+C to quit)<br>tancho_1  | INFO:     Started reloader process [1]<br>tancho_1  | INFO:     Started server process [8]<br>tancho_1  | INFO:     Waiting for application startup.<br>tancho_1  | INFO:     Application startup complete.</pre><p>Which means our app is up and running. Open a new terminal or a new terminal tab and go to the root folder, then run:</p><pre>$ docker-compose exec tancho /bin/bash</pre><p>With this command, we’re attaching out terminal to the tancho container so we can run commands inside the containers.</p><p>So now that we’re inside the container make sure that you are at the /tancho directory (which you should be because we defined so in the at the dockerfile with the WORKDIR parameter) and run:</p><pre>$ python -m pytest</pre><p>You should see an output like this:</p><pre>...<br>pets/test_pets.py::test_add_a_pets<br>pets/test_pets.py::test_get_all_pets<br>pets/test_pets.py::test_get_a_pet_by_id<br>pets/test_pets.py::test_update_a_pet_by_id<br>pets/test_pets.py::test_update_a_pet_by_id<br>pets/test_pets.py::test_delete_a_pets<br>  /usr/local/lib/python3.8/site-packages/bson/__init__.py:1098: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for &#39;#&#39; formats<br>    return decode_all(data, codec_options)</pre><pre>-- Docs: <a href="https://docs.pytest.org/en/latest/warnings.html">https://docs.pytest.org/en/latest/warnings.html</a><br><strong>============= 7 passed, 105 warnings in 1.51s ============</strong></pre><p>Notice the last line it the resume of our test, saying that 7 tests ware perform and 7 passed, don’t worry about the warnings for now. They’re related to the libraries that we are using.</p><p>We’ve only seen one test file, let’s see the next five at <strong><em>pets/test_pets.py</em></strong><em> </em>file</p><pre>from starlette.testclient import TestClient</pre><pre>...<br>client = TestClient(pets_router)</pre><pre>...</pre><pre>def test_add_a_pets():<br>    response = _insert_pet()<br>    assert response.status_code == 201, &quot;Not able to ADD a new pet&quot;</pre><pre>def test_get_all_pets():<br>    response = client.get(&quot;/&quot;)<br>    assert response.status_code == 200, &quot;Not able to GET pets&quot;</pre><pre>def test_get_a_pet_by_id():<br>    if not pets_ids:<br>        _insert_pet()<br>    assert bool(pets_ids), &quot;Not able to ADD a new pet to later GET it by ID&quot;</pre><pre>response = client.get(f&quot;/{pets_ids[0]}&quot;)<br>    assert response.status_code == 200, &quot;Not able to GET pet by ID&quot;</pre><pre>def test_update_a_pet_by_id():<br>    if not pets_ids:<br>        _insert_pet()<br>    assert bool(pets_ids), &quot;Not able to ADD a new pet to later UPDATE on it&quot;</pre><pre>    pet_oddy = dict(pet_guero)<br>    pet_oddy.update({&quot;name&quot;: &quot;Oddy&quot;})</pre><pre>    response = client.put(f&quot;/{pets_ids[0]}&quot;, json=pet_oddy)<br>    assert response.status_code == 200, &quot;Not able to UPDATE pet&quot;</pre><pre>def test_delete_a_pets():<br>    if not pets_ids:<br>        _insert_pet()<br>    assert bool(pets_ids), &quot;Not able to ADD a new pet to later DELETION&quot;</pre><pre>    for index, pet in enumerate(pets_ids):<br>        response = client.delete(f&quot;/{pet}&quot;)<br>        assert response.status_code == 200, &quot;Not able to DELETE a pet by ID&quot;<br>        del pets_ids[index]</pre><p>Here we are testing all our pet&#39;s endpoints which are CRUD operations. Let’s see one example:</p><pre>from starlette.testclient import TestClient</pre><pre>...<br>client = TestClient(pets_router)</pre><pre>...<br>def test_get_all_pets():<br>    response = client.get(&quot;/&quot;)<br>    assert response.status_code == 200, &quot;Not able to GET pets&quot;</pre><p>First, we need an HTTP test client to make the request to our endpoints</p><pre>...<br>client = TestClient(pets_router)<br>...</pre><p>The TestClient, needs and <em>FastAPI</em> instance or a <em>Router</em> instance so we pass our pets_router then the client is ready to use.</p><p>All our test are recognized by pytest module due to the prefix test_ at the function definition and file name e.g. test_get_all_pets() and test_pets.py so have this in mind when writing your test.</p><pre>response = client.get(&quot;/&quot;)</pre><p>We make the <em>request</em> to our pets_router endpoint “/” using our client get method and that would be https://localhost/pets/ if we think in a full URL way, but it’s actually &quot;/&quot; since we are using a router instance for the client remember? check pets/routes.py file for more details about it or the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-second-part-backend-fastapi-cec2e1e093a9?source=friends_link&amp;sk=ae1b0a3bbe1a1355970f1987a36dcc80">Second Part</a> of this series.</p><p>The actual testing happens here:</p><pre>assert response.status_code == 200, &quot;Not able to GET pets&quot;</pre><p>When we’re trying to assert for response.status_code == 200 if this is not True an exception is raised with a message “Not able to GET pets”. Then not passing the test, but if its True the test is passed, and we know it should be 200 for a success response at this endpoint ‘cos, we defined like that at the endpoint definition.</p><p>So now that we have some tests we could integrate them into our CI process, in fact, we’re not only adding the tests but also linting our code.</p><p>So what is Linting? In simple words is to check our code to adhere to a good <a href="https://www.python.org/dev/peps/pep-0008/">Style Guide of Python Code</a>, we want code that is easy to read or well written.</p><p>So for that let&#39;s lint our code, inside our container terminal run:</p><pre>$ pip install flake8<br>$ flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics<br>$ flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics</pre><p>The first line is installing flake8 linter tool, then the second and third line the actual linting. So now lest’s create our actual CI pipeline.</p><h3>GitHub Actions / CI</h3><p>So what&#39;re GitHub Actions? In simple words are <em>actions</em> that are triggered by GitHub e.g. when you push a commit or when you marge a branch. The <em>action</em> needs to be predefined so let&#39;s create one.</p><p>First, you need to have a GitHub account if you don’t have one <a href="https://github.com/join">create it here</a>.</p><ul><li>Log in to GitHub.</li><li>Click the <a href="https://github.com/new">new repository</a> button in the top-right. You’ll have an option there to initialize the repository with a README file.</li><li>Click the “Create repository” button.</li></ul><p>Now at the root of our project run:</p><pre>$ git init</pre><pre>$ git add .</pre><pre>$ git commit -m &quot;first commit&quot;</pre><pre>$ git remote add origin https://github.com/<strong>your_username</strong>/<strong>new_repo_name</strong></pre><pre>$ git push -u origin master</pre><p>With this, we basically upload all our code to our newly created repo, replace your <strong>username</strong> and <strong>new repo name</strong> with the real values.</p><p>Now to at your GitHub repo and click in <strong>Actions</strong> tab then click on <strong>New workflow</strong> button, then select<em> Python Application</em> by clicking in <strong>Set up this workflow</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3WK5XybUAxBx0OQFQYXVQ.png" /></figure><p>You’ll see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbCUnv2EXbyXujK4MXh5MQ.png" /></figure><p>Give it a name I called mine backend.yml but you can call it whatever makes more sense to you.</p><p>Now replace the code with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb712fa496035d15ada30c8a27b9437/href">https://medium.com/media/8bb712fa496035d15ada30c8a27b9437/href</a></iframe><p>What GitHub does is create a workspace, think of this workspace as an ubuntu box, inside this workspace, our code is copied and it is ready for the <em>action</em> to take place this happens in the form of <em>steps</em> (commands) think of this steps as a bash script running commands.</p><p>The important bits are:</p><pre>...</pre><pre>on: [push]</pre><pre>...</pre><p>Here we defined that with evert push these <em>steps </em>should run:</p><pre>...<br>cd backend/<br>pip install -r requirements.txt<br>sudo docker run --name mongo -d -p 27017:27017 mongo</pre><pre>...</pre><p>In this step, we’re moving to our <em>backend</em> directory where all our code is including our requirements.txt file then using pip we install all libraries and finally, we run a MongoDB docker instance, this is needed for our tests since they’re creating and updating items on it.</p><pre>...</pre><pre>pip install flake8<br>cd backend/<br># stop the build if there are Python syntax errors...<br>flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics        # exit-zero treats all errors as warnings. The GitHub editor...<br>flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics<br>...</pre><p>In this step, we use flake8 linter to check our code for us just like we did manually. If there are errors the build will fail showing what fails, giving us a chance to fix the linting error shown.</p><pre>...</pre><pre>pip install pytest<br>cd backend/<br>python -m pytest</pre><p>In this step, we’re run our tests notice that we run pytest as a python module with the -m parameter, this due to that we’ve modularized our app with sub-app e.g. pets, config, core.</p><p>So once you have updated the code click on Start commit green button then Commit new file button optionally if you like you can fill the form otherwise is going to use the default values shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMeknvFv11vfMRAHLoB9YA.png" /></figure><p>That’s gonna commit the file we just created, now every time we commit to our repo the CI pipeline is going lint and test our code for us, how cool is that!!.</p><p>Make sure to get this last commit to our local repo since it’s living only in the GitHub server and not in our local machine yet. Inside our root directory run:</p><pre>$ git fetch &amp;&amp; git pull</pre><p>To test this CI pipeline, make a commit to your repo, lets say, edit README.md file add some dummy text commit the change and push the commit.</p><pre>$ git add README.md<br>$ git commit -m &quot;Testing CI&quot;<br>$ git push</pre><p>The GitHub action that we just configured should start right after the push, Go to the GitHub repo and click on <strong>Actions </strong>tab to see the output, now let&#39;s jump to our CD pipeline.</p><h3>Amazon Fargate (ECS) / CD</h3><p>So what’s Amazon Fargate?</p><blockquote>AWS Fargate is a compute engine for Amazon ECS that allows you to run containers without having to manage servers or clusters.</blockquote><p>I’ve to say that these <strong>firsts steps</strong> are kind of tedious if you don’t have an AWS account already created and configured. I’m going to resume the steps and give you links to help you with the steps.</p><ul><li>If you don’t have an AWS account <a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/">create one</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html">Install</a> and <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#cli-quick-configuration">Setup</a> the aws-cli tool.</li><li>Ensure that your AWS user has the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html">required permissions</a>, basically, you need to add this to your user AmazonEC2ContainerRegistryFullAccess</li><li>Ensure that you have an ecsTaskExecutionRole IAM role in your account. If you don’t have it you’ll have to create it. Follow this <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html">guide</a> on how to check if it is already or to create it.</li></ul><p>Once you have all of this setup we can create our pipeline, first, we need a repo to store our tancho container image let’s create one on AWS</p><pre>aws ecr create-repository --repository-name rescaty-mvp-repo --region us-west-2</pre><p>Here we called our repo rescaty-mvp-repo on the us-west-2 region, <strong>so make sure that everything you create or build is in the same region </strong><strong>us-west-2 in this case.</strong></p><p>Also, we need to create a tasks-definition think of this as a docker-compose file just like the one we created on the First Part of this series this task-definition is used by <strong>Fargate</strong> engine.</p><p>At the root of our project create a new folder called aws inside create a file called tacho-task-def.json add this content to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ffe9602b133702067d5cb2eb5750818/href">https://medium.com/media/4ffe9602b133702067d5cb2eb5750818/href</a></iframe><p>Let&#39;s break this file…</p><pre>{<br>    &quot;family&quot;: &quot;tancho-task&quot;,<br>    &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>    &quot;volumes&quot;: [<br>        {<br>            &quot;name&quot;: &quot;mongo-data&quot;<br>        }<br>    ],</pre><p>family is basically a name for our task-definition.</p><p>awsvpc as <em>network mode</em> means that AWS is going to manage the networking for us, and I think is the only way supported by Fargate but not sure.</p><p>volumes work the same way as docker volumes do, but the way we defined them makes them ephemeral, meaning that all your volumes are going to be deleted when the container gets down. Later we’re going to change this to use AWS could storage service, so for now, that’s ok.</p><p>Now the cool part, our containers per se:</p><pre>    ... <br>    &quot;containerDefinitions&quot;: [<br>        {<br>            <strong>&quot;name&quot;: &quot;tancho&quot;</strong>,<br>            &quot;image&quot;: &quot;python:3.8&quot;,<br>            &quot;portMappings&quot;: [<br>                {<br>                    &quot;containerPort&quot;: 80,<br>                    &quot;hostPort&quot;: 80,<br>                    &quot;protocol&quot;: &quot;tcp&quot;<br>                }<br>            ],<br>            &quot;essential&quot;: true,<br>            &quot;entryPoint&quot;: [<br>                &quot;sh&quot;,<br>                &quot;-c&quot;<br>            ],<br>            &quot;command&quot;: [<br>                &quot;/bin/sh -c \&quot;cd /tancho &amp;&amp; uvicorn main:app --host 0.0.0.0 --port 80\&quot;&quot;<br>            ],<br>            &quot;logConfiguration&quot;: {<br>                &quot;logDriver&quot;: &quot;awslogs&quot;,<br>                &quot;options&quot;: {<br>                    &quot;awslogs-group&quot;: &quot;/ecs/tancho-task&quot;,<br>                    &quot;awslogs-region&quot;: &quot;us-west-2&quot;,<br>                    &quot;awslogs-stream-prefix&quot;: &quot;tancho-&quot;<br>                }<br>            }<br>        },<br>        {<br>            <strong>&quot;name&quot;: &quot;mongo&quot;</strong>,<br>            &quot;image&quot;: &quot;mongo&quot;,<br>            &quot;mountPoints&quot;: [<br>              {<br>                &quot;sourceVolume&quot;: &quot;mongo-data&quot;,<br>                &quot;containerPath&quot;: &quot;/data/db&quot;<br>              }<br>            ],<br>            &quot;essential&quot;: true<br>        }<br>    ],</pre><p>As you can see it looks pretty similar to our docker-compose.yml file, we covered it on the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-first-part-docker-setup-a8e4c09ef9c4?source=friends_link&amp;sk=e0dc9637ee57c5dd9a3772f0fb48370f">First Part</a> of this series.</p><p>So I think the only part that is not so obvious is:</p><pre>          &quot;logConfiguration&quot;: {<br>                &quot;logDriver&quot;: &quot;awslogs&quot;,<br>                &quot;options&quot;: {<br>                    &quot;awslogs-group&quot;: &quot;/ecs/tancho-task&quot;,<br>                    &quot;awslogs-region&quot;: &quot;us-west-2&quot;,<br>                    &quot;awslogs-stream-prefix&quot;: &quot;&quot;<br>                }<br>            }</pre><p>The “awslogs-group”: “/ecs/tancho-task” specify where do we want to log the output of our app, we’re going to use AWS cloud log services, we’ve to create these services but don’t worry about it, we’re going to use a wizard for that in a little bit. Now when creating this we’ve to make sure to create it on us-west-2 region since we’re defining so.</p><p>Last but not least.</p><pre>    &quot;cpu&quot;: &quot;256&quot;,<br>    &quot;memory&quot;: &quot;512&quot;,<br>    &quot;<strong>executionRoleArn</strong>&quot;: &quot;arn:aws:iam::2024449954452:role/ecsTaskExecutionRole&quot;</pre><p>cpu:256 says we’re going to use a 0.25 CPU and memory:512 with a 512 MB of RAM.</p><p>The important part is the executionRoleArn <strong>you have to replace the value of this with your own account ID</strong> e.g. 2024449954452. If you don’t do this your pipeline <strong>is just not going to work</strong>, so make sure to create the role and update this line, we mentioned this on the <strong>firsts steps.</strong></p><p>Now commit and push this file to our repo</p><pre>$ git add aws/tancho-task-def.json<br>$ git commit -m &quot;Add AWS Fargate task-definition for backend&quot;<br>$ git push</pre><p>Now let’s create all infrastructure that our task definition (containers) needs to run including the logger, for this we’re going to use an AWS wizard got to this link:</p><pre><a href="https://us-west-2.console.aws.amazon.com/ecs/home?region=us-west-2#/firstRun">https://us-west-2.console.aws.amazon.com/ecs/home?region=us-west-2#/firstRun</a></pre><p>You’re going to see an image like this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9mFOWNDD1qV3HHZcDKBVQ.png" /></figure><p>Select <strong>Nginx</strong> and click on the <strong>edit</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oClMGXVTlcUE2PNOTQpDg.png" /></figure><p>Change the Container name and Image then click on Advanced container configurations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXMAjY4uCiNCpzjSLJ8gtw.png" /></figure><p>Update logger configuration variables: awslogs-group , awslogs-region , awslogs-stream-prefix to match our tancho-task-def.json→Containers → tancho → logs, then click update button, then click Next button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceYtFNcNv9g2Cu20GGDnpw.png" /></figure><p>In here notice the <strong>service name</strong> is tancho-service we’re going to need this value later, and click on <strong>Application Load Balancer</strong> so we can get load balancer for our app, then click Next button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzElHsN3w8mkt63OrBDxAQ.png" /></figure><p>Change the <strong>Cluster</strong> <strong>name</strong> to rescaty and click Next button.</p><p>Then a resume of all the configuration is shown to you just click Create button.</p><p>AWS is going to start creating all the infrastructure that our containers need to communicate with the outside world e.g. VPC, Gateway, Routing table, Subnets, load balancer, logger, etc.</p><p>So at this point, we are almost done with AWS.</p><p>Go to your GitHub repo <strong>Settings</strong> tab, select <strong>Secrets</strong> from the left menu, click <strong>add new secret</strong></p><p>You need to add two, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for the values of those you need to go to AWS → IAM service → Users, then select your user and click on <strong>Security credentials</strong> tab then click on <strong>create access key</strong> button, then assign the values shown to your GitHub secrets.</p><p>Now its time to set up an <em>action</em> for this pipeline on GitHub, go to actions at your repo and click on <strong>New workflow</strong> button, then select <strong>Deploy to Amazon ECS</strong> by clicking on <strong>Set up this workflow</strong> button. An screen like this will be shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63p5f1wkK2cTIzAeF-3dig.png" /></figure><p>Then replace the content with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4038799674c7957c63ad65a8888dfb0/href">https://medium.com/media/e4038799674c7957c63ad65a8888dfb0/href</a></iframe><p>All the instructions at the beginning are basically what we’ve done, the important bits are:</p><pre>on:<br>  <strong>push</strong>:<br>    branches:<br>      <strong>- master</strong></pre><p>This action is going to run on pushes to master branch only.</p><pre>...<br>      with:<br>        <strong>aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>        aws-region: us-west-2</strong><br>...</pre><p>The secrets that we defined in the previous step and the region.</p><pre>...<br>      env:<br>        ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}<br>        <strong>ECR_REPOSITORY: rescaty-mvp-repo</strong><br>        IMAGE_TAG: ${{ github.sha }}<br>...</pre><p>The repository that we created for our tancho docker image rescaty-mvp-repo</p><pre>...<br>        # Build a docker container and<br>        # push it to ECR so that it can<br>        # be deployed to ECS.<br>        <strong>cd backend<br>        docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .<br>        docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG</strong><br>        echo &quot;::set-output name=image::$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG&quot;<br>...</pre><p>The commands to build our tancho image and push the image to our repo rescaty-mvp-repo.</p><pre>...<br>      with:<br>        <strong>task-definition: aws/task-def-backend.json<br>        container-name: tancho</strong><br>        image: ${{ steps.build-image.outputs.image }}<br>...</pre><p>The task definition file and the container name tancho to be used.</p><pre>...<br>      with:<br>        task-definition: ${{ steps.task-def.outputs.task-definition }}<br>        <strong>service: tancho-service<br>        cluster: rescaty</strong><br>        wait-for-service-stability: true<br>...</pre><p>Finally information about the cluster and service that we created on AWS Fargate with the wizard.</p><p>Commit this file as we did with the CI one and get the file to our local repo as we also did for the CI.</p><p>To test this pipeline on the master branch commit and push a change the action should start right after the push, same as we did for the CI.</p><p>Remember our new sub-app called core? Well this app defines one endpoint at the root of our URL / this is used by the load balancer and Fargate to check if our app is healthy if the app is not, it restarts the containers (tasks definition) we need it so our app is not continuously restarting.</p><p>Go to AWS →ECS → Clusters →rescaty →Service: tancho-service</p><p>Click on the load balancer and find the <strong>DNS name</strong> mine is EC2Co-EcsEl-7IAJ90C19YQW-1281948353.us-west-2.elb.amazonaws.com you can use this to access your newly created cloud-native app <strong><em>Tancho</em></strong><em>. Y</em>ou can optionally use a <em>.com</em> domain to point to that long domain like we’re going to do, later on, so your users can access your web app like <em>rescaty.com </em>instead of the long domain name.</p><p>You can get all the working code done in this part from GitHub:</p><pre>git clone -b part3 https://github.com/rescaty/mvp.git</pre><p>If you like this article please give it a clap, share it with your friends, <a href="https://twitter.com/brunuxcom">follow me on twitter</a> for more articles, you can twit me if you have any questions.</p><p>In the Fourth Part, we’re going to add Vue.js client app and we’re going to include end to end testing, including integration tests too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86025056490a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Learn: Docker, FastAPI and Vue.js — Second Part Backend (FastAPI).]]></title>
            <link>https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-second-part-backend-fastapi-cec2e1e093a9?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/cec2e1e093a9</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 03:15:32 GMT</pubDate>
            <atom:updated>2019-11-27T23:32:04.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*du7p50wS_fIsaC_lR18qsg.png" /></figure><h3>Learn: Docker, FastAPI, CI/CD, and Vue.js — Second Part Backend (FastAPI).</h3><p>Hello there, this a series of articles about learning Docker, FastAPI, and Vue.js if you haven’t read the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-first-part-docker-setup-a8e4c09ef9c4?source=friends_link&amp;sk=e0dc9637ee57c5dd9a3772f0fb48370f"><strong>First Part</strong></a> I encourage you to do so there you’ll find the base project setup using Docker and docker-compose.</p><h3>Prerequisites</h3><ul><li>You should be familiar with the Python Typing system here is a <a href="https://blog.daftcode.pl/first-steps-with-python-type-system-30e4296722af">nice article </a>to get you started this is not a must but it will help.</li></ul><h3>FastAPI</h3><p>In the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-first-part-docker-setup-a8e4c09ef9c4?source=friends_link&amp;sk=e0dc9637ee57c5dd9a3772f0fb48370f">First Part</a> of this series of articles, we did the <a href="https://github.com/tiangolo/fastapi"><strong>FastAPI</strong></a> setup, but we haven’t talked much about what is FastAPI and how it could be beneficial for our projects, so let&#39;s dig in.</p><h4>Whats FastAPI?</h4><blockquote>FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.</blockquote><p>It shares some similarities with <a href="https://palletsprojects.com/p/flask/"><strong>Flask</strong></a> and <a href="https://www.django-rest-framework.org/"><strong>D</strong>jango <strong>R</strong>est <strong>F</strong>ramework</a> I personally prefer <strong>DRF</strong> over <strong>Flask</strong> I found it better structured with tons of pluggable apps from the community with zero o very little effort to integrate, in the other hand with <strong>Flask </strong>you have to actually do some <em>tricks </em>to integrate those apps. There is also commonly said that <strong>Django/DRF </strong>comes with batteries included this is due to the <strong>Django</strong> ecosystem which comes with:</p><ul><li><strong>Authentication system</strong> with many authentications types e.g. Session, Token, Basic Auth, JWT and more… Most of the time they work out-of-the-box or very little configuration.</li><li><strong>Security</strong>, Cross-site scripting (XSS) protection, Cross-site request forgery (CSRF) protection, SQL injection protection, Clickjacking protection…</li><li><strong>First-class documentation</strong>, I just can’t stress this enough, awesome documentation.</li><li><strong>Content administration.</strong></li><li><strong>Site maps.</strong></li><li><strong>RSS feeds.</strong></li><li><strong>ORM, Routing, Forms, Templates and many more…</strong></li></ul><p>You can actually have all of that with <strong>Flask</strong> if you’re willing to spend some time doing so, and not actually working in what matters <em>coding your app</em>. Here is a <a href="https://testdriven.io/blog/django-vs-flask/">cool article</a> comparing both frameworks and how to get all those mentioned features with Flask.</p><p>I’ve used <strong>DRF </strong>and<strong> Flask</strong> to create apps and micro-services, they perform well and both scale. But I always felt unconformable somehow with <strong>Flask</strong> since in most of cases when using <strong>Flask</strong> we end up adding most of the important parts of <strong>Django/DRF</strong> ecosystem.</p><p>Does it worth to use <strong>Flask</strong> over <strong>Django/DRF</strong>? I would say if you’re pretty sure that your app/micro-service is not gonna change ever, I’d suggest use <strong>Flask</strong> since its simple, but if you’re unsure or you just want to be prepare for changes like I do, use <strong>Django/DRF</strong>.</p><p>But wait what about <strong>FastAPI</strong>? The way I see <strong>FastAPI</strong> is what I would like <strong>Flask</strong> should it be, a simple, lightweight web framework that actually does but with batteries included specialized in APIs/micro-services. When I met <strong>FastAPI</strong> I just fell in love with it since this is what it promises to bring to our world and it truly does.</p><p>It’s perfect for ML &amp; AI apps/micro-services due to its <strong><em>asynchronous</em></strong> nature, so what are the main features of FastAPI?</p><p>Since it&#39;s based on <a href="https://www.starlette.io/">starlette</a> from it you get:</p><ul><li>Seriously impressive performance on par to Go &amp; NodeJS.</li><li>WebSocket support.</li><li>GraphQL support.</li><li>In-process background tasks.</li><li>Startup and shutdown events.</li><li>Test client built on requests.</li><li>CORS, GZip, Static Files, Streaming responses.</li><li>Session and Cookie support.</li></ul><p>From <strong>FastAPI</strong> per se:</p><ul><li><a href="https://github.com/OAI/OpenAPI-Specification"><strong>OpenAPI</strong></a> for API creation, including declarations of path operations, parameters, body requests, security, etc.</li><li>Automatic data model documentation with <a href="http://json-schema.org/"><strong>JSON Schema</strong></a> (as OpenAPI itself is based on JSON Schema).</li><li>This also allows using automatic <strong>client code generation</strong> in many languages.</li><li>Automatic docs <a href="https://github.com/swagger-api/swagger-ui"><strong>Swagger UI</strong></a>, with interactive exploration, call and test your API directly from the browser. <strong>Would you like to see it working?</strong> At the root folder of the project /mvp run the project container docker-compose up if it&#39;s not running already and point your browser to http://localhost:8000/docs</li><li>Alternative API documentation with <a href="https://github.com/Rebilly/ReDoc"><strong>ReDoc</strong></a>. Point your browser to <a href="http://localhost:8000/docs">http://localhost:8000/redoc</a></li><li>Based on standard <strong>Python 3.6 type</strong> declarations (thanks to Pydantic).</li><li>Validations based on <strong>type</strong> declarations.</li><li>Security and authentication.</li><li>Dependency Injection.</li><li>100% tested and more…</li></ul><p>OK, I think that&#39;s enough of selling<strong> Django/DRF</strong> and <strong>FastAPI.</strong></p><h3>App Configuration</h3><p>Create a folder call config inside it create an empty file called __init__.py with this file, we’re telling python to acknowledge our config folder as a module also create config.py and config.yml this last file is going to store the actual configuration and with the help of config.py we’re going to load it.</p><pre>.<br>|____tancho<br>| |____config<br>| | |____config.py<br>| | |____ __init__.py<br>| | |____config.yml<br>...</pre><p>Open config.yml file and add:</p><pre># backend/tancho/config/config.yml</pre><pre>fastapi:<br>  debug: true</pre><pre>databases:<br>  default:<br>    ENGINE: &#39;mongodb&#39;<br>    DRIVER: &#39;motor&#39;<br>    NAME: &#39;tancho_db&#39;<br>    USER: &#39;tancho_user&#39;<br>    PASSWORD: &#39;4dm1n4dm1n&#39;<br>    HOST: &#39;mongo&#39;<br>    PORT: &#39;27017&#39;</pre><p>Here we’re just defining a default Data Base to use, I choose <strong>MongoDB</strong> for the fast performance an because in future we’re going to add ML models.</p><p>Open config.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a01150f5d13dae27809c1b1c7e705b/href">https://medium.com/media/b5a01150f5d13dae27809c1b1c7e705b/href</a></iframe><p>Here we’re just reading the configuration file and make it available for all modules to import it as is the case with the DB client.</p><p>Also let&#39;s update our requirements.txt file to include a <strong>MongoDB</strong> Python driver called motor since we’re already using it on config.py</p><pre># backend/requirements.txt</pre><pre>fastapi[all]==0.42.0<br>motor==2.0.0</pre><p>So now let&#39;s add <strong>MongoDB</strong> Docker container at our docker-compose.yml file:</p><pre># backend/docker-compose.yml</pre><pre>version: &#39;3.1&#39;</pre><pre>volumes:<br>    mongo_data:</pre><pre>services:<br>  # Our main app<br>  tancho:<br>    build: .<br>    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload<br>    volumes:<br>      - ./tancho:/tancho<br>    ports:<br>      - &quot;8000:8000&quot;<br>    depends_on:<br>        - mongo</pre><pre>  # MongoDB as a service<br>  mongo:<br>    image: mongo<br>    restart: always<br>    environment:<br>      MONGO_INITDB_ROOT_USERNAME: &quot;tancho_user&quot;<br>      MONGO_INITDB_ROOT_PASSWORD: &quot;4dm1n4dm1n&quot;<br>    volumes:<br>        - mongo_data:/data/db<br>    ports:<br>      - &quot;27017:27017&quot;</pre><p>Notice that we give a name of mongo to our new container here:</p><pre>...<br>  # MongoDB as a service<br>  mongo:<br>...</pre><p>This way at our backend/tancho/config/config.yml file, the HOST parameter could be set as mongo</p><pre>...<br>    HOST: &#39;mongo&#39;<br>    PORT: &#39;27017&#39;</pre><p>Docker is smart enough to resolve the name mongo to our new container, internally docker creates a full LAN network for our container to communicate to each other via IP address but don’t worry about that, the way we just defined makes docker manage all of that for us with names as we did with mongo.</p><p>Also with environment we’re explicitly telling to MongoDB container to setup the main user with username “tancho_user” and password “4dm1n4dm1n” Normally you don’t want to hard code these values in the docker-compose.yml file, one option could be to load them from your OS environment variables in which case the declaration should be like this:</p><pre>...<br>environment:<br>      - MONGO_INITDB_ROOT_USERNAME<br>      - MONGO_INITDB_ROOT_PASSWORD<br>...</pre><p>Then export or create the environment variables in your terminal, so they could exist for docker to load them.</p><pre>$ export MONGO_INITDB_ROOT_USERNAME=&quot;tancho_usuer&quot;<br>$ export MONGO_INITDB_ROOT_PASSWORD=&quot;4dm1n4dm1n&quot;</pre><p>But for now let&#39;s just keep it simple with the hard code values.</p><p>We also create a volume named mongo_data to persist the <strong>MongoDB</strong> data</p><pre>...    <br>    volumes:<br>        - mongo_data:/data/db<br>...</pre><p>Think of volumes as virtual hard drives for our containers.</p><p>Also, we marked mongo as a dependency for tancho container here:</p><pre>...<br>tancho:</pre><pre>...<br>    depends_on:<br>        - mongo<br>...</pre><p>Now we need to rebuild our containers to reflect changes, open a terminal at the docker-compose.yml level file and run:</p><pre>$ docker-compose build</pre><p>It should start the building process, after that, just start the containers both our app tancho and mongo with:</p><pre>$ docker-compose down &amp;&amp; docker-compose up</pre><p>I like to run it this way to make sure any previous container left hanging around gets shut down, so the new ones can start from scratch.</p><p>By the way, you can stop the containers and take control back of the terminal pressing ctrl-c at any time, please note that the containers get to stop but they’re still hanging around, so after that, you should run docker-compose down for a full shutdown of them.</p><h3>App’s File Structure</h3><p>Let&#39;s create a new folder called pets this folder at mvp/tancho/ this is going to encapsulate everything related to pets, think of it as a <strong>sub-app</strong> for our project.</p><p>Make sure to add __init__.py files too since those are used to indicate to Python that the folder containing them are actually modules. Now inside our new pets directory create the files called models.py and routes.py so now your file structure should look like this:</p><pre>.<br>|____tancho<br>| |____config<br>...<br>| |____pets<br>| | |____models.py<br>| | |____ __init__.py<br>| | |____routes.py<br>...</pre><h3>Models</h3><p>open models.py and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74eaa5afc98e1d6d7a8d9d807c173126/href">https://medium.com/media/74eaa5afc98e1d6d7a8d9d807c173126/href</a></iframe><p>Things start to get interesting, lets breakdown this class by class.</p><pre>class PetState(str, Enum):<br>    &quot;&quot;&quot;[summary]<br>        Used to manage supported pet states.<br>    [description]<br>        Simple enumeration to link the pets state.<br>    &quot;&quot;&quot;<br>    injured = &quot;Injured&quot;<br>    underfed = &quot;Underfed&quot;<br>    critical = &quot;Critical&quot;<br>    bad = &quot;Bad&quot;<br>    good = &quot;Good&quot;</pre><p>PetState class uses Enums to represent actual states also it inherits from str to make the auto-generated docs to infer the right value in this case strings. We’re actually representing how a pet state could be: injured, underfed and so on.</p><pre>class PetKind(str, Enum):<br>    &quot;&quot;&quot;[summary]<br>        Used to manage supported pets.</pre><pre>[description]<br>        Simple enumeration to link the kind of a pet.<br>    &quot;&quot;&quot;<br>    dog = &quot;Dog&quot;<br>    cat = &quot;Cat&quot;</pre><p>Same here, we’re just representing which types of pets we support, cat or dog if we needed more e.g. coyote we would just add it as coyote = &quot;Coyote&quot;.</p><p>Using enums allow us to make object comparative like:</p><pre>pet.kind is PetKind.dog</pre><p>we’ll see how to use those objects to make filters, now let&#39;s check PetBase model:</p><pre>class PetBase(BaseModel):<br>    &quot;&quot;&quot;[summary]<br>        Base pet abstraction model.</pre><pre>[description]<br>        Used to abstract out basic pet fields.</pre><pre>Arguments:<br>        BaseModel {[type]} -- [description]<br>    &quot;&quot;&quot;<br>    kind: PetKind<br>    states: List[PetState]<br>    location: str<br>    picture: Optional[str] = None<br>    rescued: bool = False<br>    adopted: bool = False<br>    in_temp_house: bool = False<br>    ready_for_adoption: bool = False<br>    name: Optional[str] = None</pre><p>Here things get a bit more interesting because we’re actually defining an entity pet in fact, we’re abstracting this entity as a base class so we can be inheriting from it.</p><p>We add fields just by giving a name and a type e.g. location: str, we would optional give a default value e.g. rescued: bool = False false in this case also, notice we’re using our previous defined classes at kind: PetKind and states: List[PetState] to define the type for kind and state variables.</p><p>For the field name: Optional[str] = None we’re using the Optional type, we could instead define name field as name: str = None (without Optional) but this will give an error for the Pythons Typing system, since None (default value) is not an instance of str, so we use the typing.Optional to tell the typing system to accept None as a default value and str for the actual value when given at some point in the future.</p><p>Can you guess what this type of values accepts states: List[PetState]? You got it [PetStateInstance1, PetStateInstance2, PetStateInstance3, ...] a list of PetState instances.</p><p>Finally:</p><pre>class PetOnDB(PetBase):<br>    &quot;&quot;&quot;[summary]<br>    Actual model used at DB level</pre><pre>[description]<br>    Extends:<br>        PetBase<br>    Adds `_id` field.</pre><pre>Variables:<br>        _id: str {[ObjectId]} -- [id at DB]<br>    &quot;&quot;&quot;<br>    id_: str</pre><p>Which only adds id_: str, it&#39;s going to represent MongoDB ObjectId field more about this field later on.</p><h3>Routes</h3><p>Open the pets/routes.py file and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb10778d2f371dfcf3145d371c2731c/href">https://medium.com/media/fcb10778d2f371dfcf3145d371c2731c/href</a></iframe><p>Here things get a lot more interesting since here is where we’re actually defining our endpoints per se.</p><p>Notice line <strong>#12</strong> pets_router = APIRouter() think of a router as a mini FastAPI app instance, which actually has most of the methods of it including endpoints declaration.</p><h4>Update main.py</h4><p>Before we breakdown routers.py file lets connect our newly defined routes.py with our main.py app file, so open main.py and update it, should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/544a0834ab4c55454bf2a65f5aea6802/href">https://medium.com/media/544a0834ab4c55454bf2a65f5aea6802/href</a></iframe><p>Notice line <strong>#2</strong> from pets.routes import pets_router so what we want is to include all endpoint (routes) created in our routes.py file and we do so in line 8#</p><pre>app.include_router(<br>    pets_router,<br>    prefix=&quot;/pets&quot;,<br>    tags=[&quot;pets&quot;],<br>    responses={404: {&quot;description&quot;: &quot;Not found&quot;}},<br>)</pre><p>So here we’re telling FastAPI app to include our pets routes and prefix this routes with &quot;/pets&quot; and use the tags = [&quot;pets&quot;] for documentation, they will be added to the OpenAPI schema and used by the automatic documentation generation, also we add a preferred list of responses.</p><p>Functions defined at line <strong>#17</strong> &amp; <strong>#26</strong> have initialization and termination code that is run for us by the app on startup and shutdown of it.</p><h4>Back to routes.py</h4><p>Let&#39;s analyze how our endpoints are defined.</p><h4>Inset a pet on DB</h4><pre>@pets_router.post(&quot;/&quot;, <strong>response_model=PetOnDB</strong>)<br><strong>async</strong> def add_pet(<strong>pet: PetBase</strong>):<br>    &quot;&quot;&quot;[summary]<br>    Inserts a new pet on the DB.</pre><pre>[description]<br>    Endpoint to add a new pet.<br>    &quot;&quot;&quot;<br>    pet_op = <strong>await</strong> DB.pet.insert_one(pet.dict())<br>    if pet_op.inserted_id:<br>        pet = await _get_pet_or_404(pet_op.inserted_id)<br>        <strong>pet[&quot;id_&quot;] = str(pet[&quot;_id&quot;])</strong><br>        return pet</pre><p>Here we are using our pets_router remember it? It is an instance of APIRouter which is like a mini FastAPI app instance, so using the .post(...) decorator, we’re defining that when a request of type POST arrives at / (/pets/ due to the prefix=&quot;/pets” that we added at main.py remember?), It’ll be handled by our async (asynchronous) function called add_pet and when the request leaves (now called response), it will be kind of converted or <strong>serialized</strong> using response_model=PetOnDB, PetOnDB model that we previously defined.</p><p>So we’ve to make sure that in our function return a dictionary that can actually be converted to a PetOnDB object, so all fields must be there, so FastAPI can do this conversion or serialization for us, including the id_that we’re fixing in this line, pet[“id_”] = str(pet[“_id”]) but why are we doing this fix?</p><p>Mongo uses unique IDs for its documents and stores this on _id field on the DB per se but on the PetOnDB model we defined this ID as id_ instead of _id so, why we don’t use the ID name like mongo does with _id? because doing so we were declaring _id class property or field as private (isn’t actually private but prefixing variables with _ by convention means <em>private</em>) so the library that actually makes the lifting here is <a href="https://github.com/samuelcolvin/pydantic/">Pydantic</a> which is not serializing or converting the variable _id thinking that it is a <em>private</em> one. I personally don’t like this, hope they remove this “feature”, I like to think that we are Man and we know what we’re doing… Ok maybe sometimes don’t. So that&#39;s why we’ve renamed that field from _id to id_.</p><p>But how do we get the request body with all the fields?</p><p>By default or <strong>implicitly</strong> the first argument for the function add_pet in this case pet of type PetBase is filled by the .post(…) decorator with the request body</p><pre>...</pre><pre>@pets_router.post(...)<br>async def add_pet(<strong>pet: PetBase</strong>):<br>...</pre><p>So this way pet would be <strong>serialized</strong> or converted from the request body to a PetBase instance (FastAPI do this for us) that we can use inside our function like any other normal function parameter.</p><p>Notice that our function add_pet is fully <strong>asynchronous</strong>, its using keywords async and await to perform DB operations that take some time to compute e.g. pet_op = await DB.pet.insert_one(pet.dict()) inserting a <strong>document</strong> or new register to our pet <strong>collection</strong> or table on our configured DB from config.yml file remember?</p><p>Check function at <strong>line #25</strong> can you guess what it does?</p><pre>async def _get_pet_or_404(id_: str):<br>    _id = validate_object_id(id_)<br>    pet = await DB.pet.find_one({&quot;_id&quot;: _id})<br>    if pet:<br>        return pet<br>    else:<br>        raise <strong>HTTPException</strong>(status_code=404, detail=&quot;Pet not found&quot;)</pre><p>Correct! its getting one single <strong>document</strong> or register at the DB and returning it but in case it does not find one it raises and Exception in this case a HTTPExeption with status code 404 and a detailed message of Pet not found a cool thing of FastAPI is that raising and HTTPExeption will generate a response back to the client with the parameters that we just mentioned.</p><blockquote>Don’t miss this representation with <a href="https://httpstatusdogs.com/">Dogs</a> or <a href="https://http.cat/">Cats</a> about HTTP status codes, I’ve always enjoy them when I need to search for a code that I don’t remember by hard, hope you do too.</blockquote><h4>Get a specific pet by id</h4><pre>@pets_router.get(<br>    &quot;<strong>/{id_}</strong>&quot;,<br>    response_model=PetOnDB<br>)<br>async def get_pet_by_id(<strong>id_</strong>: ObjectId = <strong>Depends(validate_object_id)</strong>):<br>    &quot;&quot;&quot;[summary]<br>    Get one pet by ID.</pre><pre>[description]<br>    Endpoint to retrieve an specific pet.<br>    &quot;&quot;&quot;<br>    pet = await DB.pet.find_one({&quot;_id&quot;: id_})<br>    if pet:<br>        pet[&quot;id_&quot;] = str(pet[&quot;_id&quot;])<br>        return pet<br>    else:<br>        raise HTTPException(status_code=404, detail=&quot;Pet not found&quot;)</pre><p>Here we’re using a .get(...) decorator to declare the endpoint /pets/{id_} where {id_} is an actually MongoDB ObjectId but wait we can’t send a parameter of that type right?. Yes, we can’t… Instead, we send it as a string path parameter e.g. /pets/5dd2094738761546e66230ae and we declare at our .get(...) decorator that we expect a path parameter, we do so with the {} operator, similar to python<em> f-strings</em> use the {} for string interpolation or substitution.</p><p>Also, we need to make sure it has the same parameter <strong>name</strong> in our function, in this case get_pet_by_id(<strong>_id</strong>: ObjectId) but we go a little bit further marking its default value as the result of a dependency:</p><pre>... get_pet_by_id(id_: ObjectId = <strong>Depends(validate_object_id)</strong>):</pre><p>So with Depends(...) we make sure to run validate_object_id function as a dependency of this _id field, the result or return value of validate_object_id gets assigned to _id parameter, in this case of type ObjectId you just have to make sure that validate_object_id function receive _id parameter too since it&#39;s forwarded to it by Depends(...) clever right? I love it.</p><p>So now you know how to accept path parameters and how to validate those.</p><h4>Delete a pet</h4><pre>@pets_router.delete(<br>    &quot;/{id_}&quot;,<br>    dependencies=[Depends(_get_pet_or_404)]<br>)<br>async def delete_pet_by_id(id_: str):<br>    &quot;&quot;&quot;[summary]<br>    Get one pet by ID.</pre><pre>[description]<br>    Endpoint to retrieve an specific pet.<br>    &quot;&quot;&quot;<br>    pet_op = await DB.pet.delete_one({&quot;_id&quot;: ObjectId(id_)})<br>    if pet_op.deleted_count:<br>        return {&quot;status&quot;: f&quot;deleted count: {pet_op.deleted_count}&quot;}</pre><p>Here we use the same endpoint /pets/{id_} but with a different HTTP method DELETE, so we used the .delete() decorator from our pet_router but now I want to show you to use the dependencies keyword argument, it basically accepts a list of Depends(…) e.g.</p><pre>dependencies=[Depends(_get_pet_or_404)]</pre><p>It works similarly that the previous example but with the difference that the return value of _get_pet_or_404 does not get assigned, so its perfect for validations e.g. token, user permission. We are using it to validate that the {_id} actually exists as a document on our DB but if it does not it rises an HTTPException. Check the code of _get_pet_or_404 for more details on how the validation is performed.</p><p>Once we validate that a pet actually exists on our DB we can safely delete it. pet_op = await DB.pet.delete_one({“_id”: ObjectId(id_)})</p><h4>Update a pet</h4><pre>@pets_router.put(<br>    &quot;/{id_}&quot;,<br>    <strong>dependencies=[Depends(validate_object_id), Depends(_get_pet_or_404)]</strong>,<br>    response_model=PetOnDB<br>)<br>async def update_pet(id_: str, pet_data: PetBase):<br>    &quot;&quot;&quot;[summary]<br>    Update a pet by ID.</pre><pre>[description]<br>    Endpoint to update an specific pet with some or all fields.<br>    &quot;&quot;&quot;<br>    pet_op = await DB.pet.update_one(<br>        {&quot;_id&quot;: ObjectId(id_)}, {&quot;$set&quot;: pet_data.dict()}<br>    )<br>    if pet_op.modified_count:<br>        return await _get_pet_or_404(id_)<br>    else:<br>        raise HTTPException(status_code=304)</pre><p>In this example, we can see the dependencies keyword argument used with more than one Depends(…):</p><pre>dependencies=[Depends(validate_object_id), Depends(_get_pet_or_404)]</pre><p>validate_object_id functions get executed before _get_pet_or_404 and only gets executed if validate_object_id finished without Exceptions.</p><p>So at this point, we knew that the ObjectId path parameter given is valid e.g. /pets/5dd2094738761546e66230ae v.s. an invalid /pets/5dd2094 and this ObjectId exists on DB. Reusing our validation functions for all our endpoints, how cool is that.</p><p>Let&#39;s test these validations, with your containers running, open your browser and point it to <a href="http://localhost:8000/pets/5dd4502b48015eb0a2db7c1a">http://localhost:8000/pets/5dd4</a> which is obviously an invalid ObjectId then <a href="http://localhost:8000/pets/5dd4502b48015eb0a2db7c1a">http://localhost:8000/pets/5dd4502b48015eb0a2db7c1a</a> which is a valid ObjectId but it does not exist on DB.</p><p>What was the result? Can you spot the code flow that was actually used? Nice!</p><h4>Get all pets</h4><pre><a href="http://twitter.com/pets_router">@pets_router</a>.get(&quot;/&quot;, response_model=List[PetOnDB])<br>async def get_all_pets(<strong>kind: PetKind = None, limit: int = 10, skip: int = 0</strong>):<br>    &quot;&quot;&quot;[summary]<br>    Gets all pets.</pre><pre>[description]<br>    Endpoint to retrieve pets.<br>    &quot;&quot;&quot;<br>    if <strong>kind is None</strong>:<br>        pets_cursor = DB.pet.<strong>find()</strong>.skip(skip).limit(limit)<br>    else:<br>        pets_cursor = DB.pet.find({&quot;kind&quot;: kind.value}).skip(skip).limit(limit)<br>    pets = await pets_cursor.to_list(length=limit)<br>    return list(map(fix_pet_id, pets))</pre><p>For GET request when we define function parameters e.g. kind, limit, skip in our function get_all_pets(...)</p><pre>...<br>async def get_all_pets(<strong>kind</strong>: PetKind = None, <strong>limit</strong>: int = 10, <strong>skip</strong>: int = 0):<br>...</pre><p>Those become query parameters for our request by default or implicitly so here we’re defining only optional ones since all have a default value e.g. kind: PetKind = <strong>None</strong>, limit: int = <strong>10</strong>, skip: int = <strong>0</strong>, What if we want them to be <strong>required </strong>you just have to remove the default value e.g.</p><pre>...<br>async def get_all_pets(<strong>kind</strong>: PetKind, <strong>limit</strong>: int, skip: int = 0):<br>...</pre><p>This way kind and limit are now required, skip stills optional with 0 as default value.</p><p>Now we use the limit parameter to limit the number of returned pets and skip to skip results, can you see how we can use skip to paginate? Nice!</p><pre>pets_cursor = DB.pet.find().skip(skip).limit(limit)</pre><p>To test this endpoint use curl to get all <em>dog</em> pets with <a href="http://localhost:8000/pets/?kind=Dog&amp;limit=1&amp;skip=1">?kind=Dog</a> query parameter:</p><pre>$ curl -X GET &quot;<a href="http://localhost:8000/pets/?kind=Dog&amp;limit=1&amp;skip=1">http://localhost:8000/pets/?kind=Dog</a>&quot;</pre><p>or this one to get all Dog or Cat</p><pre>$ curl -X GET &quot;<a href="http://localhost:8000/pets/?kind=Dog&amp;limit=1&amp;skip=1">http://localhost:8000/pets/</a>&quot;</pre><h3>Testing endpoints</h3><p>Lets tests adding a pet, for this we could use an HTTP client like curl or postman, but our app is so cool that has auto-generated a web HTTP rest-client so point your browser to <a href="http://localhost:8000/redoc">http://localhost:8000/redoc</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*N2TOzZcsyMgPxdWezj_YJQ.png" /><figcaption>redoc UI</figcaption></figure><p>ReDoc is pretty much information on how to use the endpoint that we just declare and the outcomes that you can expect from them e.g. success with status code 200, errors with status code 422.</p><p>OpenAPI <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*ZboSoRIGbjwjXSNAJE8qXQ.png" /><figcaption>OpenAPI UI formerly Swagger UI</figcaption></figure><blockquote>By default, the OpenAPI <strong>schema</strong> auto-generated is served at /openapi.json. If your curious about things that you can do with your <strong>schema</strong> here is a <a href="https://openapi.tools/">cool site</a> about a lot of tools to help you going with OpenAPI.</blockquote><p>OpenAPI UI (formerly Swagger IU) is the actual client that we’re going to use to test our endpoints, let&#39;s start with the POST one, so click on the green one to expand it, then click on button <strong>Try it out </strong>to enable the <strong>Request body </strong>lucky for us using the Python Typing system is able to infer the correct value types for our fields and present those to us in the <strong>Request body</strong>, so modify that request body or just copy/paste this one:</p><pre>{<br>    &quot;kind&quot;: &quot;Dog&quot;,<br>    &quot;states&quot;: [<br>        &quot;Bad&quot;,<br>        &quot;Underfed&quot;,<br>        &quot;Injured&quot;<br>    ],<br>    &quot;location&quot;: &quot;fake st. 123, Springfield, California&quot;,<br>    &quot;name&quot;: &quot;Guero&quot;<br>}</pre><p>Then click big blue button <strong>Execute</strong> so you should get a response similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*MvGGOWU8iRU-Rgd3doJ3AA.png" /></figure><p>With status code 200 and response body the pet object with all the fields defined in our PetOnDB model.</p><p>But if we miss a required field</p><pre>{<br>    &quot;states&quot;: [<br>        &quot;Bad&quot;,<br>        &quot;Underfed&quot;,<br>        &quot;Injured&quot;<br>    ],<br>    &quot;location&quot;: &quot;fake st. 123, Springfield, California&quot;,<br>    &quot;name&quot;: &quot;Guero&quot;<br>}</pre><p>we get something similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*6RWOE3QnE19YIuRp1m0hcg.png" /></figure><p>indicating that at the location →body → pet → <strong>kind</strong> with msg “Field required” and extra info type “value_error.missing” pretty much indicating that is missing.</p><p>Play around with this tool and more importantly have fun! try to break it sending odd parameters, let know what happens.</p><p>Get this part of the project:</p><pre>git clone -b part2 <a href="https://github.com/rescaty/mvp.git">https://github.com/rescaty/mvp.git</a></pre><p>Then just copy and edit the configuration file.</p><pre>cd mvp/backend/tancho/config<br>cp config.sample.yml config.yml<br>cd ../../<br>$ docker-compose down &amp;&amp; docker-compose up</pre><p>If you like this article please give it a clap, share it with your friends, <a href="https://twitter.com/brunuxcom">follow me on twitter</a> for more articles, you can twit me if you have any questions.</p><p>In the <a href="https://medium.com/@bruno.fosados/learn-docker-fastapi-ci-cd-and-vue-js-third-part-ci-cd-86025056490a?source=friends_link&amp;sk=6f4296f81f0cc31ff4e86a32cbb3c6e1">Third Part</a>, we’re going to create a <strong>pipeline</strong> for <strong>CI</strong> (Continues Integration) with <strong>Github Actions </strong>adding some test with <strong>pytest</strong> module and <strong>CD</strong> (Continues Delivery) to <strong>AWS</strong> fully managed container service <strong>Fargate</strong> which is part of <strong>ECS </strong>(Elastic Container Service), so we don’t have to worry about machine instance, load balancing, managing containers and so on, our app would become <strong>Cloud Native.</strong></p><p>Have a good one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec2e1e093a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Learn: Docker, FastAPI and Vue.js — First Part (Docker & Setup).]]></title>
            <link>https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-first-part-docker-setup-a8e4c09ef9c4?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e4c09ef9c4</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[uvicorn]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Fri, 15 Nov 2019 21:17:53 GMT</pubDate>
            <atom:updated>2019-11-26T20:47:09.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2LKMUUBvJTUf3VVMPeWXg.jpeg" /></figure><h3>Learn: Docker, FastAPI, CI/CD, and Vue.js — First Part (Docker &amp; Setup).</h3><p>Hello there, this is going to be the first of a series of articles about learning by building a “<strong>Pet rescue &amp; adoption</strong>” app with <strong>Docker</strong>, <strong>FastAPI, </strong>and <strong>Vue.js</strong>.</p><p>We are going to start setting up the base project with <strong>Docker</strong> and <strong>docker-compose</strong> for this article, for the second we’re going to build the <em>backend</em> using <strong>FastAPI </strong>and Python obviously, and finally, we’re going to focus on the <em>frontend</em> using <strong>Vue.js</strong> and <strong>Bulma</strong> CSS framework, so let’s get started with <strong>Docker</strong>.</p><p>So what is <strong>Docker</strong> anyway? It’s a tool for application abstraction basically, it allows you to increases some aspects of your development and deployment process, as does for your app per se and its life cycle.</p><p>For now think of it as a bag or <strong>container</strong> in which you can put all the artifacts, files, binaries and so on that your app needs in order to work.</p><p>What about <strong>docker-compose</strong>? simply, is a tool for defining and running multi-container Docker applications.</p><h3>Pre-requisites</h3><p>You’ll need to have installed <a href="https://docs.docker.com/install/">Docker</a> check these detailed guides on how to install it on <a href="https://docs.docker.com/docker-for-mac/install/">macOS</a> and <a href="https://docs.docker.com/docker-for-windows/install/">Windows</a>.</p><p>By now <a href="https://docs.docker.com/compose/">docker-compose</a> should be already installed since its bundle to docker installation except for Linux users which have to check this <a href="https://docs.docker.com/compose/install/">guide</a> on how to install it.</p><h3>Hands-On — File structure</h3><p>Let&#39;s create a folder to store our project, call this folder mvp inside this folder create another folder called tancho for the actual <em>backend</em> app and at the same level a file called requirements.txt so your file structure should look like this.</p><pre>$ cd mvp<br>$ tree</pre><pre>|____backend<br>| |____tancho<br>| |____requirements.txt</pre><p>requirements.txt is going to maintain the <em>backend</em> libraries that our project needs, open requirements.txt and add:</p><pre># requirements.txt</pre><pre>fastapi[all]==0.42.0</pre><p>We’re adding FastAPI with all the recommended dependencies.</p><h3>Docker</h3><p>The most basic way to get docker to work in a <strong>maintainable</strong> way is by defining a so-called Dockerfile in which we’re defining instructions to be interpreted by the docker engine.</p><p>Now at the same level of requirements.txt create another file called Dockerfile .</p><p>Open the Dockerfile and add the following:</p><pre>FROM python:3.8<br>ENV PYTHONUNBUFFERED 1</pre><pre>ADD /tancho /tancho/<br>ADD requirements.txt /tancho/<br>WORKDIR /tancho</pre><pre>RUN pip install -r requirements.txt</pre><p>With this instruction, we’re telling docker to use the base docker image called python:3 and inside our new container add our tancho folder to the root file structure of the container and finally install the libraries dependencies to the container with pip install -r requirements.txt</p><p>So now your file structure should look like this:</p><pre>$ tree</pre><pre>.<br>|____backend<br>| |____tancho<br>| |____requirements.txt<br>| |____Dockerfile</pre><h3>docker-compose</h3><p>At the same level of the Dockerfile create a file called docker-compose.yml and add the following:</p><pre>version: &#39;3&#39;</pre><pre>services:<br>  tancho:<br>    build: .<br>    command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload<br>    volumes:<br>      - ./tancho:/tancho<br>    ports:<br>      - &quot;8000:8000&quot;</pre><p>So now your file structure should look like this:</p><pre>.<br>|____backend<br>| |____tancho<br>| |____requirements.txt<br>| |____Dockerfile<br>| |____docker-compose.yml</pre><p>Here we’re defining or telling Docker through docker-compose how our new container should be configured and how should be initialized to serve or app. This is the most important line command: uvicorn main:app — host 0 — port 8000 — reload so lets break it a little bit.</p><p>First, what is <a href="https://www.uvicorn.org/">uvicorn</a>? is a lightning-fast ASGI server, built on <a href="https://github.com/MagicStack/uvloop">uvloop</a> and <a href="https://github.com/MagicStack/httptools">httptools</a>.</p><p>Wait so what’s an ASGI? <em>Asynchronous Server Gateway Interface </em>man that was long… Think of it as a middle man between a client’s request (web app or mobile app request) and our actual python <em>backend</em> code (app) which supports both synchronous and asynchronous requests, more on sync and async later on.</p><p>When we defined in requirements.txt our fastapi[all]==0.42.0 library to be installed, uvicorn was added as a sub-dependency of fastapi due to the [all] option has been added, so no worries on install it is already there.</p><p>uvicorn needs some parameters to run our app, main:app this makes reference to a file that we need to create and we are going to call main.py inside this file, a reference called app needs to be created to be an actual FastAPI app instance, --host 0.0.0.0 --port 8000 --reload parameters explicitly say that our app should listen for all local IP address (--host 0.0.0.0) on port 8000 and should watch for file changes in order to --reload itself.</p><h3>FastAPI</h3><p>Let&#39;s create our main.py file in order to test all our setup, this is going to be our main entry point for our <em>backend</em> app. At tancho folder create the main.py file</p><pre>$ tree</pre><pre>.<br>|____backend<br>| |____tancho<br>| | |____main.py<br>| |____requirements.txt<br>| |____Dockerfile<br>| |____docker-compose.yml</pre><p>And add the following:</p><pre>from fastapi import FastAPI</pre><pre>app = FastAPI()</pre><pre><a href="http://twitter.com/app">@app</a>.get(&quot;/pets/&quot;)<br>async def get_all_pets():<br>    &quot;&quot;&quot;[summary]<br>    Gets all pets adopted/rescued or not.</pre><pre>    [description]<br>    Endpoint for all pets.<br>    &quot;&quot;&quot;<br>    fake_pets = [{&quot;name&quot;: &quot;Guero&quot;}, {&quot;name&quot;: &quot;Pepita&quot;}]<br>    return fake_pets</pre><p>Save this file, let&#39;s break main.py file a little bit</p><pre>from fastapi import FastAPI</pre><p>Here we are importing our FastAPI factory class. With FastAPI we create an instance for our app which is used by uvicorn remember? at our docker-compose.yml command: instruction? great, so we’re instantiated it here with:</p><pre>app = FastAPI()</pre><p><em>Fun fact</em> FastAPI uses a factory pattern for creating apps instances and if you were wondering about tancho folder name is the name of one of my dogs.</p><pre><a href="http://twitter.com/app">@app</a>.get(&quot;/pets/&quot;)</pre><p>Our FastAPI instance app uses a decorator pattern for defining API endpoints, here we are defining a /pets/ endpoint on our root URI using a get method decorator, pretty simple right?</p><pre>async def get_all_pets():<br>    &quot;&quot;&quot;[summary]<br>    Gets all pets adopted/rescued or not.</pre><pre>    [description]<br>    Endpoint for all pets.<br>    &quot;&quot;&quot;<br>    fake_pets = [{&quot;name&quot;: &quot;Guero&quot;}, {&quot;name&quot;: &quot;Pepita&quot;}]<br>    return fake_pets</pre><p>Now for our endpoint we need to define what is going to do or operate, for that we’ve defined an asynchronous function get_all_pets() with keyword async please note that in this example our function is not actually full <em>asynchronous</em> since its not doing any operation that takes some time to compute in fact we are just returning a fake_pets list just for testing purposes. If we ware doing tasks that actually take some time we needed to use a keyword await but we get on that later on.</p><p>For now, think of FastAPI app that it can actually differentiate and handle <em>async/sync</em> functions for us.</p><p>So we could have used a normal function (synchronous one) instead of an async one, and FastAPI would handle that just fine.</p><p>Let&#39;s run a quick test, go back to the root of our project that would be mvp/ you should be a the level of our Dockerfile and docker-compose.yml and run:</p><pre>$ docker-compose up</pre><p>You should see an output similar to this:</p><pre>Creating network &quot;backend_default&quot; with the default driver<br>Building tancho<br>Step 1/6 : FROM python:3.8<br>3.8: Pulling from library/python<br>c7b7d16361e0: Downloading [===================&gt;                               ]  19.85MB/50.38MB<br>b7a128769df1: Download complete<br>1128949d0793: Download complete<br>667692510b70: Downloading [===&gt;                                               ]  3.669MB/51.77MB<br>bed4ecf88e6a: Downloading [&gt;                                                  ]  2.686MB/192.1MB<br>8a8c75f3996a: Waiting<br>59ba7226fec9: Waiting<br>8f449aa0129e: Waiting<br>6e376b1610c0: Waiting</pre><p>This is the docker engine reading our Dockerfile through docker-compose line by line or step by step Step 1/6 : FROM python:3.8 then you should have an output similar to this:</p><pre>Status: Downloaded newer image for python:3.8<br> ---&gt; a2aeea3dfc32<br>Step 2/6 : ENV PYTHONUNBUFFERED 1<br> ---&gt; Running in af63b5bf4807<br>Removing intermediate container af63b5bf4807<br> ---&gt; acbf8c10ae70<br>Step 3/6 : ADD /tancho /tancho/<br> ---&gt; b6d603a23945<br>Step 4/6 : ADD requirements.txt /tancho/<br> ---&gt; ad70a2417a82<br>Step 5/6 : WORKDIR /tancho<br> ---&gt; Running in b1522496f803<br>Removing intermediate container b1522496f803<br> ---&gt; c4b4964b5501<br>Step 6/6 : RUN pip install -r requirements.txt<br> ---&gt; Running in 2b29671d7071<br>Collecting fastapi[all]==0.42.0<br>  Downloading <a href="https://files.pythonhosted.org/packages/4a/28/97c3b661e7bebe8508a58343c4242603d75773c18199d719c2cfd8b8428b/fastapi-0.42.0-py3-none-any.whl">https://files.pythonhosted.org/packages/4a/28/97c3b661e7bebe8508a58343c4242603d75773c18199d719c2cfd8b8428b/fastapi-0.42.0-py3-none-any.whl</a> (166kB)<br>Collecting starlette&lt;=0.12.9,&gt;=0.12.9<br>  Downloading <a href="https://files.pythonhosted.org/packages/67/95/2220fe5bf287e693a6430d8ee36c681b0157035b7249ec08f8fb36319d16/starlette-0.12.9.tar.gz">https://files.pythonhosted.org/packages/67/95/2220fe5bf287e693a6430d8ee36c681b0157035b7249ec08f8fb36319d16/starlette-0.12.9.tar.gz</a> (46kB)<br>Collecting pydantic&lt;=0.32.2,&gt;=0.32.2<br>  Downloading <a href="https://files.pythonhosted.org/packages/02/cf/80e08943ac1af41e373f478418a76cac232d3b36ea827c2f89dbbef9a698/pydantic-0.32.2-py36.py37.py38-none-any.whl">https://files.pythonhosted.org/packages/02/cf/80e08943ac1af41e373f478418a76cac232d3b36ea827c2f89dbbef9a698/pydantic-0.32.2-py36.py37.py38-none-any.whl</a> (63kB)<br>Collecting graphene; extra == &quot;all&quot;<br>  Downloading <a href="https://files.pythonhosted.org/packages/05/97/45e743b372f65a619f8d1eb2897efb74fb1b0ffddc731ad37e0aa187ec5c/graphene-2.1.8-py2.py3-none-any.whl">https://files.pythonhosted.org/packages/05/97/45e743b372f65a619f8d1eb2897efb74fb1b0ffddc731ad37e0aa187ec5c/graphene-2.1.8-py2.py3-none-any.whl</a> (107kB)<br>...</pre><p>The first time that we run our container, itself needs to build that’s why we see all those steps running, next time we run docker-compose up it won’t be building since we already have done this if you want to manually rebuild for some reason run the command docker-compose build at the docker-compose.yml and Dockerfile file level.</p><pre>Successfully built 6f01b9c13530<br>Successfully tagged backend_tancho:latest<br>WARNING: Image for service tancho was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.<br>Creating backend_tancho_1 ... done<br>Attaching to backend_tancho_1<br>tancho_1  | INFO:     Uvicorn running on <a href="http://0.0.0.0:8000/">http://0.0.0.0:8000</a> (Press CTRL+C to quit)<br>tancho_1  | INFO:     Started reloader process [1]<br>tancho_1  | INFO:     Started server process [9]<br>tancho_1  | INFO:     Waiting for application startup.<br>tancho_1  | INFO:     Application startup complete.</pre><p>After successfully built docker-compose runs our command: uvicorn main:app --host 0.0.0.0 --port 8000 --reload and as we can see it started successfully tancho_1 | INFO: Application startup complete.</p><p>Now we can actually test our setup by querying the endpoint /pets/ I’m using curl if you want you can use your favorite web browser just point it to <a href="http://localhost:8000/pets/">http://localhost:8000/pets/</a></p><pre>$ curl -v <a href="http://localhost:8000/pets/">http://localhost:8000/pets/</a><br>*   Trying ::1...<br>* TCP_NODELAY set<br>* Connected to localhost (::1) port 8000 (#0)<br>&gt; GET /pets/ HTTP/1.1<br>&gt; Host: localhost:8000<br>&gt; User-Agent: curl/7.64.1<br>&gt; Accept: */*<br>&gt;<br>&lt; HTTP/1.1 200 OK<br>&lt; date: Fri, 15 Nov 2019 18:30:35 GMT<br>&lt; server: uvicorn<br>&lt; content-length: 36<br>&lt; content-type: application/json<br>&lt;<br>* Connection #0 to host localhost left intact</pre><pre>[{&quot;name&quot;:&quot;Guero&quot;},{&quot;name&quot;:&quot;Pepita&quot;}]</pre><pre>* Closing connection 0</pre><p>You should have a response similar to:</p><pre>[<br>    {<br>        &quot;name&quot;: &quot;Guero&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Pepita&quot;<br>    }<br>]</pre><p><em>Fun fact</em> Guero and Pepita are the name of my dogs too, I love dogs!!</p><p>There many cool features about FastAPI that we’re going to dig in, one that we can spot right now; its smart enough to actually cast our fake_pets return from a Python List of Dictionaries to an Array of JSON Objects, saving precious time and typing for us.</p><p>So here you have it, the base for our app has been done, you can get the full code here:</p><pre>git clone -b part1 https://github.com/rescaty/mvp.git</pre><p>Then just run the project</p><pre>$ cd mvp/backend/<br>$ docker-compose up</pre><p>If you like this article please give it a clap share it with your friends, <a href="https://twitter.com/brunuxcom">follow me on twitter</a> for more articles.</p><p>You can now jump to the <a href="https://medium.com/@bruno.fosados/simple-learn-docker-fastapi-and-vue-js-second-part-backend-fastapi-cec2e1e093a9?source=friends_link&amp;sk=ae1b0a3bbe1a1355970f1987a36dcc80">second part</a> of this series which focused on <strong>FastAPI</strong>, we’ve added a new sub-app pet and we’ve written some <strong>models</strong> and <strong>views</strong> (routes) with <strong>CRUD</strong> asynchronous operations on <strong>MongoDB</strong>.</p><p>Have a good one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e4c09ef9c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple words: K nearest neighbors algorithm — Machine Learning]]></title>
            <link>https://medium.com/@bruno.fosados/simple-words-k-nearest-neighbors-algorithm-machine-learning-24c69a87b159?source=rss-c2e961655545------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c69a87b159</guid>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bruno Fosados]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 09:21:35 GMT</pubDate>
            <atom:updated>2019-11-06T00:42:52.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple words: K nearest neighbors algorithm — Machine Learning</h3><p>How can you teach a computer to clap? Mmm… not that easy, right? So we’re going to learn about <strong>K nearest neighbors</strong> algorithm and how it <strong>works</strong> for machine learning applications.</p><p>People tend to clap, when? Something is really cool for some reason or perhaps they have some personal preference about the subject or simply because they fell so, in this article we’re going to tech our computer to clap to good jokes, so let’s get started.</p><p>First… How can we <strong>define</strong> a good joke? Well, a good joke must have some characteristics or <strong>features</strong>, e.g. it could talk about animals vs real life or maybe a knock knock which tend to be kind of ridiculous, it could be long or short or perhaps it cold be told by <strong>Kevin Hart</strong> or <strong>Ellen DeGeneres</strong> which both have different skills for told a joke and so on…</p><p>So from this we would say that there are factors or <strong>features</strong> related to the joke that makes a joke <strong>good</strong> or <strong>bad</strong> so for this features we’re going to give an scale from 0 to 1, e.g. 0.45, 0.98 and we’re going to define the actual <strong>list of features.</strong></p><p>We’re going to use two <strong>features</strong> “Duration” (if the duration was good enough) and “told skill” (how well was told) with values of 0.55 and 0.61 respectively, in a real life example there could be as many features as needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97cabeaef31085434eb95513cc3d25b8/href">https://medium.com/media/97cabeaef31085434eb95513cc3d25b8/href</a></iframe><p>In the previews code we’ve defined our joke, the features, and assigned some values, in real life this values needs to be actually measured to reflect reality by some method. Think of this example that we’ve asked some body to give a rate for both features between 0 and 1 and that was the result.</p><p>Now, we’ve asked some people about 25 different jokes and we got some <strong>data</strong>, with this <strong>data</strong> we’re going to <strong>tech</strong> or computer so it can differentiate from a good joke or a bad one, based on they’re <strong>features</strong>, using the<strong> K nearest neighbors algorithm</strong> this process is called <strong>training.</strong></p><p>So what is all the fuzz about the <strong>KNN</strong> (K nearest neighbors) algo anyway? In common words it says that points than tend to be together tend to be similar. Here is a Wikipedia page about the <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">KNN</a> for you in case you want to get more technical about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcnlWd_JbbAiO5J0WYdaqw.png" /><figcaption>By Antti Ajanki AnAj — Own work, CC BY-SA 3.0, <a href="https://commons.wikimedia.org/w/index.php?curid=2170282">https://commons.wikimedia.org/w/index.php?curid=2170282</a></figcaption></figure><p>In this picture, our joke, the one about the marshmallow remember? Would represented by the green circle in which case we don’t known yet how is going to be <strong>labeled </strong>or <strong>classified </strong>by our computer; good or bad joke.</p><p>All other figures; squares and triangles represents other jokes that we for sure know they’re good or bad jokes, those represent the 25 jokes data that we collect earlier, <strong>blue</strong> squares are <strong>good</strong> jokes and <strong>red</strong> triangle are <strong>bad</strong> jokes.</p><p>Also we can see two <strong>delimiters</strong>: one continues black line that creates a circle around some figures and a dashed bigger one. The K nearest neighbors uses factor call ‘K’, you can play with ‘<strong>K</strong>’ factor, making it <strong>bigger</strong> or <strong>smaller</strong> for the computer to classify our marshmallow joke. The K factor is represented by this delimiters.</p><p>If we use the dashed black line as K factor (k=5, total items without our green one) our green point is going to be classified as <strong>blue</strong> due to 3BlueSqueres &gt; 2RedTriangle since we have more blue squares than red triangles, but if we use the small delimiter (k=3) the outcome is going to be <strong>red</strong> due to 2RedTriangle &gt; 1BlueSqueres.</p><p>Wait, what about if we have the same number of figures: 2RedTriangle == 2BlueSqueres, If this is the case then the closest one to the green circle(test sample) is chosen that would be the red triangle.</p><p>So how do we set the ‘K’ factor? The answer is <strong>testing</strong>, did you remember our 25 jokes data that we collected earlier? We’re going to split this data. One part for the <strong>training</strong> process and one part for <strong>testing</strong> purposes, we can split the data in different portions but a good start is <strong>80–20</strong>, 80% of the data for training our computer and 20% for testing our ‘K’ factor in order to find the more accurate one.</p><p>At this point you should be able to understand the basics of the <strong>KNN</strong> and how it works, we are going to get a little bit more technical, we’re going to actually make your computer clap for good jokes!</p><p>We are going to use: <a href="https://www.python.org/downloads/">Python3</a>, <a href="https://scikit-learn.org/stable/install.html">SKLearn</a> and <a href="https://matplotlib.org/users/installing.html">MathPlotLib</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e4faf179c9cadf6e9d1b52bda3f58c1/href">https://medium.com/media/5e4faf179c9cadf6e9d1b52bda3f58c1/href</a></iframe><p>Try to set different values for `green_joke` variable, are they good jokes or bad ones?</p><p>Congrats! now you your computer can actually know if your jokes are good or bad, don’t get sad if they’re bad ones, you’ll get it!.</p><p>Now if you want to find the best ‘K’ factor you need to train you model with different ‘K’s check the for loop in where we are iterating with different ‘K’s values and measure its accuracy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38531bafca5b0f50fa7becb6dab363ae/href">https://medium.com/media/38531bafca5b0f50fa7becb6dab363ae/href</a></iframe><p>In conclusion, the better accurate data you have for your <strong>features </strong>the best predictions your are going to have.</p><p>If you like this please give it a clap, follow me for more interesting articles in ‘simple words’.</p><p>Have a good one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c69a87b159" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>