<?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 Fernando Freitas Alves on Medium]]></title>
        <description><![CDATA[Stories by Fernando Freitas Alves on Medium]]></description>
        <link>https://medium.com/@ffreitasalves?source=rss-2ac49f6afab0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*RxNvragbmH2cr_P-PIjGUg.jpeg</url>
            <title>Stories by Fernando Freitas Alves on Medium</title>
            <link>https://medium.com/@ffreitasalves?source=rss-2ac49f6afab0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:46:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ffreitasalves/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[Hackeando o Organograma. Influenciando ativamente quem está acima de você]]></title>
            <link>https://medium.com/@ffreitasalves/hackeando-o-organograma-influenciando-ativamente-quem-est%C3%A1-acima-de-voc%C3%AA-6d1edc3592d2?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d1edc3592d2</guid>
            <category><![CDATA[comunicação]]></category>
            <category><![CDATA[desenvolvimento-pessoal]]></category>
            <category><![CDATA[humildade]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Sat, 17 Aug 2019 14:15:10 GMT</pubDate>
            <atom:updated>2019-08-17T14:15:10.548Z</atom:updated>
            <content:encoded><![CDATA[<p>Essa semana li um texto interessantíssimo do meu amigo Muller Nascimento: <a href="http://mullernascimento.com/textos/as-vezes-e-a-maca-e-as-vezes-e-o-barril/">Às vezes é a maçã e às vezes é o barril</a>. O texto discute o que fazer quando o problema é quem toma as decisões. Isso não é simples e entendo que para a maioria das pessoas essa situação pareça insolúvel, mas não é. Hackeando o organograma, você pode liderar sua empresa, independentemente da posição que ocupa.</p><p>Minha sugestão aqui é que você assuma uma postura de liderança, sem se prender ao seu papel na empresa. Para isso, você vai precisar trabalhar em vários pontos ativamente. A maioria das pessoas vai fugir, ou achar que não vale o esforço, mas se você for uma das poucas pessoas a lutar terá aprendido muito no processo e poderá ser responsável por melhorar não só seu ambiente de trabalho, como a si mesmo e sairá dessa batalha um profissional muito mais capacitado e pronto para assumir posições mais difíceis.</p><h4>Comunicação</h4><p>Jeff Sutherland no seu livro <a href="https://www.amazon.com.br/SCRUM-fazer-dobro-trabalho-metade/dp/8543107164?tag=goog0ef-20&amp;smid=A1ZZFT5FULY4LN&amp;ascsubtag=go_1494986073_58431735035_285514469186_aud-519888259198:pla-531170537199_c_">Scrum</a>, fala sobre a importância da saturação da comunicação para o funcionamento efetivo do time. É uma verdade dentro de um time de 5 ou 6 pessoas e continua sendo verdade para organizações inteiras, com centenas de colaboradores (ou maçãs 🍎 🍏, como chamou o Muller). Mas por quê ainda se fala tanto sobre a importância da comunicação ? Porque é sempre o primeiro problema pra resolver.</p><p>Para manter todo mundo na mesma página é que surgem as reuniões de alinhamento, planejamento, reuniões diárias (daily meetings), retrospectivas, etc. O único objetivo é compartilhar o máximo para que todos tenham contexto suficiente para tomar as melhores decisões. A boa comunicação e a saturação dela entre “líderes” e “liderados” é o caminho para uma relação mais harmoniosa e um trabalho mais efetivo.</p><p>Na prática: O que fazer quando seu líder não se comunica de maneira eficiente? Perguntas! Sempre que alguma coisa não estiver clara para você, você vai perguntar. Seu objetivo não é entender “Como fazer alguma coisa” ou “O que deve ser feito”. Seu objetivo primeiramente é entender o Objetivo por trás de qualquer tarefa. Entender o “Por quê” algo precisa ser feito vai te trazer a visão global de algo. Toda vez que não estiver claro, pergunte ativamente. Discuta os pontos que devem ser feitos, qual a melhor forma de fazê-los e quando algo não estiver claro para você como “por quê estamos usando a metodologia x ao invés de y?” ou “por que não tentamos fazer tal coisa”.</p><h4>Fale com quem resolve</h4><p>Falar com quem resolve é outro ponto que deve ser trabalhado se você quiser liderar de baixo para cima. Discuta abertamente os problemas da empresa com o seu chefe e não pelas costas para os seus pares. Falar com alguém que não tem o poder de mudar nada só vai soar como reclamação e vai contaminar o barril inteiro e ainda pode ter um efeito negativo sobre como os outros funcionários enxergam você. Se você levar isso para quem tem o poder de resolver, você estará ativamente buscando soluções.</p><h4>Seja Humilde</h4><p>Contudo, considere se você está sendo humilde. Eu sei o quão irritante pode ser ouvir isso, principalmente se você estiver de saco cheio com a sua empresa, porém ser humilde para considerar se o que está sendo feito tem sentido, ou se você tem o contexto completo para avaliar uma decisão é crucial para ser ouvido também. No livro, <a href="https://www.amazon.com.br/Extreme-Ownership-U-S-SEALs-English-ebook/dp/B0739PYQSS?tag=goog0ef-20&amp;smid=A18CNA8NWQSYHH&amp;ascsubtag=go_1686871380_65779544836_327582895583_aud-580930410671:pla-793030093391_c_">Extreme Ownership</a>, Jocko Willink e Leif Babin explicam como o ego pode atrapalhar seu julgamento e sua tomada de decisões. Se você ouvir atenciosamente, maior será sua chance de entender melhor o cenário e com isso ter uma melhor base de argumentação, se necessário. No final de uma boa discussão os envolvidos vão sair melhores, entendendo mais os pontos um do outro. Mesmo que haja discordância, é mais fácil seguir por um caminho depois de entender quais são os trade-offs de cada alternativa.</p><h4>Compartilhe Conhecimento</h4><p>Uma outra estratégia que pode ser aplicada juntamente a todas as outras é compartilhar conhecimento. As diferentes visões para a tomada de decisão vem de diferentes repertórios. Nutra os demais membros do time com informações que você achou relevante para basear a sua visão. Indique <a href="https://fernandofreitasalves.com/tanto-no-pessoal-quanto-no-profissional-boas-praticas-do-seu-trabalho-na-vida-cotidiana/">textos</a>, livros, <a href="https://fernandofreitasalves.com/4-melhores-podcasts-sobre-tecnologia-e-startups/">podcasts</a>, <a href="https://fernandofreitasalves.com/2o-hangout-empreendedorismo-python-brasil/">vídeos</a>, ted talks, cursos e tudo que puder para seus líderes. As vezes um simples “Fulano, gostaria de discutir um texto com você”, pode ser suficiente para um aprendizado relevante na sua empresa. Ninguém sabe tudo e fomentar essas trocas só enriquece o ambiente e o aprendizado.</p><h4>Vá embora, você não é uma árvore</h4><p>Por fim, se a incompatibilidade de gênios é certa, não leve nada para o pessoal. Crie asas e voe para outro lugar. Foque nas coisas boas que você construiu e nos aprendizados que vai levar desta empresa para outra e vá atrás de algo melhor para você. Permanecer em um lugar que não tem nenhum sinal que vai dar certo pode te desmotivar e isso não prejudica só sua empresa, mas também as pessoas próximas (ninguém suporta reclamões) e principalmente sua imagem profissional, pois alguém desmotivado por um longo período pode ser visto como preguiçoso e/ou incapaz pelos colegas e refletir negativamente em futuras indicações.</p><h4>Resumo</h4><p>Algorítimo para hacker as organizações:</p><p>Comunicação efetiva sempre! Pergunte até esclarecer pontos obscuros. Não assuma nada!Fale com quem pode resolver. Levar problemas para os seus pares não muda sua vida, só faz de você um bebê chorão ou uma matrona fofoqueira.Seja Humilde.Eduque quem estiver ao seu redor! Considere compartilhar com eles textos e livros sobre temas que acredita que eles não estão bem treinados. Essa é uma forma efetiva de feedback para liderar.Não leve nada para o lado pessoal. Muitas vezes temos que lidar com pessoas que não tem a mesma maturidade que temos. Se for o caso, bola pra frente</p><h4>Vamos discutir?</h4><p>Concordando ou não, deixe um comentário, eu realmente quero ouvir outras opiniões sobre esse assunto.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d1edc3592d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy SSR applications using Supervisord]]></title>
            <link>https://medium.com/@ffreitasalves/deploy-ssr-applications-using-supervisord-dc32f1c0cda4?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc32f1c0cda4</guid>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 04:12:13 GMT</pubDate>
            <atom:updated>2019-06-15T16:11:46.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy SSR Applications using Supervisord</h3><p>If you’re building Server-Side Rendering applications with React (<a href="https://nextjs.org/">next.js</a>) or Vue.js (<a href="https://nuxtjs.org/">nuxt.js</a>) you will have to deploy it using some process control tool to keep it running. I have seen that a lot of websites are teaching how to do this with <a href="https://www.npmjs.com/package/pm2">PM2</a>, but I decided to deploy SSR applications using <a href="http://supervisord.org/">Supervisord</a>. It will work in the same way and it’s a very common tool, so chances are you already have Supervisord in your server. Especially you’ve followed the <a href="https://hackernoon.com/deploy-for-kids-django-python-3-74261cae076c">Deploy For Kids</a> tutorial</p><p>The number one reason to have a React or Vue.js SSR app is SEO. Google Bot doesn’t work well with CSR (Client-Side Rendering) and it can’t index your pages in that way. So, having an SSR app running in your server means you have node.js running some program that you’ve built in Javascript. But you can’t just run node in a screen and get out of it, you must have some process control tool to keep it running if the server restarts or if the application crashes for some reason.</p><p>Installing Supervisord:</p><pre>sudo apt-get install supervisor</pre><p>Now, create a new configuration file for your SSR application:</p><pre>sudo vi /etc/supervisor/conf.d/my-ssr-app.conf</pre><p>That’s the content:</p><pre><strong>[program:myappname]</strong><br>directory=/home/username/yourproject/<br>command=npm run start<br>user=username<br>autostart=<strong>true</strong><br>autorestart=<strong>true</strong></pre><p>Now, you have to tell Supervisord about this new process:</p><pre>sudo supervisorctl reread<br>sudo supervisorctl update</pre><p>And if in the future you need to restart just your app, use the name in the conf file:</p><pre>sudo supervisorctl restart myappname</pre><p>That’s it. Now you know how to deploy SSR applications using Supervisord.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*HwXsfU9gaMELSxZK" /></figure><p>Interesting links:</p><p><a href="https://www.reddit.com/r/reactjs/comments/an16mx/how_does_seo_work_with_react/">https://www.reddit.com/r/reactjs/comments/an16mx/how_does_seo_work_with_react/</a></p><p><a href="https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8">https://medium.com/walmartlabs/the-benefits-of-server-side-rendering-over-client-side-rendering-5d07ff2cefe8</a></p><p><a href="https://dev.to/stereobooster/server-side-rendering-or-ssr-what-is-it-for-and-when-to-use-it-2cpg">Server Side Rendering pros and cons. When to use it and when to choose something else</a></p><p><em>Originally published at </em><a href="https://fernandofreitasalves.com/deploy-ssr-applications-using-supervisord/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc32f1c0cda4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando um container Docker para um projeto Django Existente]]></title>
            <link>https://medium.com/python-weekly-brazil/criando-um-container-docker-para-um-projeto-django-existente-a2d142ca22be?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d142ca22be</guid>
            <category><![CDATA[deploy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 00:43:03 GMT</pubDate>
            <atom:updated>2018-02-14T13:24:50.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Neste post, vou mostrar como criar um container Docker para um projeto Django já existente. Como exemplo, resolvi buscar por uma <a href="https://github.com/shakedown-street/django-boards/issues/66">issue aberta</a> no github que estivesse pedindo para ser dockerizada. Criei um PR para a Issue e usei como exemplo aqui.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*2pKkYRP8U2ykRjKE.png" /></figure><p>Por quê você vai querer dockerizar uma aplicação web django que já existe? Bom, existem muitas razões, se você acha que não tem uma, faça pela diversão!</p><p>Eu decidi usar o docker em uma das minhas aplicações porque ela estava ficando muito difícil de instalar. Muitos requisitos do sistema, vários bancos de dados, celery, rabbitmq e por aí vai. Sem dockerizar cada vez que uma nova pessoa entra no time é um inferno pra setar tudo porque levava tempo demais.</p><p>O mundo ideal é que o programador tenha em seu ambiente de desenvolvimento o mais próximo que puder do ambiente de produção. Se você usa SQLite na sua máquina mas Postgres no servidor pode ser que tenha problemas de dados que são simplesmente truncados localmente mas que vão levantar erros na base de produção. Só para ter ideia de um exemplo.</p><p>Se você não sabe o que é o docker, imagine que é um imenso virtualenv que no lugar de ter apenas pacotes python tem o sistema operacional “inteiro”. Isso consegue isolar seu app de tudo que está no seu SO, bancos de dados, workers, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/0*Wbbb5bPIIJPX2Sk_.jpeg" /></figure><h4>Mão na massa</h4><p>Ok, falar é fácil, vamos codar um pouco.</p><p>Primeiro de tudo, <a href="https://docs.docker.com/install/">instale</a> o Docker. Fiz isso no Ubuntu e no Mac sem nenhum problema. Já no Windows Home não consegui fazer funcionar.</p><p>Para dizer ao docker que sua aplicação é um container você precisa criar um arquivo Dockerfile:</p><pre>FROM python:3.6<br>ENV PYTHONUNBUFFERED 1<br><br>RUN mkdir /webapps<br>WORKDIR /webapps<br><br># Installing OS Dependencies<br>RUN apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; apt-get install -y \<br>libsqlite3-dev<br><br>RUN pip install -U pip setuptools<br><br>COPY requirements.txt /webapps/<br>COPY requirements-opt.txt /webapps/<br><br>RUN pip install -r /webapps/requirements.txt<br>RUN pip install -r /webapps/requirements-opt.txt<br><br>ADD . /webapps/<br><br># Django service<br>EXPOSE 8000</pre><p>Vamos lá, linha a linha:</p><h4>Docker Images</h4><pre>FROM python:3.6</pre><p>Aqui estamos usando uma imagem do docker <a href="https://hub.docker.com/">hub</a>. Isto, é um container pré-formatado do docker que permite que você monte sua máquina a partir daquela configuração inicial. Nesse caso, Python 3.6 é um container de um Ubuntu que tem o Python 3.6 instalado nele. Você pode procurar por containers no docker hub.</p><h4>Environment Variables (Variáveis de ambiente)</h4><p>Você pode criar todas as variáveis de ambiente que quiser com o ENV.</p><pre>ENV PYTHONUNBUFFERED 1  # Here we can create all Environment variables for our container</pre><p>Por exemplo, se você usa variáveis de ambiente para guardar sua secret key do Django é só fazer assim:</p><pre>ENV DJANGO_SECRET_KEY abcde0s&amp;&amp;$uyc)hf_3rv@!a95nasd22e-dxt^9k^7!f+$jxkk+$k-</pre><p>E usar no seu settings, desse jeito:</p><pre>import os<br>SECRET_KEY = os.environ[&#39;DJANGO_SECRET_KEY&#39;]</pre><h4>Run Commands</h4><p>Docker Run Commands tem um nome meio óbvio. Você pode rodar um comando “dentro” do seu container. Estou colocando dentro entre aspas porque o docker na verdade cria algo como sub containers para que não precise rodar os mesmos comandos novamente no caso de precisar dar um rebuild do container.</p><pre>RUN mkdir /webapps<br>WORKDIR /webapps<br><br># Installing OS Dependencies<br>RUN apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; apt-get install -y \<br>libsqlite3-dev<br><br>RUN pip install -U pip setuptools<br><br>COPY requirements.txt /webapps/<br>COPY requirements-opt.txt /webapps/<br><br>RUN pip install -r /webapps/requirements.txt<br>RUN pip install -r /webapps/requirements-opt.txt<br><br>ADD . /webapps/</pre><p>Aqui estamos criando o diretório que guardará os arquivos do projeto: <strong>webapps/</strong>.</p><p>Workdir é uma instrução para mostrar ao docker em qual diretório ele vai rodar os comandos a partir dali.</p><p>Depois disso estou instalando as dependências do sistema operacional. Quando estamos usando <em>requirements.txt</em> no projeto, estamos colocando apenas os requisitos do python e não os do SO. Mais um motivo para querer usar o docker para desenvolver. Quanto maior seu projeto, mais requisitos de sistema operacional vão aparecer.</p><h4>COPY e ADD</h4><p>Copy e ADD são basicamente a mesma cosia. Ambos <em>copiam</em> um arquivo do seu computador (o Host) dentro do container (o Guest). No meu exemplo, estou apenas copiando o requirements para dentro do docker, para que eu possa dar <em>pip install</em> nos pacotes.</p><h4>EXPOSE</h4><p>Expose é para mapear uma porta do Guest (o Container) para o Host (seu computador)</p><pre># Django service<br>EXPOSE 8000</pre><p>Ok, e agora? Como podemos adicionar mais containers para rodá-los juntos? E se precisarmos colocar um postgresql para rodar em um container também? Não se preocupe, vamos usar o docker-compose.</p><h4>Docker-Compose</h4><p>O <a href="https://docs.docker.com/compose/">compose</a> é uma ferramenta para rodar múltiplos containers do docker. Só precisa criar um arquivo yml na pasta do seu projeto com o nome docker-compose.yml:</p><pre>version: &#39;3.3&#39;<br><br>services:<br>  # Postgres<br>  db:<br>    image: postgres<br>    environment:<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=postgres<br>      - POSTGRES_DB=postgres<br><br>  web:<br>    build: .<br>    command: [&quot;./run_web.sh&quot;]<br>    volumes:<br>      - .:/webapps<br>    ports:<br>      - &quot;8000:8000&quot;<br>    links:<br>      - db<br>    depends_on:<br>      - db</pre><p>Aqui estou usando uma <a href="https://hub.docker.com/_/postgres/">imagem do Postgres</a> que também peguei no Docker Hub.</p><p>Agora vamos mudar o settings.py para poder usar o Postgres do container como banco de dados.</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,<br>        &#39;NAME&#39;: &#39;postgres&#39;,<br>        &#39;USER&#39;: &#39;postgres&#39;,<br>        &#39;PASSWORD&#39;: &#39;postgres&#39;,<br>        &#39;HOST&#39;: &#39;db&#39;,<br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><p>Quase lá, deixa eu falar um pouco sobre o arquivo docker-compose.yml,</p><h4>VOLUMES</h4><p>Lembra do <a href="https://www.vagrantup.com/">vagrant</a>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*LYgKQb2wKJiaP2dN.png" /></figure><p>Era uma vez o Vagrant. Ele era uma forma de rodar um projeto dentro de uma Máquina Virtual que permitia configurar e mapear portas fácilmente, provisionar requisitos do sistema e compartilhar volumes. Seu computador (o Host) podia compartilhar um volume com a máquina virtual (o Guest, ou convidado). No docker, o volume é exatamente a mesma coisa. Quando você escreve um arquivo em um volume que está compartilhado o arquivo também está sendo escrito dentro do container.</p><pre>volumes:<br>  - .:/webapps</pre><p>Nesse o caso, o diretório em que nos encontramos (.) é o que está sendo compartilhado com o container.</p><h4>LINKS</h4><pre>links:<br>  - db</pre><p>Você pode se referir a outro container que pertence ao seu arquivo docker-compose utilizando o nome dele. Como criamos um container com o nome <strong>db</strong> para o Postgres nós podemos criar um link para ele no nosso container chamado <strong>web</strong>. Pode ver que no settings.py nós colocamos ‘<strong>db</strong>’ como host.</p><h4>DEPENDS_ON</h4><p>Para rodar sua aplicação, seu banco de dados precisa estar pronto <strong>antes</strong> do container web, senão vai dar algum pau!</p><pre>depends_on:<br>  - db</pre><h4>Command</h4><p>Command é o comando padrão que o docker vai rodar logo depois que você subir, ou seja, colocar os containeres para funcionar.</p><p>No nosso exemplo, eu criei um <strong>run_web.sh</strong> que vai rodar as migrações, coletar o static files e iniciar o servidor de desenvolvimento.</p><pre>#!/usr/bin/env bash<br><br>cd django-boards/<br>python manage.py migrate<br>python manage.py collectstatic --noinput<br>python manage.py runserver 0.0.0.0:8000</pre><p>Alguém pode argumentar que migrar assim automaticamente toda vez que subir o container pode <strong>não ser uma boa prática. Eu concordo</strong>. Você pode (e deve) rodar o migrate direto na máquina web. Você pode acessar seu container para rodar comandos assim (como no bom e velho vagrant ssh):</p><pre>docker-compose run web bash</pre><p>Se você quiser , você pode rodar o comando sem acessar o container mesmo, apenas mudando o último argumento do comando acima:</p><pre>docker-compose run web python manage.py migrate</pre><p>O mesmo para outros comandos:</p><pre>docker-compose run web python manage.py test<br>docker-compose run web python manage.py shell</pre><h4>Rodando o Docker</h4><p>Com nosso Dockerfile, docker-compose.yml e o run_web.sh no lugar, vamos rodar tudo junto:</p><pre>docker-compose up</pre><p>Você pode ver esse projeto aqui <a href="https://github.com/ffreitasalves/django-boards">no meu GitHub</a>.</p><p>Escrevi esse texto <a href="https://fernandofreitasalves.com/dockerizing-django-for-development/">originalmente em inglês</a>.</p><p><em>Originally published at </em><a href="https://fernandofreitasalves.com/criando-um-container-docker-para-um-projeto-django-existente/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d142ca22be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-weekly-brazil/criando-um-container-docker-para-um-projeto-django-existente-a2d142ca22be">Criando um container Docker para um projeto Django Existente</a> was originally published in <a href="https://medium.com/python-weekly-brazil">Python Weekly Brazil</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Django for Development]]></title>
            <link>https://medium.com/@ffreitasalves/dockerizing-django-for-development-bc36bdd3bb63?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc36bdd3bb63</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[virtualenv]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Sun, 11 Feb 2018 18:48:34 GMT</pubDate>
            <atom:updated>2018-02-12T03:18:40.653Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll show how to containerize an existing project using Docker. I’ve picked a random project from GitHub that had an <a href="https://github.com/shakedown-street/django-boards/issues/66">open issue</a> saying Dockerize to contribute and use as an example here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*GFXwo8-Ys_IhzrcR.png" /></figure><p>Why in the world do you want to Dockerize an existing Django web application? There are plenty of reasons, but if you don’t have one just do it for fun!</p><p>I decided to use docker because one of my applications was getting hard to install. Lots of system requirements, multiple databases, celery, and rabbitmq. So every time a new developer joined the team or had to work from a new computer, the system installation took a long time.</p><p>Difficult installations lead to time losses and time losses lead to laziness and laziness leads to bad habits and it goes on and on… For instance, one can decide to use SQLite instead of Postgres and not see truncate problems on a table until it hits the Test server.</p><p>If you don’t know what docker is, just picture it as a huge virtualenv that instead of containing just some python packages have Containers for isolating everything from the OS to your app, databases, workers, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/0*0Rn98ibAeVTt8-j-.jpeg" /></figure><h4>Getting Things Done</h4><p>Ok, talk is cheap. Show me some code, dude.</p><p>First of all, <a href="https://docs.docker.com/install/">install </a>Docker. I did it using Ubuntu and Mac OS without any problem, but on Windows Home, I couldn’t have it working.</p><p>To tell Docker how to run your application as a container you’ll have to create a Dockerfile</p><pre>FROM python:3.6<br>ENV PYTHONUNBUFFERED 1<br><br>RUN mkdir /webapps<br>WORKDIR /webapps<br><br># Installing OS Dependencies<br>RUN apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; apt-get install -y \<br>libsqlite3-dev<br><br>RUN pip install -U pip setuptools<br><br>COPY requirements.txt /webapps/<br>COPY requirements-opt.txt /webapps/<br><br>RUN pip install -r /webapps/requirements.txt<br>RUN pip install -r /webapps/requirements-opt.txt<br><br>ADD . /webapps/<br><br># Django service<br>EXPOSE 8000</pre><p>So, let’s go line by line:</p><h4>Docker Images</h4><pre>FROM python:3.6</pre><p>Here we’re using an Image from <a href="https://hub.docker.com/">docker hub</a>. e.q. One pre-formated container that helps build on top of that. In this case, Python 3.6 is an Ubuntu container that already has Python3.6 installed on it.</p><h4>Environment Variables</h4><p>You can create all sort of Environment Variables using Env.</p><pre>ENV PYTHONUNBUFFERED 1  # Here we can create all Environment variables for our container</pre><p>For instance, if you use them for storing your Django’s Secret Key, you could put it here:</p><pre>ENV DJANGO_SECRET_KEY abcde0s&amp;&amp;$uyc)hf_3rv@!a95nasd22e-dxt^9k^7!f+$jxkk+$k-</pre><p>And in your code use it like this:</p><pre>import os<br>SECRET_KEY = os.environ[&#39;DJANGO_SECRET_KEY&#39;]</pre><h4>Run Commands</h4><p>Docker Run Commands are kinda obvious. You’re running a command “inside” your container. I’m quoting <em>inside</em> because docker creates something as sub-containers, so it doesn’t have to run the same command again in case of rebuilding a container.</p><pre>RUN mkdir /webapps<br>WORKDIR /webapps<br><br># Installing OS Dependencies<br>RUN apt-get update &amp;&amp; apt-get upgrade -y &amp;&amp; apt-get install -y \<br>libsqlite3-dev<br><br>RUN pip install -U pip setuptools<br><br>COPY requirements.txt /webapps/<br>COPY requirements-opt.txt /webapps/<br><br>RUN pip install -r /webapps/requirements.txt<br>RUN pip install -r /webapps/requirements-opt.txt<br><br>ADD . /webapps/</pre><p>In this case, We are creating the directory that will hold our files <strong>webapps/</strong>.</p><p>Workdir is also kind of self-evident. It just docker to run the commands in the indicated directory.</p><p>After that, I am including one OS dependency. When we’re just using requirements.txt usually we are not including any OS requirement for the project and believe me, for large projects you’ll have lots and lots of OS requirements.</p><h4>COPY and ADD</h4><p>Copy and ADD are the same. Both <em>copy</em> a file from your computer (the Host) into the container (The Guest OS). In my example, I’m just coping requirements to pip install them. But Add can COPY from a URL.</p><h4>EXPOSE</h4><p>Expose Instruction is for forwarding a port from Guest to the Host.</p><pre># Django service<br>EXPOSE 8000</pre><p>Ok, so now what? How can we add more containers and make them work together? What if a need a Postgresql inside a container too? Don’t worry, here we go.</p><h4>Docker-Compose</h4><p><a href="https://docs.docker.com/compose/">Docker-compose</a> is a tool for running multiple Docker containers. It’s a yml, you just need to create a docker-compose.yml on your project folder.</p><pre>version: &#39;3.3&#39;<br><br>services:<br>  # Postgres<br>  db:<br>    image: postgres<br>    environment:<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=postgres<br>      - POSTGRES_DB=postgres<br><br>  web:<br>    build: .<br>    command: [&quot;./run_web.sh&quot;]<br>    volumes:<br>      - .:/webapps<br>    ports:<br>      - &quot;8000:8000&quot;<br>    links:<br>      - db<br>    depends_on:<br>      - db</pre><p>In this case, I’m using an <a href="https://hub.docker.com/_/postgres/">Image of Postgres</a> from Docker Hub.</p><p>Now, let’s change the settings.py to use Postgres as Database.</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,<br>        &#39;NAME&#39;: &#39;postgres&#39;,<br>        &#39;USER&#39;: &#39;postgres&#39;,<br>        &#39;PASSWORD&#39;: &#39;postgres&#39;,<br>        &#39;HOST&#39;: &#39;db&#39;,<br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><p>We’re almost, done. Let me talk a little about the docker compose file.</p><h4>VOLUMES</h4><p>Remember <a href="https://www.vagrantup.com/">vagrant</a>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*6yLtYpnn3F6is50u.png" /></figure><p>Once upon a time, there was Vagrant and it was a form to run a project inside a Virtual Machine but easily configuring it forwarding ports, provisioning requirements and, sharing volumes. Your machine (Host) could share a volume with your Virtual Machine (Guest). In docker, it’s exactly the same. When you’re writing a file on a shared volume this file is being written on your container as well.</p><pre>volumes:<br>  - .:/webapps</pre><p>In this case, the current directory (.) is being shared as webapps on the container.</p><h4>LINKS</h4><pre>links:<br>  - db</pre><p>You can refer to another container that belongs to your compose using its name. Since we created a <strong>db</strong> container for our Postgres we can link it to our <strong>web</strong> container. You can see that in our settings.py file I’ve used ‘<strong>db</strong>’ as host.</p><h4>DEPENDS_ON</h4><p>In order to your application work, your database has to be<strong> ready for use</strong> before web container, otherwise, it will raise an exception.</p><pre>depends_on:<br>  - db</pre><h4>Command</h4><p>Command is the default command that your container will run right after it is up.</p><p>For our example, I’ve created a run_web.sh, that will run the migrations, collect the static files and start the development server.</p><pre>#!/usr/bin/env bash<br><br>cd django-boards/<br>python manage.py migrate<br>python manage.py collectstatic --noinput<br>python manage.py runserver 0.0.0.0:8000</pre><p>One can argue that run the migrate at this point, automatically, every time the container is up is <strong>not a good practice</strong>. <strong>I agree.</strong> You can run it directly on the web machine. You can access your container (just like the good’ol <strong>vagrant ssh</strong>) :</p><pre>docker-compose run web bash</pre><p>if you’d like you can run it without accessing the container itself, just change the last argument from the previous command.</p><pre>docker-compose run web python manage.py migrate</pre><p>The same for other commands</p><pre>docker-compose run web python manage.py test<br>docker-compose run web python manage.py shell</pre><h4>Running Docker</h4><p>With our Dockerfile, docker-compose.yml and run_web.sh set in place, just run it all together:</p><pre>docker-compose up</pre><p>You can see this project here <a href="https://github.com/ffreitasalves/django-boards">on my GitHub</a>.</p><p><em>Originally published at </em><a href="https://fernandofreitasalves.com/dockerizing-django-for-development/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc36bdd3bb63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using celery with multiple queues, retries, and scheduled tasks]]></title>
            <link>https://medium.com/@ffreitasalves/using-celery-with-multiple-queues-retries-and-scheduled-tasks-589fe9a4f9ba?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/589fe9a4f9ba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 23:23:17 GMT</pubDate>
            <atom:updated>2018-02-05T23:23:17.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*FTbp3IG4x_kg1GHA.jpg" /></figure><p>On this post, I’ll show how to work with multiple queues, scheduled tasks, and retry when something goes wrong.</p><p>If you don’t know how to use celery, read this post first: <a href="https://fernandofreitasalves.com/executing-time-consuming-tasks-asynchronously-with-django-and-celery/">https://fernandofreitasalves.com/executing-time-consuming-tasks-asynchronously-with-django-and-celery/</a></p><h4>Retrying a task</h4><p>Let’s say your task depends on an external API or connects to another web service and for any reason, it’s raising a ConnectionError, for instance. It’s plausible to think that after a few seconds the API, web service, or anything you are using may be back on track and working again. In this cases, you may want to catch an exception and retry your task.</p><pre>from celery import shared_task<br> <br>@shared_task(bind=True, max_retries=3)  # you can determine the max_retries here<br>def access_awful_system(self, my_obj_id):<br>    from core.models import Object<br>    from requests import ConnectionError<br> <br>    o = Object.objects.get(pk=my_obj_id)<br> <br>    # If ConnectionError try again in 180 seconds<br>    try:<br> <br>        o.access_awful_system()<br>  <br>    except ConnectionError as exc:<br>        self.retry(exc=exc, countdown=180)  # the task goes back to the queue</pre><p>The self.retry inside a function is what’s interesting here. That’s possible thanks to bind=True on the shared_task decorator. It turns our function <em>access_awful_system</em> into a method of Task class. And it forced us to use self as the first argument of the function too.</p><p>Another nice way to retry a function is using exponential backoff:</p><pre>self.retry(exc=exc, countdown=2 ** self.request.retries)</pre><h4>ETA — Scheduling a task for later</h4><p>Now, imagine that your application has to call an asynchronous task, but need to wait one hour until running it.</p><p>In this case, we just need to call the task using the ETA(estimated time of arrival) property and it means your task will be executed any time after ETA. To be precise not exactly in ETA time because it will depend if there are workers available at that time. If you want to schedule tasks exactly as you do in crontab, you may want to take a look at <a href="http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html">CeleryBeat</a>).</p><pre>from django.utils import timezone<br>from datetime import timedelta</pre><pre>now = timezone.now() <br> <br># later is one hour from now<br>later = now + timedelta(hours=1)</pre><pre>access_awful_system.apply_async((object_id), eta=later)</pre><h4>Using more queues</h4><p>When you execute celery, it creates a queue on your broker (in the last blog post it was RabbitMQ). If you have a few asynchronous tasks and you use just the celery default queue, all tasks will be going to the same queue.</p><p>Suppose that we have another task called <em>too_long_task </em>and one more called<em> quick_task</em> and imagine that we have one single queue and four workers.</p><p>In that scenario, imagine if the producer sends ten messages to the queue to be executed by <em>too_long_task </em>and right after that, it produces ten more messages to <em>quick_task. </em>What is going to happen? All your workers may be occupied executing <em>too_long_task</em> that went first on the queue and you don’t have workers on <em>quick_task.</em></p><p>The solution for this is <a href="http://docs.celeryproject.org/en/latest/userguide/routing.html">routing</a> each task using named queues.</p><pre># CELERY ROUTES<br>CELERY_ROUTES = {<br>    &#39;core.tasks.too_long_task&#39;: {&#39;queue&#39;: &#39;too_long_queue&#39;},<br>    &#39;core.tasks.quick_task&#39;: {&#39;queue&#39;: &#39;quick_queue&#39;},<br>}</pre><p>Now we can split the workers, determining which queue they will be consuming.</p><pre># For too long queue<br>celery --app=proj_name worker -Q too_long_queue -c 2</pre><pre># For quick queue<br>celery --app=proj_name worker -Q quick_queue -c 2</pre><p>I’m using 2 workers for each queue, but it depends on your system.</p><p>As, in the last post, you may want to run it on Supervisord</p><p><a href="http://docs.celeryproject.org/en/latest/userguide/workers.html">There is a lot of interesting things to do with your workers here.</a></p><h4>Calling Sequential Tasks</h4><p>Another common issue is having to call two asynchronous tasks one after the other. It can happen in a lot of scenarios, e.g. if the second tasks use the first task as a parameter.</p><p>You can use chain to do that</p><pre>from celery import chain<br>from tasks import first_task, second_task<br> <br>chain(first_task.s(meu_objeto_id) | second_task.s())</pre><p>The chain is a task too, so you can use parameters on apply_async, for instance, using an ETA:</p><pre>chain(salvar_dados.s(meu_objeto_id) | trabalhar_dados.s()).apply_async(eta=depois)</pre><h4>Ignoring the results from ResultBackend</h4><p>If you just use tasks to execute something that doesn’t need the return from the task you can ignore the results and improve your performance.</p><p>If you’re just saving something on your models, you’d like to use this in your settings.py:</p><pre>CELERY_IGNORE_RESULT = True</pre><h4>Sources:</h4><ul><li><a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html">Tasks - Celery 4.1.0 documentation</a></li><li><a href="http://docs.celeryproject.org/en/latest/userguide/optimizing.html#guide-optimizing">Optimizing - Celery 4.1.0 documentation</a></li><li><a href="https://denibertovic.com/posts/celery-best-practices/">Celery - Best Practices</a></li><li><a href="https://news.ycombinator.com/item?id=7909201">Celery - Best Practices | Hacker News</a></li><li><a href="http://docs.celeryproject.org/en/latest/userguide/workers.html">Workers Guide - Celery 4.1.0 documentation</a></li><li><a href="http://docs.celeryproject.org/en/latest/userguide/canvas.html">Canvas: Designing Work-flows - Celery 4.1.0 documentation</a></li></ul><h4>Super Bônus</h4><p><a href="http://lc0.github.io/blog/2013/05/01/celery-messaging-at-scale-at-instagram/">Celery Messaging at Scale at Instagram — Pycon 2013</a></p><p><em>Originally published at </em><a href="http://fernandofreitasalves.com/using-celery-with-multiple-queues-retries-and-scheduled-tasks/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=589fe9a4f9ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Melhores Podcasts sobre tecnologia e Startups]]></title>
            <link>https://medium.com/@ffreitasalves/4-melhores-podcasts-sobre-tecnologia-e-startups-69145151ff0c?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/69145151ff0c</guid>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[podcast]]></category>
            <category><![CDATA[empreendedorismo]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Thu, 18 Jan 2018 03:11:59 GMT</pubDate>
            <atom:updated>2018-01-19T03:59:55.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Ouvir Podcasts é uma forma muito eficiente para se manter por dentro do que acontece na sua área. Ouço vários Podcasts sobre tecnologia e startups, além de outros temas e tenho certeza que eles são importantes para que eu continue atualizado no meu ramo. Estar informado pode ser a diferença entre ser bom e ser ótimo.</p><p>Para quem não conhece, podcast é como um programa de rádio com a diferença de que você pode ouvir quando quiser, escolher os episódios e sempre ficará sabendo quando publicarem um programa novo. Podcast não é novidade mas não chegou a virar mainstream no Brasil ainda. Vai crescer muito este ano.</p><p>Meu aplicativo para assinar (baixar e ouvir) podcasts é o <a href="https://www.shiftyjelly.com/pocketcasts/">PocketCasts</a> ele é pago, paga uma vez só e usa todos os dias, mas existem várias outras opções gratuitas aí para quem não quiser desembolsar os R$ 12 reais. Bora pra lista:</p><h4>Hipsters.tech</h4><figure><img alt="logo do podcast hipsters.tech" src="https://cdn-images-1.medium.com/max/300/0*GljdtY4-oppb8hKQ.png" /></figure><p>Apesar do nome péssimo, clichê e modinha é na minha opinião o melhor podcast brasileiro. Tem um episódio por semana e é um programa muito bem formatado. Normalmente os episódios tem menos de uma hora e variam sobre desenvolvimento, design, empreendedorismo, etc.</p><p>Esse é um dos episódios que gostei bastante sobre <a href="https://hipsters.tech/squads-nao-suicidas-hipsters-08/">Squads</a>. Você pode dar uma olhada em outros episódios no site deles <a href="https://hipsters.tech/">https://hipsters.tech</a></p><h4>Software Engineering Daily</h4><figure><img alt="software engineering daily logo" src="https://cdn-images-1.medium.com/max/300/0*cC3T2wFJH9NnisuY.png" /></figure><p>Esse é um podcast gringo (em inglês). Eles soltam um episódio por dia útil, ou seja, é <em>daily</em> mesmo. Mesmo que não dê para ouvir todos os dias é bom ficar por dentro e olhar o que eles já fizeram. Tem entrevistas com gente da área de tecnologia e de startups, normalmente engenheiros e empreendedores de empresas renomadas e criadores das tecnologias que estão sendo discutidas. Você pode ver os <a href="https://softwareengineeringdaily.com/">episódios aqui</a></p><h4>Talk Python to Me</h4><figure><img alt="talk python to me podcast logo" src="https://cdn-images-1.medium.com/max/300/0*01PwazyK8LpU2sNg.png" /></figure><p>Esse podcast é mais específico para pythonistas, mas quem não gosta de python? Tem participações de caras muito fodas da comunidade como <a href="https://twitter.com/kennethreitz?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">Kenneth Reitz</a>, <a href="https://twitter.com/dabeaz?lang=en">David Beasley</a> e até do <a href="https://twitter.com/gvanrossum?lang=en">Guido Van Rossum</a>.</p><p>O site é esse aqui: <a href="https://talkpython.fm/">https://talkpython.fm/</a> . Meu único problema com esse podcast é que ele tinha a melhor música de abertura de qualquer podcast até o meio do ano passado, depois entrou uma música chata =P</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttp%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F14032377%26show_artwork%3Dtrue&amp;url=https%3A%2F%2Fsoundcloud.com%2Fsmixx%2Fsmixx-developers-feat-steve&amp;image=http%3A%2F%2Fi1.sndcdn.com%2Fartworks-000006621616-ej5015-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef6a4f9851d9320a417ccdb4f0592cd5/href">https://medium.com/media/ef6a4f9851d9320a417ccdb4f0592cd5/href</a></iframe><h4>Like a Boss</h4><figure><img alt="like a boss podcast logo" src="https://cdn-images-1.medium.com/max/300/0*S21Wi38zl2r_gWSY.jpg" /></figure><p>Esse é um podcast dos mesmos criadores do Hipsters. O objetivo é “trazer entrevistas com líderes, fundadores de startups e empresas inovadoras” nas próprias palavras deles. Está bem no comecinho, tem apenas 7 episódios.</p><p>Gostei bastante dessa <a href="https://www.likeaboss.com.br/episodios/david-velez-ceo-nubank-criacao-de-um-novo-banco/">entrevista com David Vélez</a>, o fundador do <a href="https://nubank.com.br/">Nubank</a>.</p><h4>Outros podcasts:</h4><p>Eu gostava muito do <a href="http://zofe.com.br/">ZOFE</a> (Zone of Front-Enders) , mas infelizmente ele não tem novas publicações já faz tempo. O site está mais desatualizado que o podcast mas ainda assim dá para ouvir conteúdo do passado. Era realizado pelo <a href="https://twitter.com/danielfilho">Daniel Filho</a>, um cara diferenciado que eu sempre via no melhor meetup de front-ends de São Paulo, o <a href="https://www.meetup.com/pt-BR/femugsp/">FEMUG-SP.</a></p><p>Falando em podcasts antigos, outro que curti bastante mas já não solta coisa nova é o <a href="http://www.grokpodcast.com/">Grok Podcast</a>. Isso que é bom dos podcasts, eles podem ter acabado mas os episódios estão aí para sempre.</p><p>Um podcast que eu descobri recentemente foi o <a href="http://castalio.info/">Castálio Podcast</a>. Também fala bastante de Python. Por enquanto, só ouvi um episódio e <a href="http://castalio.info/episodio-124-serverless-com-moacir-moda-neto.html">foi sobre serverless</a>. Aliás, dá pra ver o podcast sendo gravado ao vivo no youtube e mandar perguntas para eles.</p><p>Mais um podcast gringo que estou esperando ver como vai desenrolar é o <a href="https://moderncto.io/">Modern CTO</a>. Me parece uma estratégia audaciosa para criar conteúdo para CTOs uma coisa que não se vê todo dia. Estou começando a acompanhar.</p><p>Bom, esses foram os meus podcasts favoritos sobre esses temas. Quem tiver outros podcasts que quiser indicar deixe nos comentários.</p><p><em>Originally published at </em><a href="https://fernandofreitasalves.com/4-melhores-podcasts-sobre-tecnologia-e-startups/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69145151ff0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tanto no pessoal quanto no profissional — Boas práticas do seu trabalho na vida cotidiana]]></title>
            <link>https://medium.com/@ffreitasalves/tanto-no-pessoal-quanto-no-profissional-boas-pr%C3%A1ticas-do-seu-trabalho-na-vida-cotidiana-c99501c5d078?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99501c5d078</guid>
            <category><![CDATA[desenvolvimento-pessoal]]></category>
            <category><![CDATA[empreendedorismo]]></category>
            <category><![CDATA[rotina]]></category>
            <category><![CDATA[balanço]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 02:56:13 GMT</pubDate>
            <atom:updated>2018-01-08T02:58:27.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lAa2MMAfY7QG-OcY.jpg" /></figure><p>Não é incomum ouvirmos histórias de pessoas que são bem sucedidas no trabalho mas sua vida pessoal é uma bagunça. Maus hábitos, sedentarismo, finanças descontroladas, não tem tempo pra nada e a culpa sempre recai sobre o trabalho.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*zZC3KQ6oXbUUD0Za.jpg" /></figure><p>Dependendo de como for sua <a href="https://fernandofreitasalves.com/so-sai-rotina-quem-tem-uma/">rotina</a>, pode ser que a culpa seja do trabalho, mas o mais provável é que a culpa seja sua mesmo. Se está cursando uma faculdade e trabalha 12 horas por dia e dorme pouco pode parecer que não cabe mais nada na sua vida, mas mesmo assim é possível melhorar algum aspecto.</p><p>Sempre gostei de estudar e usava isso como desculpa para muitas coisas quando era mais novo, inclusive para não estudar. Como fiz ensino médio e técnico ao mesmo tempo (um de manhã e o outro noturno) eu deixava algumas matérias do ensino médio de lado porque gostava mais dos assuntos de computação. Se fui mal em geografia logo me escorava mentalmente em estar indo bem no curso técnico e dizia pra mim mesmo que se estivesse apenas cursando o ensino médio, teria ido bem em geografia. É o velho e batido “quem quer dá um jeito e quem não quer dá uma desculpa”.</p><p>Esse mecanismo mental de compensação é natural do ser humano. No livro <a href="https://www.amazon.com.br/Willpower-Instinct-Self-Control-Works-Matters-ebook/dp/B005ERIRZE/ref=sr_1_1?ie=UTF8&amp;qid=1515352271&amp;sr=8-1&amp;keywords=the+willpower+instinct">The Willpower Instinct</a>, a professora de Standford Kelly McGonigal fala sobre como deixamos que um bom comportamento anterior seja uma desculpa para um mau comportamento no presente. Um fenômeno bem conhecido de quem está tentando emagrecer, logo depois de fazer um exercício acaba se dando de presente um rodízio de pizza. Mesmo que já esteja provado que é muuuito <a href="https://www.vox.com/2018/1/3/16845438/exercise-weight-loss-myth-burn-calories?utm_content=buffer69e76&amp;utm_medium=social&amp;utm_source=facebook.com&amp;utm_campaign=buffer">mais difícil emagrecer só fazendo exercícios</a>.</p><p>Esse comportamento me acompanhou durante muitos anos. Sempre gostei de me ver como alguém que quer alimentar a mente com conteúdo interessante, estudando, tentando coisas novas e isso acabou sendo desculpa para nunca praticar esportes, por exemplo. Felizmente, tive a oportunidade de conhecer pessoas completas (Mente sã, corpo são). Parece que o dia dessas pessoas tem 40 horas. Elas trabalham, leem, praticam esportes, estudam, mantêm relacionamentos e tem amigos. Com certeza você conhece alguém assim também.</p><p>Mesmo assim, há 2 ou 3 anos estou querendo ser como uma dessas pessoas. Não só me dedicar no trabalho, bater metas, entregar resultados e projetos, mas também alcançar os meus resultados pessoais, bater as minhas próprias metas, melhorar em cada aspecto que eu puder melhorar. Pode parecer uma coisa de auto-ajuda e é. (Aliás, sempre desprezei o termo auto-ajuda, sempre me pareceu conversa para boi dormir, mas descobri que de cada livro, palestra ou TED Talk de auto-ajuda que eu assisto mesmo que tenha papo-furado terá algo útil para minha vida pessoal).</p><p>O que percebi é que muito das técnicas que usamos todos os dias no ambiente de trabalho para alcançar resultados são simplesmente esquecidas na nossa vida pessoal. Provavelmente sua empresa possui um planejamento, sabe quais são os objetivos, tem uma visão de longo prazo, tem valores, um budget e prioridades definidas. Mesmo que sua empresa não tenha tudo isso, você SABE que ela precisa ter. Por quê então a sua vida pessoal pode seguir dia após dia sem ter planos, metas, sem ter uma visão do que você quer para você e sem ter um orçamento para as áreas da sua vida?</p><h4>1. Escreva um plano!</h4><p>Um estudo que saiu no British Journal of Health Psychology fez um estudo com 3 grupos pedindo a cada grupo que fosse à academia pelas próximas 2 semanas. Ao primeiro grupo só foi feito o pedido. O segundo grupo além de ter recebido o pedido, também assistiram vídeos motivacionais (chamaram de grupo motivado). Já o terceiro grupo recebeu o pedido para ir a academia, assistiu os mesmos vídeos do grupo motivado e pediram que eles escrevessem a seguinte frase:</p><p><em>Durante a próxima semana eu vou praticar 20 minutos de atividade física vigorosamente na _____ (local) às __________ (horário)</em></p><p>Esse conceito é chamado de <strong>Implementation Intention </strong>(Intenção de implementação em tradução livre Fernandística). É basicamente quando você escreve as condições para terminar uma tarefa.</p><p>Os resultados foram :</p><p>38% do Grupo 1 compareceu à academia na próxima semana.</p><p>35% do Grupo 2 (Grupo Motivado)</p><p>91% do Grupo 3, o grupo que escreveu utilizando <strong>Implementation Intention</strong>.</p><p>Nunca subestime <strong>escrever um plano</strong>!</p><p>Anote no papel, no <a href="https://evernote.com/intl/pt-br/">Evernote</a> ou em qualquer lugar que você possa acessá-lo novamente depois.</p><h4>2. Crie um sistema para atingir resultados</h4><p>Somente focar em bater a meta é inútil. Não confie só na sua força de vontade para fazer você se mexer. Você precisa de um sistema que funcione para diminuir sua energia de ativação para realizar as tarefas até que elas se tornem um hábito.</p><p>Eu simplesmente não conseguia controlar o que comia ou bebia quando almoçava em restaurantes, assim resolvi que ia fazer marmitas para levar ao trabalho. Resolvi que ia preparar toda minha comida da semana aos domingos. Ao fazer dieta você começa a pensar que come todos os dias a mesma coisa e tudo vira motivo para ficar enjoado. O fato é que você não varia muito seus alimentos, mesmo quando não está fazendo dieta. Quando li isso no livro do Tim Ferris, <a href="https://www.amazon.com.br/4-Hour-Body-Uncommon-Incredible-Superhuman/dp/030746363X/ref=sr_1_1?ie=UTF8&amp;qid=1515371557&amp;sr=8-1&amp;keywords=the+4+hour+body">The 4 hour body</a>, percebi o quanto usei isso como desculpa para sair da dieta. Então resolvi ver uns vídeos no youtube sobre como preparar várias marmitas para a semana e voilá, cada vez menos falho em me alimentar bem na hora do almoço.</p><p>Criar um sistema serve para qualquer coisa, se você quer ler mais você precisa pensar que em determinado momento do seu dia ou da sua semana você vai precisar parar para ler. Se não separar esse tempo, você simplesmente não vai ler os livros que decidiu ler.</p><p>Na sua vida profissional você segue um sistema. Pode ser que você tenha que ligar para 10 clientes por dia, pode ser que você tenha que pesquisar 5 fornecedores para cada produto que você vai comprar, não importa. O sistema vai facilitar a sua vida.</p><h4>3. Priorize</h4><p>Você acordou 7h30 da manhã, foi no banheiro, levou seu celular, abriu o Facebook, deu uma scrollada, leu umas notícias, leu uns comentários e de repente são quase 9h00. Você já está atrasado, precisa tomar banho e começa seu dia naquela loucura para quando chegar em casa você entrar novamente nas redes sociais, olhar os grupos de WhatsApp, etc. Sua prioridade é essa merda de Facebook, simples assim. Desinstale ele do seu celular, assista menos TV a noite, leia menos jornal de manhã. Essa é a chave para criar tempo no seu dia. Se você gosta de postar coisas na sua rede social use o <a href="https://hootsuite.com/">Hootsuite</a>. Quer ler só o que saiu de interessante no jornal? Se inscreva em uma newsletter como o <a href="https://www.canalmeio.com.br/">Canal Meio</a>.</p><p>Muita gente acha, ou diz que se informa pelas redes sociais, quando na verdade as redes sociais e grupos estão é cheios de entretenimento e notícias irrelevantes. Aproveitar o tempo perdido nessas ferramentas é priorizar aquilo que você planejou. Acredite em mim, as notícias importantes, os acontecimentos e até mesmo os memes do momento vão chegar a você sem que você precise scrollar o seu Facebook por uma hora de manhã. Aproveite seu tempo no trânsito, arrumando a casa ou na esteira para ouvir Podcasts e aprender coisas novas, ouvir notícias ou ouvir um <a href="https://www.audible.com/">Audiobook</a>.</p><p>Com certeza para ser bem sucedido na sua vida profissional você aprendeu a priorizar entre suas tarefas. Use isso na sua vida pessoal também.</p><h4>4. Demita as pessoas tóxicas da sua vida</h4><p>Já faz alguns anos que estou demitindo pessoas que não me acrescentam em nada na vida. Sabe aquela pessoa que quando você conversa com ela você se sente drenado? Pessoas que reclamam de tudo, ou reclamam dos outros, só falam de si, etc. Essas pessoas também tomam um tempo desnecessário da sua vida. Pessoas que em qualquer ambiente de trabalho seriam a maçã podre ou um fofoqueiro. Corte-as sem dó.</p><p>Mantendo somente amizade com pessoas interessantes você vai ver que pode aprender muito com elas. Até as notícias importantes que você deixou de ler para se dedicar a outra coisa chegarão a você através desse network bem selecionado de amigos que você vai manter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*SqX2MhT3iVhjShMM.gif" /></figure><h4>5. Bônus: Meditação</h4><p>Se você é um ateu, agnóstico ou cético pode ser que balance a cabeça ao ler sobre meditação, mas isso é cientificamente comprovado que melhora muito sua qualidade de vida. Não tem a ver com energia, com ki, com cosmo, com nada disso. Meditação é um exercício no qual você foca no agora, no seu corpo, na sua respiração e quando sua mente começa a viajar você percebe isso e volta para o que tinha que fazer. Isso vai melhorar sua produtividade, seu foco, sua resiliência e sua forma de lidar com suas emoções, afinal são partes de ser humano.</p><p>Se quiser melhorar tanto sua vida profissional quanto a pessoal comece a meditar. Já falei disso aqui no blog na retrospectiva do <a href="https://fernandofreitasalves.com/aprendi-gerenciando-3-produtos-em-2016/">ano passado</a>. E se depois de tentar achar que isso não é para você então pare uns minutos na sua manhã e escreva o que estiver na sua cabeça em um caderno. Prestar atenção em você é a importantíssimo!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*PPmwJ9uMI_FuuOjV.jpg" /></figure><h4>Minha experiência pessoal</h4><p>No começo de 2017 resolvi escrever um plano pessoal, pode chamar de resolução de ano novo, pode chamar do que quiser, mas o fato é que escrever o que eu queria para minha vida no ano passado foi extremamente importante para eu ter resultados na esfera pessoal.</p><p>Os objetivos que escrevi foram:</p><ul><li>Chegar aos 88 Kg</li><li>Fazer atividade física uma vez a cada 3 dias ( ou 120 dias no ano)</li><li>Participar de uma corrida de 10 km</li><li>Fazer um curso de Machine Learning</li><li>Escrever pelo menos 6 posts no blog</li><li>Casar</li><li>Fazer uma viagem internacional</li><li>Fazer aulas de bateria</li><li>Tirar carteira de motorista</li><li>Fazer aulas de tênis</li><li>Economizar dinheiro</li><li>Ler 12 livros no ano</li></ul><p>Todos os que marquei com fonte vermelha são os objetivos que não atingi. Todos os outros eu consegui, alguns até antes do tempo e fui capaz de <a href="https://www.youtube.com/watch?v=Y1NfRN4D7NE">dobrar a meta</a>.</p><p>Lutei com meu peso nos últimos 10 anos, tentei por várias vezes praticar atividades físicas, mas sempre voltava para o sedentarismo. Muitas vezes usando a desculpa de que trabalho muito (50 a 60 horas por semana) e que não dá tempo para treinar. Em 2017 isso mudou. saí de 2016 que não fiz quase nenhuma atividade para 181 dias de atividade física em 2017. Bati os 120 dias em setembro e resolvi aumentar.</p><p>Para exercício considerei qualquer atividade física que fosse musculação ou aeróbica com 40 minutos de duração. Mesmo assim não cheguei aos 88 kg que planejara porque aprendi um pouco tarde como seguir uma dieta regrada, mas comecei o novo ano pesando 8 kg a menos que no ano anterior, com mais disposição e feliz em praticar atividades físicas diariamente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*qrRuM0n9hUbwBnIB.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*sWF0YUho9exXoHiI.jpg" /></figure><p>O sucesso de ter atingido essa meta se deve muito a como eu a escrevi, que foi um pouco mais detalhada que as outras. Com minha meta financeira também fui bem mais específico, fiz um planejamento de como faria para diminuir minhas contas mensais e conseguir fazer minha viagem internacional e guardar dinheiro. Assim consegui no meio do ano ir para Nova York, Barcelona e Paris. Surgiu uma oportunidade boa para viajar com amigos e eu já estava me preparando financeiramente para poder viajar, por mais que não tivesse o plano inteiro pronto. A oportunidade aparece, se você estiver preparado vai poder aproveitar.</p><p>Uma coisa muito legal para mim foi conseguir ler os 12 livros. Nunca tinha lido tanto em um ano. Quando cheguei em outubro já tinha lido 8 livros mas achei que não conseguiria ler mais 4 até o final do ano. Achei que era muito! Bom, tive 2 conversas na mesma semana que me motivaram, uma com uma colega de trabalho que disse ler um livro por semana e outra com um colega que fiz no bar o <a href="https://www.instagram.com/hqbierman/">HQBierman</a>. Comprei um <a href="https://www.amazon.com.br/Paperwhite-ilumina%C3%A7%C3%A3o-embutida-sens%C3%ADvel-defini%C3%A7%C3%A3o/dp/B00QJDONQY/ref=sr_1_1?ie=UTF8&amp;qid=1515376198&amp;sr=8-1&amp;keywords=kindle">Kindle com backlight</a> para ler deitado antes de dormir, comecei a ir para a cama mais cedo e ler aos domingos e consegui. No último final de semana do ano eu consegui bater minha meta. Hoje me parece que 12 livros foi fácil, esse ano quero ler 16 livros.</p><p>Ler foi uma experiência ótima pra mim, foi uma conquista. Eu lembro de assistir uma TED Talk que o palestrante dizia que Líderes são Leitores (Leaders are Readers). Ler é fazer o download da experiência de outra pessoa para a sua cabeça. E não só os livros técnicos são bons para isso, mas qualquer um. Mesmo os livros que não gostei me ensinaram alguma coisa. Esses são os livros que li esse ano:</p><ul><li><a href="https://www.amazon.com.br/4-Hour-Body-Uncommon-Incredible-Superhuman/dp/030746363X/ref=sr_1_1?ie=UTF8&amp;qid=1515371557&amp;sr=8-1&amp;keywords=the+4+hour+body">The 4 hour body — Tim Ferriss</a></li><li><a href="https://www.amazon.com.br/Freakonomics-Lado-Oculto-Inesperado-Afeta/dp/8535227407/ref=sr_1_sc_1?s=books&amp;ie=UTF8&amp;qid=1515376658&amp;sr=1-1-spell&amp;keywords=frakonomics">Freakonomics — Steve Levitt and Stephen Dubner</a></li><li><a href="https://www.amazon.com.br/Poder-do-H%C3%A1bito-Charles-Duhigg/dp/8539004119/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&amp;psc=1&amp;refRID=F0MTDM42FH8BS313170H">The power of habit — Charles Duhigg</a></li><li><a href="https://www.amazon.com.br/Total-Recall-Unbelievably-Story-English-ebook/dp/B006VGGAC4/ref=sr_1_sc_3?s=books&amp;ie=UTF8&amp;qid=1515376676&amp;sr=1-3-spell&amp;keywords=totall+recall">Total Recall — Arnold Schwarzenegger</a></li><li><a href="https://www.amazon.com.br/Anything-You-Want-Lessons-Entrepreneur-ebook/dp/B00SI0B5FS/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376715&amp;sr=1-1&amp;keywords=anything+you+want">Anything You Want — 40 Lessons For a New Kind of Entrepreneur — Derek Sivers</a></li><li><a href="https://www.amazon.com.br/Google-Biografia-Steven-Levy-ebook/dp/B00CMDED6K/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376758&amp;sr=1-1&amp;keywords=a+biografia+google">A biografia do Google -Steven Levy</a></li><li><a href="https://www.amazon.com.br/Laranja-Mec%C3%A2nica-Anthony-Burgess/dp/8576570033/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376786&amp;sr=1-1&amp;keywords=laranja+mecanica">Laranja mecânica — Anthony Burgess</a></li><li><a href="https://www.amazon.com.br/Subtle-Art-Not-Giving-Counterintuitive/dp/0062457713/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376819&amp;sr=1-1&amp;keywords=the+subtle+art+of+not+giving+a+fck">The subtle art of not giving a fuck — Mark Manson</a></li><li><a href="https://www.amazon.com.br/Clube-Luta-Chuck-Palahniuk/dp/8580444497/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376800&amp;sr=1-1&amp;keywords=clube+da+luta">Clube da Luta — Chuck Palahniuck</a></li><li><a href="https://www.amazon.com.br/Por-que-Fazemos/dp/8542207416">Por que fazemos o que fazemos — Mario Sergio Cortella</a></li><li><a href="https://www.amazon.com.br/Casais-Inteligentes-Enriquecem-Juntos-Finan%C3%A7as/dp/8543101433/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376834&amp;sr=1-1&amp;keywords=casais+inteligentes+enriquecem+juntos">Casais inteligentes enriquecem juntos — Gustavo Cerbasi</a></li><li><a href="https://www.amazon.com.br/Hard-Thing-about-Things-Building/dp/0062273205/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1515376854&amp;sr=1-1&amp;keywords=the+hard+thing+about+hard+things">The hard thing about hard things — Ben Horowitz</a></li></ul><p>Quanto à outras metas, muitas não consegui bater por que foram metas idiotas. Jeff Sutherland criador do <a href="https://www.amazon.com.br/Scrum-Fazer-Dobro-Trabalho-Metade/dp/8544104517/ref=sr_1_1?ie=UTF8&amp;qid=1515376921&amp;sr=8-1&amp;keywords=scrum">Scrum</a> diz: <em>Planejar é útil. Seguir cegamente os planos é estupidez</em>. Quando eu decidi que correria 10 km , simplesmente não pensei que estou com condromalacia patelar e que não posso correr antes de ter perdido bastante peso e fortalecido os músculos das pernas. Também não senti tanta vontade de fazer aulas de tênis, simplesmente não quis arranjar tempo pra fazer isso, musculação e bike aos fins de semana estavam sendo legais o bastante pra mim. Até cheguei a procurar por aulas de bateria, mas quando vi os preços vi que não estava com tanta vontade assim.</p><p>Das outras metas, apesar de não tê-las concluído elas andaram e isso é ótimo! Estou matriculado em uma auto-escola, já tinha começado a fazer o curso de machine learning ( e assim acabei fazendo um outro curso de gerenciamento de projetos no <a href="https://www.coursera.org/">Coursera</a>)</p><p>Quanto ao casamento ainda não saiu, mas pude fazer um pedido à minha noiva em Paris:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*EONK__gSKNfCTDtB.jpg" /></figure><p>Links interessantes:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV5BXuZL1HAg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV5BXuZL1HAg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FV5BXuZL1HAg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/285cc1378120eb9a6c0e77772b000b09/href">https://medium.com/media/285cc1378120eb9a6c0e77772b000b09/href</a></iframe><ul><li><a href="https://jamesclear.com/goals-systems">Forget About Setting Goals. Focus on This Instead.</a></li><li><a href="https://medium.com/the-mission/setting-up-a-great-system-can-help-you-achieve-almost-anything-e18bbf781cb6">Setting up a Great System Can Help You Achieve Almost Anything</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbktV25WgMII%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbktV25WgMII&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbktV25WgMII%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d60c0a25dbb0f8f45d454a6b47e631f7/href">https://medium.com/media/d60c0a25dbb0f8f45d454a6b47e631f7/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnHgK9hlHrAQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnHgK9hlHrAQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnHgK9hlHrAQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f50ddd94cafc93e67a9d836ebe422b82/href">https://medium.com/media/f50ddd94cafc93e67a9d836ebe422b82/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeTFy8RnUkoU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeTFy8RnUkoU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeTFy8RnUkoU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2154cc572f0a226a3f5de45eb252af74/href">https://medium.com/media/2154cc572f0a226a3f5de45eb252af74/href</a></iframe><p><em>Originally published at </em><a href="https://fernandofreitasalves.com/tanto-no-pessoal-quanto-no-profissional-boas-praticas-do-seu-trabalho-na-vida-cotidiana/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99501c5d078" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy for kids — Django & Python 3]]></title>
            <link>https://medium.com/hackernoon/deploy-for-kids-django-python-3-74261cae076c?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/74261cae076c</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deploy]]></category>
            <category><![CDATA[gunicorn]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 03:33:46 GMT</pubDate>
            <atom:updated>2018-01-17T11:21:28.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7j3b0akLsayNypQ9.jpg" /></figure><p>The reason many people has problems deploying is that they don’t pay enough attention to details. Deploying is easy when you are familiarized with all parts involved. You must know how to authenticate through ssh, be used to command line and Linux, understand how to configure and set up your project, have an idea of what serving static files is, what is Gunicorn… Ok, it’s not that simple. That’s why there is a lot of deploy tools, kits, and tutorials. Currently, with Ansible, Docker and whatever kids are using these days it’s easier to deploy, but what happens under the hood gets more abstract.</p><p>Maybe in a couple of years, this post is going to be obsolete if it’s not already with serverless and everything else. Anyway, just a few people want to learn how to deploy Django as I’ll show here, but if it helps at least one person, I’ll be satisfied.</p><p>Enjoy this <strong>Old-Style</strong> guide!</p><h4>The Server</h4><p>I presume you don’t have a server or <a href="https://aws.amazon.com/">AWS</a> account, <a href="https://www.digitalocean.com/">DigitalOcean</a>, <a href="https://www.linode.com/">Linode</a>… Nothing! You have to create an account in one of them and launch a server with the distro you want. If it’s your first time, don’t go with AWS because it’s way more complicated than the others.</p><p>In this tutorial, I’m using an Ubuntu 16.04, the most common distro you’ll see around. You can also pick a Debian if you like.</p><h4>Initial Set Up</h4><p>Configure server timezone</p><pre>sudo locale-gen --no-purge --lang pt_BR  # I&#39;m using pt_BR, because HUE HUE BR BR<br>sudo dpkg-reconfigure tzdata</pre><p>Update and upgrade OS Packages:</p><pre>sudo apt-get update <br>sudo apt-get -y upgrade</pre><h4>Installing Python 3.6 over Python 3.5</h4><p>Replace Python 3.5 which is default on our distro with Python 3.6.</p><pre>sudo apt-get update<br>sudo add-apt-repository ppa:jonathonf/python-3.6<br>sudo apt-get install python3.6<br>sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1<br>sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2</pre><p>You can choose which Python version the OS will call when you type python3.</p><pre>sudo update-alternatives --config python3</pre><p>Having trouble, take a look here:</p><p><a href="http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/">How to Install Python 3.6.1 in Ubuntu 16.04 LTS</a></p><h4>Install OS requirements</h4><pre>sudo apt-get install python3-pip nginx supervisor git git-core libpq-dev python-dev <br>python-virtualenv</pre><p>If your project has more OS requirements, install them as well.</p><h4>VirtualEnvWrapper for Python3</h4><p>I’m a fan of <a href="https://virtualenvwrapper.readthedocs.io/en/latest/">VirtualEnvWrapper</a>. It’s super easy and creates all my virtual environments in the same place. That’s a personal choice, if you don’t like it, use what you know how to use.</p><p>First, you install <strong>virtualenvwrapper</strong>, and then define where to put your virtualenvs. (WORKON_HOME).</p><p>If you need to use it with multiple Python versions, you must define VIRTUALENVWRAPPER_PYTHON. Here I’m using always with python3. It’s not a problem since you can create a virtualenv pointing which Python that env will use.</p><pre>sudo pip3 install virtualenvwrapper<br>echo &#39;export WORKON_HOME=~/Envs&#39; &gt;&gt; ~/.bashrc<br>echo ‘export VIRTUALENVWRAPPER_PYTHON=`which python3`’ &gt;&gt; ~/.bashrc<br>echo &#39;source /usr/local/bin/virtualenvwrapper.sh&#39; &gt;&gt; ~/.bashrc<br>source ~/.bashrc</pre><p>Now, create your virtualenv and define what Python is going to use.</p><pre>mkvirtualenv name_venv --python=python3</pre><p>VirtualEnvWrapper is really easy to use. If you want to activate a virtual env, you can use <strong>workon</strong>.</p><pre>workon name_venv</pre><p>To deactivate this virtualenv:</p><pre>deactivate</pre><p>To <strong>remove</strong> a virtualenv:</p><pre>rmvirtualenv name_venv</pre><h4>Generate SSH for GitHub Authentication</h4><p>You don’t want (neither should) write your password to git pull your project on the server.</p><p>Generating SSH Keys:</p><pre>cd ~/.ssh<br>ssh-keygen -t rsa -b 4096 -C &quot;dev@email.com&quot;<br>eval &quot;$(ssh-agent -s)&quot;<br>ssh-add ~/.ssh/id_rsa</pre><p>See and copy the content of your public key (<strong>id_rsa.pub</strong>)</p><pre>cat ~/.ssh/id_rsa.pub</pre><p>Then sign in your GitHub account and go to <a href="https://github.com/settings/keys">Settings &gt; SSH and GPG Keys</a>. Click on New SSH Key, give it a name, like (“test server keys”) and in Key paste the content of your id_rsa.pub</p><h4>Clone your Django Project</h4><p>Copy the SSH link from GitHub to clone your project. In this case, I’m using a project that I just have found as an example.</p><pre>git clone git@github.com:kirpit/django-sample-app.git</pre><p>In the project folder, install the project requirements.</p><p>Remember that you have to be in your virtual environment</p><pre>cd django-sample-app/<br>pip install -r requirements.txt</pre><p>Now, make the necessary alterations for your deploy, such as create a settings_local.py file, change database settings or anything specific to your project.</p><p>After you’re done, run your migrations and collect your static files (if you’re using it).</p><pre>python manage.py migrate<br>python manage.py collectstatic</pre><h4>Configuring NGINX</h4><p>Nginx, like Apache, is an entirely separate world. Right now, you just need the basics.</p><p><strong>/etc/nginx/sites-available/</strong> is a directory where you have to put the config files of available sites. There is another directory, <strong>/etc/nginx/sites-enabled/ </strong>that shows which sites are enabled. They are the same thing, but what is put on enabled will be served by Nginx.</p><p>It’s usual to create your config file on sites-available and create just a symlink to sites-enabled.</p><p>First of all, I’ll remove the default site from Nginx.</p><pre>sudo rm /etc/nginx/sites-enabled/default</pre><p>Now, create the config file for your site. (If you don’t know how to use VIM, use nano instead of vi)</p><pre>sudo vi /etc/nginx/sites-available/mysite</pre><p>Past this on your file, changing the necessary paths:</p><pre>server {<br> listen 80;<br> access_log /home/username/logs/access.log;<br> error_log /home/username/logs/error.log;<br><br> server_name nome-site.com.br;<br><br> location / {<br> proxy_pass <a href="http://127.0.0.1:8000;">http://127.0.0.1:8000;</a> <br><br> proxy_pass_header Server;<br> proxy_set_header X-Forwarded-Host $server_name;<br> proxy_set_header X-Real-IP $remote_addr;<br> proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br> proxy_set_header Host $http_host;<br><br><br> }<br><br> location /static {<br><br>   alias /home/username/project_path/static/;<br><br> }</pre><p>And create a symlink to sites-enabled:</p><pre>sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/mysite</pre><p>Restart Nginx:</p><pre>sudo service nginx restart</pre><p>Ok, if you made it till here, if you access your website you will see a 502 Bad Gateway from Nginx. That’s because it’s nothing here: <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000</a></p><p>Now, configure the website to run on 8000 port.</p><h4>Configuring Gunicorn</h4><p>Are you guys alive? Don’t give up, we’re almost there.</p><p>In your virtualenv (remember workon name_env?) install Gunicorn</p><pre>pip install gunicorn</pre><p>In your project’s directory, make a <strong>gunicorn_conf</strong> file:</p><pre>bind = &quot;127.0.0.1:8000&quot;<br>logfile = &quot;/home/username/logs/gunicorn.log&quot;<br>workers = 3</pre><p>Now, if you run Gunicorn you will see your website working!</p><pre>/home/username/Envs/name_venv/bin/gunicorn project.wsgi:application -c gunicorn_conf</pre><p>But what are you going to do? Run this command inside a screen and walk away? Of course not! You’ll use <a href="http://supervisord.org/">Supervisord</a> to control Gunicorn.</p><h4>Configuring Supervisor</h4><p>Now create a gunicorn.conf:</p><pre>sudo vi /etc/supervisor/conf.d/gunicorn.conf</pre><p>That’s the content:</p><pre>[program:gunicorn]<br>command=/home/username/Envs/name_venv/bin/gunicorn project.wsgi:application -c /home/username/project/project_django/gunicorn_conf<br>directory=/home/username/project/project-django<br>user=username<br>autostart=true<br>autorestart=true<br>redirect_stderr=true</pre><p>And now, you just tell Supervisor that there is a new process in town and Supervisord will take care of it:</p><pre>sudo supervisorctl reread<br>sudo supervisorctl update<br>sudo supervisorctl restart gunicorn</pre><p>And voilá! A new running you will have.</p><h4>Conclusion</h4><p>There is a lot of things involved in a deploy process. You have to configure a firewall, probably you’ll have to serve more than one static folder, etc, etc… But you have to start somewhere.</p><p>I can’t believe I wrote a whole post without using any GIF. So, just to finish, <strong>pay attention to all paths I’ve used here.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*HlHAzrHbBaSoOePt.gif" /></figure><p>Oops..</p><p><em>Originally published at </em><a href="http://fernandofreitasalves.com/deploy-for-kids-django-python-3/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74261cae076c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/deploy-for-kids-django-python-3-74261cae076c">Deploy for kids — Django &amp; Python 3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and populating a non-nullable field in Django]]></title>
            <link>https://medium.com/@ffreitasalves/creating-and-populating-a-non-nullable-field-in-django-f5ebea8f5c49?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ebea8f5c49</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 03:14:16 GMT</pubDate>
            <atom:updated>2017-08-12T03:17:21.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sV0fxQLSmoOWZUGf.jpg" /></figure><p>Hey, what’s up guys, that’s another quick post! I’ll show you how to create a new non-nullable field in Django and how to populate it using Django migrations.</p><p><strong>SAY WUUUUT?????</strong></p><figure><img alt="george costanza taking his glasses off" src="https://cdn-images-1.medium.com/max/370/0*dX-MQwa_UPiTHW3r.gif" /></figure><p>Here’s the thing, do you know when you have your website in production and everything set in order and then some guy (there’s always some guy) appears with a new must-have mandatory field that nobody, neither the client nor the PO, no one, thought about it? That’s the situation.</p><p>But it happens that you use Django Migrations and you want to add those baby fields and run your migrations back and forth, right?</p><p>For this example, I decided to use a random project from the web. I chose this <a href="https://github.com/garmoncheg/django-polls_1.10">Django Polls on Django 1.10</a>.</p><p>So, as usual, clone and create your virtual environment.</p><pre>git clone git@github.com:garmoncheg/django-polls_1.10.git<br>cd django-polls_1.10/<br>mkvirtualenv --python=/usr/bin/python3 django-polls <br>pip install django==1.10  # Nesse projeto o autor não criou um requirements.txt<br>python manage.py migrate  # rodando as migrações existentes<br>python manage.py createsuperuser <br>python manage.py runserver</pre><p>Note: This project has one missing migration, so if you’re following this step-by-step run <strong>python manage.py makemigrations</strong> to create the migration 0002 (that’s just a minor change on a verbose_name)</p><p>Now, <a href="http://(http//localhost:8000/admin/polls/question/add/)">access the admin</a> website and add a poll</p><figure><img alt="django polls admin" src="https://cdn-images-1.medium.com/max/1024/0*0hQ0T2Wx5OpJtdGH.jpg" /></figure><p>Alright, you can go to the app and <a href="http://localhost:8000/polls/">see your poll there</a>, answer it and whatever. Until now we did nothing.</p><p>The idea is to create more questions with different pub_dates to get the party started.</p><p>After you use your Polls app a little you’ll notice that any poll stay forever on your website, i.e., you never close it.</p><p>So, our update on this project will be that: From now on, all polls will have an expiration date. When the user creates a poll, he/she <strong>must</strong> enter the expiration date. That’s a non-nullable, mandatory field. For the polls that already exists in our database, we will arbitrarily decide they will have a single month to expire from the publication date.</p><p>Before migrations exist, it was done through SQL, you had to add a DateField that allowed NULL, then you’d create a query to populate this field and finally another ALTER TABLE to turn that column into a mandatory field. With the migrations, it works in the same way.</p><p>So, let’s add the <strong>expires_date</strong> field to models.py</p><pre>expires_date = models.DateTimeField(&#39;expires at&#39;, null=True)</pre><p>The whole models:</p><pre>class Question(models.Model):<br>    question_text = models.CharField(max_length=200)<br>    pub_date = models.DateTimeField(&#39;date published&#39;)<br>    expires_date = models.DateTimeField(&#39;expires at&#39;, null=True)<br><br>    def __str__(self):<br>        return self.question_text<br><br>    def was_published_recently(self):<br>        now = timezone.now()<br>        return now - datetime.timedelta(days=1) &lt;= self.pub_date &lt;= now<br>    was_published_recently.admin_order_field = &#39;pub_date&#39;<br>    was_published_recently.boolean = True<br>    was_published_recently.short_description = &#39;Published recently?&#39;</pre><p>It’s time to make migrations:</p><pre>python manage.py makemigrations</pre><p>This is going to generate the 0003_question_expires_date migration, like this:</p><pre>class Migration(migrations.Migration):<br><br>    dependencies = [<br>        (&#39;polls&#39;, &#39;0002_auto_20170429_2220&#39;),<br>    ]<br><br>    operations = [<br>        migrations.AddField(<br>            model_name=&#39;question&#39;,<br>            name=&#39;expires_date&#39;,<br>            field=models.DateTimeField(null=True, verbose_name=&#39;expires at&#39;),<br>        ),<br>    ]</pre><p>Let’s alter this migration’s code, <strong>NO PANIC!</strong></p><h4>Populating the new field</h4><p>First of all, create a function to populate the database with the expires dates:</p><pre>def populate_expires_date(apps, schema_editor):<br>    &quot;&quot;&quot;<br>    Populates expire_date fields for polls already on the database.<br>    &quot;&quot;&quot;<br>    from datetime import timedelta<br><br>    db_alias = schema_editor.connection.alias<br>    Question = apps.get_model(&#39;polls&#39;, &#39;Question&#39;)<br><br>    for row in Question.objects.using(db_alias).filter(expires_date__isnull=True):<br>        row.expires_date = row.pub_date + timedelta(days=30)<br>        row.save()</pre><p>Originally, I’ve used this code in a project with multiple databases, so I needed to use db_alias and I think it’s interesting to show it here.</p><p>Inside a migration, you’ll find a <strong>operations</strong> list. On that list, we’ll add the commands to run our populate_expires_date function and after that, we’ll alter this field to make it non-nullable.</p><pre>operations = [<br>    migrations.AddField(<br>        model_name=&#39;question&#39;,<br>        name=&#39;expires_date&#39;,<br>        field=models.DateTimeField(null=True, verbose_name=&#39;expires at&#39;),<br>    ),<br>    migrations.RunPython(populate_expires_date, reverse_code=migrations.RunPython.noop),<br>    migrations.AlterField(<br>        model_name=&#39;question&#39;,<br>        name=&#39;expires_date&#39;,<br>        field=models.DateTimeField(verbose_name=&#39;expires at&#39;),<br>    )<br>]</pre><p>You can see that we used migrations.RunPython to run our function during the migration. The reverse_code is for cases of unapplying a migration. In this case, the field didn’t exist before, so we’ll do nothing.</p><p>Right after, we’ll add the migration to alter the field and turn null=True. We also could have done that just removing that from the model and running makemigrations again. ( Now, we have to remove it from the model, anyway).</p><p>models.py</p><pre>class Question(models.Model):<br>    question_text = models.CharField(max_length=200)<br>    pub_date = models.DateTimeField(&#39;date published&#39;)<br>    expires_date = models.DateTimeField(&#39;expires at&#39;)<br><br>    def __str__(self):<br>        return self.question_text<br><br>    def was_published_recently(self):<br>        now = timezone.now()<br>        return now - datetime.timedelta(days=1) &lt;= self.pub_date &lt;= now<br>    was_published_recently.admin_order_field = &#39;pub_date&#39;<br>    was_published_recently.boolean = True<br>    was_published_recently.short_description = &#39;Published recently?&#39;</pre><p>And we’re ready to run the migrations</p><pre>python mange.py migrate</pre><p>Done! To see this working I’ll add this field to admin.py:</p><pre>class QuestionAdmin(admin.ModelAdmin):<br>    fieldsets = [<br>        (None,               {&#39;fields&#39;: [&#39;question_text&#39;]}),<br>        (&#39;Date information&#39;, {&#39;fields&#39;: [&#39;pub_date&#39;, &#39;expires_date&#39;], &#39;classes&#39;: [&#39;collapse&#39;]}),<br>    ]<br>    inlines = [ChoiceInline]<br>    list_display = (&#39;question_text&#39;, &#39;pub_date&#39;, &#39;expires_date&#39;, &#39;was_published_recently&#39;)<br>    list_filter = [&#39;pub_date&#39;]<br>    search_fields = [&#39;question_text&#39;]</pre><p>And voilá, all Questions you had on polls now have an expires_date, mandatory and with 30 days by default for the old ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*-Gq3YizCCsszoVdj.jpg" /></figure><p>That’s it, the field we wanted! The modified project is here on my GitHub: <a href="https://github.com/ffreitasalves/django-polls_1.10">https://github.com/ffreitasalves/django-polls_1.10</a></p><p>If you like it, share it and leave a comment, if you didn’t, just leave the comment.</p><p>XD</p><h4><strong>References:</strong></h4><ul><li><a href="http://stackoverflow.com/questions/28012340/django-1-7-makemigration-non-nullable-field">Django 1.7: Makemigration: non-nullable field</a></li><li><a href="http://stackoverflow.com/questions/29217706/django-view-sql-query-without-publishinhg-migrations">Django - view sql query without publishinhg migrations</a></li><li><a href="https://realpython.com/blog/python/data-migrations/">Data Migrations</a></li><li><a href="https://docs.djangoproject.com/en/1.10/howto/writing-migrations/#non-atomic-migrations">Writing database migrations | Django documentation | Django</a></li></ul><p><em>Originally published at </em><a href="http://fernandofreitasalves.com/creating-and-populating-non-nullable-field-in-django/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ebea8f5c49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pip Installing a Package From a Private Repository]]></title>
            <link>https://medium.com/@ffreitasalves/pip-installing-a-package-from-a-private-repository-b57b19436f3e?source=rss-2ac49f6afab0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b57b19436f3e</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[quick-tips]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pip]]></category>
            <dc:creator><![CDATA[Fernando Freitas Alves]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 23:52:17 GMT</pubDate>
            <atom:updated>2017-08-09T01:40:58.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1BOzu5hJmt-IxWdg.jpg" /></figure><p>That’s a python quick tip. It’s very basic, but still very helpful. When your company uses GitHub for private repositories you often want to put them on the requirements.</p><p>First of all, remember to add your public key on your GitHub settings.</p><p>You just have to use like this:</p><pre>pip install git+ssh://git@github.com/&lt;&lt;your organization&gt;&gt;/&lt;&lt;the project&gt;&gt;.git@&lt;&lt; the tag&gt;&gt;</pre><p>You can even use on your requirements, without the pip install. E.g. if your organization is called Django and your project is called… let’s say… Django and you’d like to add Django 1.11.4 in your requirements you can use like this:</p><pre>git+ssh://git@github.com/django/django.git@1.11.4</pre><p>Probably you already have a deploy key configured to your server or a machine user, it will work for your private Repos on your server, if you don’t, take a <a href="https://developer.github.com/v3/guides/managing-deploy-keys/">look at this</a></p><h4>SSH Keys</h4><p>If you don’t know how to generate your ssh-key, It’s easy:</p><pre>cd ~/.ssh<br>ssh-keygen -t rsa -b 4096 -C &quot;dev@email.com&quot;<br>eval &quot;$(ssh-agent -s)&quot;<br>ssh-add ~/.ssh/id_rsa</pre><p>Now, copy the content of your public key (<strong>id_rsa.pub</strong>).</p><pre>cat ~/.ssh/id_rsa.pub</pre><p>In your GitHub account go to <a href="https://github.com/settings/keys">Settings &gt; SSH and GPG Keys</a> and add it.</p><p><em>Originally published at </em><a href="http://fernandofreitasalves.com/pip-installing-package-from-private-repository/"><em>Fernando Alves</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b57b19436f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>