The Wayback Machine - https://web.archive.org/web/20170102153714/http://planetpython.org/

skip to navigation
skip to content

Planet Python

Last update: January 02, 2017 01:47 PM

January 02, 2017


Mike Driscoll

PyDev of the Week: Ivan Levkivskyi

This week we welcome Ivan Levkivskyi (@ILevkivskyi) as our PyDev of the Week! Ivan is the author or coauthor of several Python Enhancement Proposals, specifically 483, 484 and 526. In other words, Ivan is one of the lead developers behind adding type hints to Python via the typing module. Ivan is a scientist and as such, he has written a lot of interesting research papers, which I will readily admit that they are over my head. You might also find his Github page interesting as he is involved in a lot of projects. Let’s take some time to get to know our fellow Pythonista better!

Can you tell us a little about yourself (hobbies, education, etc):

I work as a researcher in theoretical physics. I was more interested in mathematical physics in high school, but now I mostly interested in mesoscopic physics — area that investigates the boundaries between our macroscopic world and the quantum microscopic world. I have been learning physics for about 20 years and never had any CS education. Although, I should note that my rough familiarity with category theory helps me in the programming world.

Most of the time, programming was rather my hobby, only the last 5 years I have been programming for work. My first acquaintance with programming was learning x86 assembly at an age of 10. Then I played with other languages from time to time. And now I use Python a lot in my work, mostly for prototyping and number-crunching.

I am from Ukraine originally, but now live in Switzerland. Apart from physics and programming, I like mountain sports: hiking, rock climbing, ski touring, etc. Also I like listening to music a lot and I used to play accordion and bass.

Why did you start using Python?

I first tried Python when I was playing with automated trading strategies (purely for fun) in 2009. I was struggling with some data processing in Mathematica, and a friend showed me Python. I was impressed by list comprehensions — it was love at first sight 🙂 — and I decided to learn the language more. That was probably an important point in my life: a classical case of “programming is fun again”. I became interested and learned many new programming languages that year. Now I enjoy programming especially in Python in my research work.

Another important step was last year when I started contributing to CPython. With more understanding came more appreciation of the language design and
implementation. It is a pleasure to work with CPython code.

What other programming languages do you know and which is your favorite?

I played with around a dozen programming languages, but my favorite among mainstream languages is probably C (after Python of course). Also from less popular I should point out Forth, Scheme, and Haskell. I think these three influenced a lot my programming philosophy and style.

What projects are you working on now?

I am interested in static typing in Python. I co-authored PEP 483: The theory of type hints, worked on PEP 484: Type hints, and co-authored and implemented PEP 526: Syntax for variable annotations. Static vs dynamic typing is typically considered a “dangerous” topic, since people tend to be polarized in opinions. But I like that Python has chosen a wise way to add an expressive type system while making it completely optional and gradual. Namely, one can annotate only part of the code and use a special type “Any“ to combine static and dynamic typing virtually seamlessly. This approach contrasts type declarations in more static languages like Java or C# and is closer to how it is done in Racket, Erlang, and TypeScript. One can view type hints as a way to provide structured type metadata to third party tools, or a way to write automatically verifiable documentation that accompanies docstrings. Type hints could also potentially be used for optimizations, but it is not the main direction now.

Now I am mostly focused on mypy, one of the popular Python static type checkers. In particular right now I am working on adding support for structural subtyping (a.k.a. “static duck typing” or protocols or interfaces). Also I have started working on com2ann, a small library for automatic translation between type comments and type annotations. Type comments were added because of lack of syntactic support for type annotations in earlier versions of Python. Only type comments are allowed in 2.7, and type comments are required to annotate variables prior to 3.6. The library already supports translation to PEP 526 variable annotations, more functionality will be added soon.

Finally, there is an open source project in computational genetics to which I am going to come back later.

Which Python libraries are your favorite (core or 3rd party)?


I would name “typing“ (for obvious reasons), “pickle“ that I find very simple yet useful to save some arbitrary data for later exploration or processing, “collections“ provide several handy data structures that I use frequently (for example “defaultdict“, “Counter“, “ChainMap“).
Among third party my favorites are numpy and matplotlib. I use them a lot in my work, and I am very happy with them.

Where do you see Python going as a programming language?

I think three main directions where Python will be applied the most in the following decade are:

These are probably the most important directions in general for programming now. And I believe Python will lead in these directions.

Is there anything else you’d like to say?

I am new to the open source development (around two years), but it has been a really great experience to work in Python community. I had a very warm welcome, I receive a lot of appreciation and trust as well. Python is a cool language, but community and culture formed around it are essential parts of Python’s success.

Thanks for doing the interview!

January 02, 2017 01:30 PM


Kushal Das

Looking back at 2016 blog posts

Writing more blog posts was one of my goal in 2016. Every time I tried that before, I slowly moved into a writer’s block mode. But, finally, it seems to be working for me.

Number of posts

In 2016, I wrote 53 blog posts, in 2015 the number was 37.

Number of words

I wrote around 23704 words in 2016, the year before, around 13.5k words.

Change in the workflow/tools

I am still using Shonku as my blogging tool. But, I am writing the posts first on focuswriter, and later I am moving them into the right place. I use vim for the final edit, before pushing them live. A few days back, I added AMP support in Shonku, it currently lives on a private git branch. I will push it out after few more days of testing it on my blog.

I will be writing more in the coming months. I generally speak a lot, but never managed to write down my ideas. I hope, I will be doing that regularly now.

January 02, 2017 12:12 PM

PyCon Pune updates January, 2017

We have only a month left for first ever PyCon Pune. This is a short post with the latest updates from the conference organizing team. I am listing them below without any particular order.

January 02, 2017 10:40 AM

January 01, 2017


PyTennessee

PyTN Profiles: Keynoter Sarah Guido and Intellovations


Speaker Profile: Sarah Guido (@sarah_guido)

Sarah is a data scientist who loves Python, machine learning, large-scale data, and the startup world. She is an accomplished conference speaker, community organizer, and an O'Reilly Media author. She currently resides in New York City and attended the University of Michigan for grad school.

Sarah will be presenting our opening keynote this year.

Sponsor Profile: Intellovations (@ForecastWatch)

Intellovations builds intelligent and innovative software that helps you understand, communicate, and use your data to make better decisions, increase productivity, and discover new knowledge.

We specialize in large-scale data collection and analysis, Internet-based software, and scientific and educational applications. We have experience building systems that have collected over 500 million metrics per day from Internet-based hardware, have created powerful desktop Internet-search products, and have used genetic algorithms and genetic programming for optimization.

Intellovations’ main product is ForecastWatch, a service that continually monitors and assesses the accuracy of weather forecasts around the world, and is in use by leaders in the weather forecasting industry such as AccuWeather, Foreca, Global Weather Corporation, MeteoGroup, Pelmorex, and The Weather Company.

January 01, 2017 11:15 PM


Yoong Kang Lim

3 ways of testing Django views

I tried 3 different ways of testing a Django view. These are my thoughts.

Say we have this Django view that creates a Post that we want to test:

# views.py
from . import forms

def create_post(request):
    form = forms.PostForm(request.POST or None)
    if form.is_valid():
        post = form.save()
        messages.info(request, 'Post created.')
        return redirect(post)
    return render(request, 'post/create.html', {'form': form})

How should I write tests for this view?

Let's look at 3 different ways.

Using the Django test client

Perhaps the most straightforward way is to use the Django test client 1.

from django.test import Client, TestCase


class PostViewTestCase(TestCase):
    def test_post_creation(self):
        c = Client()  # instantiate the Django test client
        response = c.post('/post/create', {'title': 'Some title', 'body': 'Some text'})
        self.assertEqual(response.redirect_chain, [('/post/1/', 302)])
        self.assertContains(response, 'Post created.')
        self.assertContains(response, 'Some title')

Pros:

Cons:

Using Selenium

We could also use Selenium with StaticLiveServerTestCase 2 (requires installing Selenium).

from django.test import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver


class PostSeleniumTest(StaticLiveServerTestCase):
    def setUp(self):
        self.browser = WebDriver()
        self.browser.implicitly_wait(10)

    def tearDown(self):
        self.browser.quit()

    def test_post_creation(self)
        # Go to Post creation form and create post
        self.browser.get('/post/create/')
        title_input = self.browser.find_element_by_name('title')
        title_input.send_keys('Some title')
        body_input = self.browser.find_element_by_name('body')
        body_input.send_keys('Some text')
        self.browser.find_element_by_xpath('//input[@value="Create post"]').click()

        # Finally, the assertions
        messages_text = self.browser.find_element_by_id('id_messages').text
        self.assertIn('Post created.', messages_text)
        post_text = self.browser.find_element_by_id('id_post').text
        self.assertIn('Some title', post_text)
        self.assertIn('Some text', post_text)

Pros:

Cons:

Unit tests

In Django's design philosophies page4, it says this (emphasis mine):

Use request objects

Views should have access to a request object – an object that stores metadata about the current request. The object should be passed directly to a view function, rather than the view function having to access the request data from a global variable. This makes it light, clean and easy to test views by passing in “fake” request objects.

Nice! That sounds like it's a good thing to use for unit tests.

"Fake" objects are usually called "Test Doubles" -- they're fake objects that respond to the same interface as the real object, but returns fixed values for the purposes of the test (instead of, say, performing an expensive calculation).

We could create a class like this ourselves, but Django provides a utility to do that via the RequestFactory 5. We can use it to pass it in the views like this:

from django.test import RequestFactory
from .views import some_view

request = RequestFactory().get('/some_url/)
response = some_view(request)  # just pass it in the view

RequestFactory doesn't handle the middleware for you (and it shouldn't), and you'll have to handle that yourself. So if you have code that writes to the request session, you'll need to mock that out.

Unit tests are different from integration tests (like the one using the test client) in that unit tests are concerned with testing one thing -- in this case, the view.

Things a unit test should do

I think these are the considerations for unit testing the view:

We don't care about anything else. In other words, our unit test should be isolated.

You might be wondering how we know if the side effect actually happened, i.e. how do we know the Post gets created?

We want to test that, but that's not the responsibility of the view's test. That responsibility relies on tests of the thing that the view calls instead.

For example, if we rely on the view to call the save() method in a ModelForm to create that side effect, we should make sure that the view calls it. But, it is the ModelForm tests that are responsible for ensuring that the object gets created.

However, Django already has extensive tests for ModelForms, so we don't have to write tests for them. We can just rely on the framework to work as expected. The caveat for this is you have custom clean() or clean_FOO() methods, which you should be testing. Also, remember that a ModelForm will call the model's full_clean() method, so if you have overridden any of the methods it calls, you should test that too. And also if you have custom validators.

That was a lot of words. Let's look at a concrete example:

Unit test example

from django.test import TestCase, RequestFactory, mock
from post import views, models


class PostTestCase(TestCase):

    @mock.patch('post.views.messages')
    @mock.patch('post.views.forms.PostForm)
    def test_create_view(self, form_class, messages):
        request = RequestFactory().post(
            '/post/create/', 
            {
                'title': 'Some title',
                'body': 'Some text',
            }
        )
        form = form_class.return_value
        form.is_valid.return_value = True
        response = views.create_post(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/post/1/')
        form.save.assert_called()  # test that save() is called
        messages.info.assert_called_with(request, 'Post created.')

This test will run a lot faster than the other two tests, since we don't touch middleware or the database.

It also feels like we have mocked half of the universe to get this test to run. The result is, sometimes unit tests will lie to you. For example, notice that I have this line in the test:

form.save.assert_called()  # test that save() is called

If for some reason, the view gets changed to use this code:

post = form.save(commit=False)

#... never calls post.save()

The test would still pass, and that's really bad.

To fix, this, you'll need to ensure that you're always calling the method with arguments that cause the side effect:

form.save.assert_called_with()  # test that save() is called with no arguments

Pros:

Cons:

Discussion

The test client is the most straightforward way to test views, and it's reasonably reliable. It can get slow if there are many database operations.

Selenium tests are very slow, and can be brittle, but it will catch all kinds of problems, including HTML elements not displaying correctly.

Unit tests are fast, but mocking can be challenging, and sometimes mocking will cause the tests to lie to you. But if you find mocking challenging, or if you find your unit tests are difficult to write, that can serve as an indicator that your code is tightly coupled and should be refactored.

Which one should we be using? My personal opinion is to use the Django test client for views that have relatively straightforward database operations.

If we have many corner cases in the view, we should also use the Django test client, but only in one or two cases (a success scenario and a fail scenario). We should use unit tests to test all the possible corner cases that we're interested in, and not using the test client multiple times.

An example of this is if we want to test the field errors on a form we submit that relies on a database query in its clean() method. We don't want to be using the test client to post to the view over and over to test each combination of field errors! Just write unit tests for the form and the view.

Selenium tests can be useful if the workflow of the thing you're testing is business critical, like the flow of customers signing up.

Resources

Testing is a deep topic. Let me leave you with a few resources I personally found helpful (mainly talks).

Sandi Metz from the Ruby community gave a talk called The Magic Tricks of Testing which is the basis of what I wrote here on what assertions a unit test should have, including command and query messages. You should watch the whole video, Sandi Metz is a wonderful speaker.

Gary Bernhardt gave a talk called Fast Test, Slow Test that discusses the speed of unit tests, and which tests are really integration tests disguised as unit tests.

Harry Percival wrote a book called Obey the Testing Goat which is a great resource for learning TDD in Django specifically. It's available for free online.

Casey Kinsey also talked about writing fast tests in his talk Writing Fast and Efficient Unit Tests for Django.


  1. Django test client. https://docs.djangoproject.com/en/1.10/topics/testing/tools/#the-test-client  ↩

  2. Django documentation for LiveServerTestCase and Selenium. https://docs.djangoproject.com/en/1.10/topics/testing/tools/#liveservertestcase ↩

  3. Splinter documentation. https://splinter.readthedocs.io/en/latest/ ↩

  4. Django's design philosophies. https://docs.djangoproject.com/en/1.10/misc/design-philosophies/#use-request-objects ↩

  5. Django's RequestFactory. https://docs.djangoproject.com/en/1.10/topics/testing/advanced/#the-request-factory ↩

  6. Python's mocking framework. https://docs.python.org/3/library/unittest.mock.html ↩

  7. Query calls, in this context, aren't necessarily database queries. I'm using query calls to mean "method/function calls that return an object, or None and do not cause a side effect". This is the terminology used by Sandi Metz in her talk "The Magic Tricks of Testing" which is also linked to in the resources section. ↩

January 01, 2017 03:00 PM


Import Python

Hey Python 2.x programmers do you see yourself making the leap to 3.x in 2017 ? - Twitter Poll

If you cannot see the widget then take the poll here.

January 01, 2017 12:33 PM

December 31, 2016


Lintel Technologies

InlineCallbacks

Twisted features a decorator named inlineCallbacks which allows you to work with deferreds without writing callback functions.

This is done by writing your code as generators, which yield deferreds instead of attaching callbacks.

Consider the following function written in the traditional deferred style:

import txredisapi as redis

from twisted.internet import defer
from twisted.internet import reactor

def main():
    rc = redis.Connection()
    print rc
    rc.addCallback(onSuccess)
    rc.addErrback(onFail)


def onSuccess(result):
    print "Success : "
    print result


def onFail(result):
    print "Fail : "
    print result


if __name__ == '__main__':
    main()
    reactor.run()

using inlineCallbacks, we can write this as:

from twisted.internet.defer import inlineCallbacks

import txredisapi as redis

from twisted.internet import defer
from twisted.internet import reactor


@defer.inlineCallbacks
def main():
    rc = yield redis.Connection()
    print rc

    yield rc.set("abc", "pqr")
    v = yield rc.get("abc")
    print "value : ", repr(v)

    yield rc.disconnect()


if __name__ == "__main__":
    main()
    reactor.run()

Instead of calling addCallback on the deferred returned by redis.Connection, we yield it. this causes Twisted to return the deferred‘s result to us.

Though the inlineCallbacks looks like synchronous code, which blocks while waiting for the request to finish, each yield statement allows other code to run while waiting for the deferred being yielded to fire.

inlineCallbacks become even more powerful when dealing with complex control flow and error handling.

The post InlineCallbacks appeared first on Lintel Technologies Blog.

December 31, 2016 08:59 AM


Mike Driscoll

wxPython Cookbook is Officially Released!

I recently finished up Mmy third book, wxPython Cookbook and I am officially releasing it today. My wxPython Cookbook is my longest book yet, clocking in at over 340 pages and over 50 recipes. I have a full table of contents on Leanpub for anyone who is interested in the nitty gritty details.

Here are the current places that you can get a copy of the book:

Thanks so much to all my readers and Kickstarter backers who have encouraged me throughout the writing process.

December 31, 2016 02:25 AM

December 30, 2016


Weekly Python StackOverflow Report

(lii) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2016-12-30 23:00:19 GMT


  1. Pythonic way to replace list values with upper and lower bound (clipping)? - [18/2]
  2. what is the most efficient way to find the position of the first np.nan value? - [11/4]
  3. How to use type hints in python 3.6? - [10/3]
  4. File size limit for read()? - [10/1]
  5. Why does the symbol '{' remain when f"\{10}" is evaluated in Python 3.6? - [10/1]
  6. Multiple 'for' loops in dictionary generator - [9/5]
  7. Python: how to Parse and check the time? - [8/2]
  8. Drawing fewer plots than specified in matplotlib subplots - [8/1]
  9. numpy ufuncs speed vs for loop speed - [7/1]
  10. Find array corresponding to minimal values along an axis in another array - [6/3]

December 30, 2016 11:00 PM


Anarcat

My free software activities, November and December 2016

Debian Long Term Support (LTS)

Those were 8th and 9th months working on Debian LTS started by Raphael Hertzog at Freexian. I had trouble resuming work in November as I had taken a long break during the month and started looking at issues only during the last week of November.

Imagemagick, again

I have, again, spent a significant amount of time fighting the ImageMagick (IM) codebase. About 15 more vulnerabilities were found since the last upload, which resulted in DLA-756-1. In the advisory, I unfortunately forgot to mention CVE-2016-8677 and CVE-2016-9559, something that was noticed by my colleague Roberto after the upload... More details about the upload are available in the announcement.

When you consider that I worked on IM back in october, which lead to an upload near the end of November covering around 80 more vulnerabilities, it doesn't look good for the project at all. Of the 15 vulnerabilities I worked on, only 6 had CVEs assigned and I had to request CVEs for the other 9 vulnerabilities plus 11 more that were still unassigned. This lead to the assignment of 25 distinct CVE identifiers as a lot of issues were found to be distinct enough to warrant their own CVEs.

One could also question how many of those issues affect the fork, Graphicsmagick. A lot of the vulnerabilities were found through fuzzing searches that may not have been tested on Graphicsmagick. It seems clear to me that a public corpus of test data should be available to test regressions and cross-project vulnerabilities. It's already hard enough to track issues withing IM itself, I can't imagine what it would be for the fork to keep track of those issues, especially since upstream doesn't systematically request CVEs for issues that they find, a questionable practice considering the number of issues we all need to keep track of.

Nagios

I have also worked on the Nagios package and produced DLA 751-1 which fixed two fairly major issues (CVE-2016-9565 and CVE-2016-9566) that could allow remote root access under certain conditions. Fortunately, the restricted permissions setup by default in the Debian package made both exploits limited to information disclosure and privilege escalation if the debug log is enabled.

This says a lot about how proper Debian packaging can help in limiting the attack surface of certain vulnerabilities. It was also "interesting" to have to re-learn dpatch to add patches to the package: I regret not converting it to quilt, as the operation is simple and quilt is so much easier to use.

People new to Debian packaging may be curious to learn about the staggering number of patching systems historically used in Debian. On that topic, I started a conversation about how much we want to reuse existing frameworks when we work on those odd packages, and the feedback was interesting. Basically, the answer is "it depends"...

NSS

I had already worked on the package in November and continued the work in December. Most of the work was done by Raphael, which fixed a lot of issues with the test suite. I tried to wrap this up by fixing CVE-2016-9074, the build on armel and the test suite. Unfortunately, I had to stop again because I ran out of hours and the fips test suite was still failing, but fortunately Raphael was able to complete the work with DLA-759-1.

As things stand now, the package is in better shape than in other suites as tests (Debian bug #806639) and autopkgtest (Debian bug #806207) are still not shipped in the sid or stable releases.

Other work

For the second time, I forgot to formally assign myself a package before working on it, which meant that I wasted part of my hours working on the monit package. Those hours, of course, were not counted in my regular hours. I still spent some time reviewing mejo's patch to ensure it was done properly and it turned out we both made similar patches working independently, always a good sign.

As I reported in my preliminary November report, I have also triaged issues in libxml2, ntp, openssl and tiff.

Finally, I should mention my short review of the phpMyAdmin upload, among the many posts i sent to the LTS mailing list.

Other free software work

One reason why I had so much trouble getting paid work done in November is that I was busy with unpaid work...

manpages.debian.org

A major time hole for me was trying to tackle the manpages.debian.org service, which had been offline since August. After a thorough evaluation of the available codebases, I figured the problem space wasn't so hard and it was worth trying to do an implementation from scratch. The result is a tool called debmans.

It took, obviously, way longer than I expected, as I experimented with Python libraries I had been keeping an eye on for a while. For the commanline interface, I used the click library, which is really a breeze to use, but a bit heavy for smaller scripts. For a web search service prototype, I looked at flask, which was also very interesting, as it is light and simple enough to use that I could get started quickly. It also, surprisingly, fares pretty well in the global TechEmpower benchmarking tests. Those interested in those tools may want to look at the source code, in particular the main command (using an interesting pattern itself, __main__.py) and the search prototype.

Debmans is the first project for which I have tried the CII Best Practices Badge program, an interesting questionnaire to review best practices in software engineering. It is an excellent checklist I recommend every project manager and programmer to get familiar with.

I still need to complete my work on Debmans: as I write this, I couldn't get access to the new server the DSA team setup for this purpose. It was a bit of a frustrating experience to wait for all the bits to get into place while I had a product ready to test. In the end, the existing manpages.d.o maintainer decided to deploy the existing codebase on the new server while the necessary dependencies are installed and accesses are granted. There's obviously still a bunch of work to be done for this to be running in production so I have postponed all this work to January.

My hope is that this tool can be reused by other distributions, but after talking with Ubuntu folks, I am not holding my breath: it seems everyone has something that is "good enough" and that they don't want to break it...

Monkeysign

I spent a good chunk of time giving a kick in the Monkeysign project, with the 2.2.2 release, which features contributions from two other developers, which may be a record for a single release.

I am especially happy to have adopted a new code of conduct - it has been an interesting process to adapt the code of conduct for such a relatively small project. Monkeysign is becoming a bit of a template on how to do things properly for my Python projects: documentation on readthedocs.org including a code of conduct, support and contribution information, and so on. Even though the code now looks a bit old to me and I am embarrassed to read certain parts, I still think it is a solid project that is useful for a lot of people. I would love to have more time to spend on it.

LWN publishing

As you may have noticed if you follow this blog, I have started publishing articles for the LWN magazine, filed here under the lwn tag. It is a way for me to actually get paid for some of my blogging work that used to be done for free. Reports like this one, for example, take up a significant amount of my time and are done without being paid. Converting parts of this work into paid work is part of my recent effort to reduce the amount of time I spend on the computer.

An funny note: I always found the layout of the site to be a bit odd, until I looked at my articles posted there in a different web browser, which didn't have my normal ad blocker configuration. It turns out LWN uses ads, and Google ones too, which surprised me. I definitely didn't want to publish my work under banner ads, and will never do so on this blog. But it seems fair that, since I get paid for this work, there is some sort of revenue stream associated with it. If you prefer to see my work without ads, you can wait for it to be published here or become a subscriber which allows you to get rid of the ads on the site.

My experience with LWN is great: they're great folks, and very supportive. It's my first experience with a real editor and it really pushed me in improving my writing to make better articles that I normally would here. Thanks to the LWN folks for their support! Expect more of those quality articles in 2017.

Debian packaging

I have added a few packages to the Debian archive:

I have also updated sopel and atheme-services.

Other work

Against my better judgment, I worked again on the borg project. This time I tried to improve the documentation, after a friend asked me for help on "how to make a quick backup". I realized I didn't have any good primer to send regular, non-sysadmin users to and figured that, instead of writing a new one, I could improve the upstream documentation instead.

I generated a surprising 18 commits of documentation during that time, mainly to fix display issues and streamline the documentation. My final attempt at refactoring the docs eventually failed, unfortunately, again reminding me of the difficulty I have in collaborating on that project. I am not sure I succeeded in making the project more attractive to non-technical users, but maybe that's okay too: borg is a fairly advanced project and not currently aimed at such a public. This is yet another project I am thinking of creating: a metabackup program like backupninja that would implement the vision created by liw in his A vision for backups in Debian post, which was discarded by the Borg project.

Github also tells me that I have opened 19 issues in 14 different repositories in November. I would like to particularly bring your attention to the linkchecker project which seems to be dead upstream and for which I am looking for collaborators in order to create a healthy fork.

Finally, I started on reviving the stressant project and changing all my passwords, stay tuned for more!

December 30, 2016 10:00 PM


PyCharm

PyCharm 2016.3.2 Released

Right before the end of the year we’d like to release our latest and greatest version of PyCharm 2016. This version resolves a few issues:

To get this improved version, you can download it from our website. Once patch updates are ready for your platform, you’ll get a notification, so you can update from within PyCharm, by choosing Help | Check for Updates on Windows and Linux, or by choosing PyCharm | Check for Updates on macOS.

Thank you for your interest in PyCharm, and we’d like to wish you a happy and productive 2017!

-PyCharm Team
The Drive to Develop

December 30, 2016 02:34 PM


Import Python

ImportPython Issue 105 - Modern Dict, Tidy / sanitize data, drop Python 2 in 2017

Worthy Read

Python's dictionaries are stunningly good. Over the years, many great ideas have combined together to produce the modern implementation in Python 3.6. This fun talk is given by Raymond Hettinger, the Python core developer responsible for the set implementation and who designed the compact-and-ordered dict implemented in CPython for Python 3.6 and in PyPy for Python 2.7.
core-python
,
dict

How popular is Python? Based on our survey findings, 19% of Linux and 13% of macOS developers use Python as their primary server-side language. If you want to read more insights like these, contribute to the latest Developer Economics survey - you’ll receive analysed trends in your inbox! The survey is fun, while you’ll get the chance to win a prize, and learn something new !
Sponsor

I ran into this situation today where I wanted to issue a few commands over ssh to a remote host as part of a Click command I'm building to do some ops automation here at REVSYS. It's probably not perfect in terms of error handling, but it sure is simple!.
ssh
,
click

The course will also introduce data manipulation and cleaning techniques using the popular python pandas data science library and introduce the abstraction of the DataFrame as the central data structure for data analysis. The course will end with a statistics primer, showing how various statistical measures can be applied to pandas DataFrames. By the end of the course, students will be able to take tabular data, clean it, manipulate it, and run basic inferential statistical analyses.
data science
,
mooc

In this post, I will summarize some tidying examples Wickham uses in his paper and I will demonstrate how to do so using the Python pandas library.

Considering rich Python Ecosystem of tools, libraries, and frameworks for data crunching, I’d like to share a few examples how to plug Datahub API as a data source to your Python-based workflow. I’ll start with a simple example: how to turn Datahub API JSON output into Numpy arrays using Pandas framework.

Python 3.6.0 came out day before yesterday, and it was like a Christmas present for many of us. But in the midst of all the celebration, many of you were still asking if it is safe to drop Python 2 and move over to Python 3. There still seems to be a fear of missing out on useful third party libraries that lack Python 3 support. So in this post, I will try to settle this issue once and for all by presenting the relevant data. After you have seen all the data, you will be able to come to your own conclusion (I have already expressed my conclusion in the title).
python3

There are already a fair number of books about Numpy (see Bibliography) and a legitimate question is to wonder if another book is really necessary. As you may have guessed by reading these lines, my personal answer is yes, mostly because I think there is room for a different approach concentrating on the migration from Python to Numpy through vectorization.
numpy

performance

pykids is a voluntary effort to bring Python to elementary school (5th & 6th grades). At present I run AWS servers to support my venture. These servers are available for anyone to use. I run a monthly bill of about 20 USD to run this server. The money that you donate will go into support keeping these servers online.
community

IDE

dependency

opinion


Jobs

Bangalore, India
Venture backed company developing technology platform in the field of Law and Finance. They have released SaaS based product |(Complius) in area of legal compliances.


Projects

soundhax - 124 Stars, 20 Fork
A heap overflow in tag processing leads to code execution when a specially- crafted m4a file is loaded by Nintendo 3DS Sound. This bug is particularly good, because as far as I can tell it is the first ever homebrew exploit that is free, offline, and works on every version of the firmware for which the sound app is available.

pep8speaks - 69 Stars, 3 Fork
A GitHub integration to automatically review Python code style over Pull Requests

mx-lsoftmax - 24 Stars, 7 Fork
mxnet version of Large-Margin Softmax Loss for Convolutional Neural Networks.

objectify - 9 Stars, 1 Fork
Upload any image, and the app will tell you the object in the image and translate it to any language you want (read out aloud).

djangohero - 8 Stars, 2 Fork
DjangoHero automates the process of starting a new Django project on Heroku.

pipupdate - 2 Stars, 1 Fork
An easy-to-use PIP package manager. Update, force reinstall, do an easy requirements.txt install, and uninstall all packages in 1 command.

December 30, 2016 07:21 AM


Catalin George Festila

The python arch module for financial econometrics.

This python module arch: is a work-in-progress for ARCH and other tools for financial econometrics, written in Python (and Cython).
The arch python module come with tools for:

You can read and see many examples here.
Let's start with instalation into my python 2.7.12 version.
First you need to install this python module with pip tool:
C:\Python27\Scripts>pip install Arch
Collecting Arch
Downloading arch-4.0.tar.gz (107kB)
100% |################################| 112kB 390kB/s
Requirement already satisfied: matplotlib>=1.4 in c:\python27\lib\site-packages (from Arch)
Requirement already satisfied: scipy>=0.15 in c:\python27\lib\site-packages (from Arch)
Collecting patsy>=0.2 (from Arch)
Downloading patsy-0.4.1-py2.py3-none-any.whl (233kB)
100% |################################| 235kB 906kB/s
Collecting statsmodels>=0.6 (from Arch)
Downloading statsmodels-0.6.1.tar.gz (7.0MB)
100% |################################| 7.0MB 85kB/s
Collecting pandas>=0.16 (from Arch)
Downloading pandas-0.19.2-cp27-cp27m-win32.whl (6.8MB)
100% |################################| 6.8MB 81kB/s
Requirement already satisfied: numpy>=1.6 in c:\python27\lib\site-packages (from matplotlib>=1.4->Arch)
Requirement already satisfied: python-dateutil in c:\python27\lib\site-packages (from matplotlib>=1.4->Arch)
Requirement already satisfied: cycler in c:\python27\lib\site-packages (from matplotlib>=1.4->Arch)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,>=1.5.6 in c:\python27\lib\site-packages (from matplotlib>=1.4->Arch)
Requirement already satisfied: pytz in c:\python27\lib\site-packages (from matplotlib>=1.4->Arch)
Requirement already satisfied: six in c:\python27\lib\site-packages (from patsy>=0.2->Arch)
Installing collected packages: patsy, pandas, statsmodels, Arch
Running setup.py install for statsmodels ... done
Running setup.py install for Arch ... done
Successfully installed Arch-4.0 pandas-0.19.2 patsy-0.4.1 statsmodels-0.6.1

This python module is very mathematical and technical so I'll refer you to a few examples.
Can be used in statistical research and econometrics, or the application of mathematics, statistics, and computer science to economic data. 

December 30, 2016 03:12 AM


Vasudev Ram

Jal-Tarang, and a musical alarm clock in Python

By Vasudev Ram

Hi readers,

Season's greetings!

After you check out this video (Ranjana Pradhan playing the Jal Tarang in Sydney, 2006, read the rest of the post below ...



Here is a program that acts as a musical command-line alarm clock. It is an adaptation of the one I created here a while ago:

A simple alarm clock in Python (command-line)

This one plays a musical sound (using the playsound Python library) when the alarm time is reached, instead of beeping like the above one does. I had recently come across and used the playsound library in a Python course I conducted, so I thought of enhancing the earlier alarm clock app to use playsound. Playsound is a nice simple Python module with just one function, also called playsound, which can play either WAV or MP3 audio files on Windows.

The playsound library is described as "a pure Python, cross platform, single function module with no dependencies for playing sounds."

Excerpt from its PyPI page:

[ On Windows, uses windll.winmm. WAVE and MP3 have been tested and are known to work. Other file formats may work as well.

On OS X, uses AppKit.NSSound. WAVE and MP3 have been tested and are known to work. In general, anything QuickTime can play, playsound should be able to play, for OS X.

On Linux, uses ossaudiodev. I don’t have a machine with Linux, so this hasn’t been tested at all. Theoretically, it plays WAVE files. ]

Here is the code for the program, musical_alarm_clock.py:

from __future__ import print_function

'''
musical_alarm_clock.py

Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram

Description: A simple program to make the computer act like
a musical alarm clock. Start it running from the command line
with a command line argument specifying the number of minutes
after which to give the alarm. It will wait for that long, and
then play a musical sound a few times.
'''

import sys
import string
from playsound import playsound, PlaysoundException
from time import sleep, asctime

sa = sys.argv
lsa = len(sys.argv)
if lsa != 2:
print("Usage: python {} duration_in_minutes.".format(sys.argv[0]))
print("Example: python {} 10".format(sys.argv[0]))
print("Use a value of 0 minutes for testing the alarm immediately.")
print("The program plays a musical sound a few times after the duration is over.")
sys.exit(1)

try:
minutes = int(sa[1])
except ValueError:
print("Invalid value {} for minutes.".format(sa[1]))
print("Should be an integer >= 0.")
sys.exit(1)

if minutes < 0:
print("Invalid value {} for minutes.".format(minutes))
print("Should be an integer >= 0.")
sys.exit(1)

seconds = minutes * 60

if minutes == 1:
unit_word = "minute"
else:
unit_word = "minutes"

try:
print("Current time is {}.".format(asctime()))
if minutes > 0:
print("Alarm set for {} {} later.".format(str(minutes), unit_word))
sleep(seconds)
else:
print("Running in immediate test mode, with no delay.")
print("Alarm time reached at {}.".format(asctime()))
print("Wake up.")
for i in range(5):
playsound(r'c:\windows\media\chimes.wav')
#sleep(1.00)
sleep(0.50)
#sleep(0.25)
#sleep(0.10)
except PlaysoundException as pe:
print("Error: PlaysoundException: message: {}".format(pe))
sys.exit(1)
except KeyboardInterrupt:
print("Interrupted by user.")
sys.exit(1)



Jal Tarang image attribution

The picture above is of a Jal Tarang.

The Jal Tarang is an ancient Indian melodic percussion instrument. Brief description adapted from the Wikipedia article: It consists of a set of bowls filled with water. The bowls can be of different sizes and contain different amounts of water. The instrument is tuned by adjusting the amount of water in each bowl. The music is played by striking the bowls with two sticks.

I've watched live jal-tarang performances only a few times as a kid (it was probably somewhat uncommon even then, and there are very few people who play it nowadays), so it was interesting to see this video and read the article.

Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates (via Gumroad) on my forthcoming apps and content.

Jump to posts: Python * DLang * xtopdf

Subscribe to my blog by email

My ActiveState Code recipes

Follow me on: LinkedIn * Twitter

Managed WordPress Hosting by FlyWheel



December 30, 2016 02:53 AM


Python Data

Stockstats – Python module for various stock market indicators

I’m always working with stock market data and stock market indicators. During this work, there’s times that I need to calculate things like Relative Strength Index (RSI), Average True Range (ATR), Commodity Channel Index (CCI) and other various indicators and stats.

My go-to for this type of work is TA-Lib and the python wrapper for TA-Lib but there’s times when I can’t install and configure TA-Lib on a computer. When this occurs, I then have to go find the various algorithms to calculate the various indicators / stats that I need.  When this happens, I usually end up making mistakes and/or taking longer than I really should to get these algo’s built to use in a project.  Of course I re-use what I can when I can but many times I’ve forgotten that I built an RSI function in the past and recreate.

I found myself in this situation today. I need an RSI calculation for some work I’m doing.  I couldn’t get TA-Lib installed and working on the machine I was working on (no clue what was wrong either) so I decided to write my own indicator.  While looking around the web for a good algorithm to use, I ran across a new module that I hadn’t see before called stockstats.

Stockstats is a wrapper for pandas dataframes and provides the ability to calculate many different stock market indicators / statistics.  The fact that it is a simple wrapper around pandas is ideal since I do 99% of my work within pandas.

To use stockstats, you simply to to ‘convert’ a pandas dataframe to a stockstats dataframe. This can be done like so:

stockstats_df = StockDataFrame.retype(df)

Then, to calculate the RSI for this dataframe, all you need to do is pass a command into the stockstats dataframe.

stock['rsi_14']

The above calculates the 14-day RSI for the entire dataframe.

Let’s look at a full example using data from yahoo.

First, import the modules we’ll need:

import pandas as pd
import pandas.io.data as web
from stockstats import StockDataFrame as Sdf

Pull down all the historical data for the S&P 500 ETF (SPY):

data = web.get_data_yahoo('SPY')

Taking a look at the ‘tail’ of the data gives us something like the data in Table 1.

SPY historical data - stock market indicatorsTable 1: SPY Historical Data

To calculate RSI, retype the pandas dataframe into a stockstats dataframe and then calculate the 14-day RSI.

stock_df = Sdf.retype(data)
data['rsi']=stock_df['rsi_14']

With this approach, you end up with some extra columns in your dataframe. These can easily be removed with the ‘del’ command.

del data['close_-1_s']
del data['close_-1_d']
del data['rs_14']
del data['rsi_14']

With these extra columns removed, you now have the 14-day RSI values a column titled “rsi”.

SPY Historical Data with RSI  - stock market indicatorsTable 2: SPY Historical Data with RSI

One caveat on this approach – stockstats seems to take the ‘close’ column. This might or might not be an issue for you if you are wanting to use the Adj Close column provided by yahoo. This is a simple fix (delete the ‘close’ and rename ‘adj close’ to ‘close’).

Stockstats currently has about 26 stats and stock market indicators included. Definitely not as robust as TA-Lib, but it does have the basics. If you are working with stock market data and need some quick indicators / statistics and can’t (or don’t want to) install TA-Lib, check out stockstats.

The post Stockstats – Python module for various stock market indicators appeared first on Python Data.

December 30, 2016 12:09 AM

December 29, 2016


PyCharm

PyCharm 2017.1 Early Access Program Started

Even though PyCharm 2016.3 was only released last month, we haven’t been idle, and we have been working hard on improving PyCharm. If you want to have a sneak peek at what’s coming in the next version of PyCharm, you can download our Early Access Program (EAP) versions which we will be releasing regularly from now on until the release.

In this first EAP release for PyCharm 2017.1 we’ve included these features:

Several bugs have been fixed as well:

We’d like to invite you to try this EAP build and to let us know how you like it. If you encounter any issues with the EAP you can report an issue on our issue tracker. You can also reach out to us by commenting on this blog post, or by tweeting us. If you’d like to let us know about a feature you’d like us to develop, please let us know as well!

Finally, we’d like to wish you a happy 2017, we hope your code in the next year will be better than ever before!

-PyCharm Team
The Drive to Develop

December 29, 2016 05:26 PM


Talk Python to Me

#92 Bonus: Python Bytes Crossover: Python 3.6 is going to be awesome, Kite: your friendly co-developing AI

Here's a bonus as many of you are on winter break or travelling around. I hope you enjoy this episode of Python Bytes. If you love it, be sure to subscribe to the full podcast. <br/> <br/> Full <a href='https://pythonbytes.fm/episodes/show/6/python-3.6-is-going-to-be-awesome-kite-your-friendly-co-developing-ai'>show notes here</a>.

December 29, 2016 08:00 AM


Python Data

Book Review – Machine Learning With Random Forests And Decision Trees by Scott Hartshorn

Machine Learning With Random Forests And Decision Trees: A Mostly Intuitive Guide, But Also Some PythonI just finished reading Machine Learning With Random Forests And Decision Trees: A Mostly Intuitive Guide, But Also Some Python (amazon affiliate link).

The short review

This is a great introductory book for anyone looking to learn more about Random Forests and Decision Trees. You won’t be an expert after reading this book, but you’ll understand the basic theory and and how to implement random forests in python.

The long(ish) review

This is a short book – only 76 pages. But…those 76 pages are full of good, introductory information on Random Forests and Decision Trees.  Even though I’ve been using random forests and other machine learning approaches in python for years, I can easily see value for people that are just starting out with machine learning and/or random forests. That said, there were a few things in the book that I had either forgotten or didn’t know (Entropy Criteria for example).

While the entire book is excellent, the section on Feature Importance is the best in the book.  This section provides a very good description of the ‘why’ and the ‘how’ of feature importance (and therefore, feature selection) for use in random forests and decision trees.  There are some very good points made in this section regarding how to get started with feature selection and cross validation.

Additionally, the book provides a decent overview of the idea of ‘out-of-sample’ (or ‘Out-of-bag’) data.  I’m a huge believer in keeping some data out of your initial training data set to use for validation after you’ve built your models.

If you’re looking for a good introductory book on random forests and decision trees, pick this one up ( (amazon affiliate link)) …its only $2.99 for the kindle version.  Like I mentioned earlier, this book won’t make you an expert but it will provide a solid grounding to get started on the topic of random forests, decision trees and machine learning.

One negative comment I have on this book is that there is very little python in the book. The book isn’t marketed as strictly a python book, but I would have expected a bit more python in the book to help drive home some of the theory with runnable code. That said, this is a very small negative to the book overall.

 

 

The post Book Review – Machine Learning With Random Forests And Decision Trees by Scott Hartshorn appeared first on Python Data.

December 29, 2016 01:39 AM


Armin Ronacher

Be Careful with Python's New-Style String Format

This should have been obvious to me for a longer time, but until earlier today I did not really realize the severity of the issues caused by str.format on untrusted user input. It came up as a way to bypass the Jinja2 Sandbox in a way that would permit retrieving information that you should not have access to which is why I just pushed out a security release for it.

However I think the general issue is quite severe and needs to be a discussed because most people are most likely not aware of how easy it is to exploit.

The Core Issue

Starting with Python 2.6 a new format string syntax landed inspired by .NET which is also the same syntax that is supported by Rust and some other programming languages. It's available behind the .format() method on byte and unicode strings (on Python 3 just on unicode strings) and it's also mirrored in the more customizable string.Formatter API.

One of the features of it is that you can address both positional and keyword arguments to the string formatting and you can explicitly reorder items at all times. However the bigger feature is that you can access attributes and items of objects. The latter is what is causing the problem here.

Essentially one can do things like the following:

>>> 'class of {0} is {0.__class__}'.format(42)
"class of 42 is <class 'int'>"

In essence: whoever controls the format string can access potentially internal attributes of objects.

Where does it Happen?

First question is why would anyone control the format string. There are a few places where it shows up:

  • untrusted translators on string files. This is a big one because many applications that are translated into multiple languages will use new-style Python string formatting and not everybody will vet all the strings that come in.
  • user exposed configuration. One some systems users might be permitted to configure some behavior and that might be exposed as format strings. In particular I have seen it where users can configure notification mails, log message formats or other basic templates in web applications.

Levels of Danger

For as long as only C interpreter objects are passed to the format string you are somewhat safe because the worst you can discover is some internal reprs like the fact that something is an integer class above.

However tricky it becomes once Python objects are passed in. The reason for this is that the amount of stuff that is exposed from Python functions is pretty crazy. Here is an example from a hypothetical web application setup that would leak the secret key:

CONFIG = {
    'SECRET_KEY': 'super secret key'
}

class Event(object):
    def __init__(self, id, level, message):
        self.id = id
        self.level = level
        self.message = message

def format_event(format_string, event):
    return format_string.format(event=event)

If the user can inject format_string here they could discover the secret string like this:

{event.__init__.__globals__[CONFIG][SECRET_KEY]}

Sandboxing Formatting

So what do you do if you do need to let someone else provide format strings? You can use the somewhat undocumented internals to change the behavior.

from string import Formatter
from collections import Mapping

class MagicFormatMapping(Mapping):
    """This class implements a dummy wrapper to fix a bug in the Python
    standard library for string formatting.

    See http://bugs.python.org/issue13598 for information about why
    this is necessary.
    """

    def __init__(self, args, kwargs):
        self._args = args
        self._kwargs = kwargs
        self._last_index = 0

    def __getitem__(self, key):
        if key == '':
            idx = self._last_index
            self._last_index += 1
            try:
                return self._args[idx]
            except LookupError:
                pass
            key = str(idx)
        return self._kwargs[key]

    def __iter__(self):
        return iter(self._kwargs)

    def __len__(self):
        return len(self._kwargs)

# This is a necessary API but it's undocumented and moved around
# between Python releases
try:
    from _string import formatter_field_name_split
except ImportError:
    formatter_field_name_split = lambda \
        x: x._formatter_field_name_split()

class SafeFormatter(Formatter):

    def get_field(self, field_name, args, kwargs):
        first, rest = formatter_field_name_split(field_name)
        obj = self.get_value(first, args, kwargs)
        for is_attr, i in rest:
            if is_attr:
                obj = safe_getattr(obj, i)
            else:
                obj = obj[i]
        return obj, first

def safe_getattr(obj, attr):
    # Expand the logic here.  For instance on 2.x you will also need
    # to disallow func_globals, on 3.x you will also need to hide
    # things like cr_frame and others.  So ideally have a list of
    # objects that are entirely unsafe to access.
    if attr[:1] == '_':
        raise AttributeError(attr)
    return getattr(obj, attr)

def safe_format(_string, *args, **kwargs):
    formatter = SafeFormatter()
    kwargs = MagicFormatMapping(args, kwargs)
    return formatter.vformat(_string, args, kwargs)

Now you can use the safe_format method as a replacement for str.format:

>>> '{0.__class__}'.format(42)
"<type 'int'>"
>>> safe_format('{0.__class__}', 42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__

December 29, 2016 12:00 AM

December 28, 2016


Simon Wittber

I made a Server Program in Go.

MiddleMan: A Pub/Sub and Request/Response server in Go.

This is my first Go project. It is a rewrite of an existing Python server, based on some previous work: https://entitycrisis.blogspot.de/2016/09/python3-asyncio-pubsub-plaything.html

All code available here: https://github.com/simonwittber/middleman

I can see Go becoming my preferred language for game servers.

December 28, 2016 09:39 PM


Django Weblog

Django Fellowship Program: 2016 retrospective

2016 concludes my second year working full-time to support the development of Django. Here are some highlights from my weekly summaries published on the django-developers mailing list.

On the infrastructure front, I keep Django's continuous integration servers running smoothly, including the pull request checks that help keep code quality high and allow reviewers to focus on less trivial concerns. I also upgraded the djangoproject.com website to Django 1.10 and contributed several patches to third-party dependencies. I moved two under-maintained community sites, Django People and Django Snippets, to the djangoproject GitHub organization and upgraded them to supported versions of Django.

In Django's ticket tracker, I triage around 10-15 new tickets each week. A working knowledge of the 1000+ accepted tickets allows me to quickly identify duplicate and related issues and steer contributors in the right direction.

I coordinate security releases by preparing patches and backporting them to all supported versions of Django. In 2016, seven security issues were promptly fixed over five releases.

Django 1.10 marked the third consecutive on-time major release. As the release manager, I send regular email updates on the status of release blockers to django-developers, and I fix blockers when no one else has time or interest.

The Django 1.11 alpha is scheduled for mid-January with the final release scheduled for April 1. Following the 1.11 alpha release, the master development branch will target Django 2.0 and drop support for Python 2.7. I'm excited to see the simplifications and improvements we'll be able to make as a result.

Over the Python 3.6 prerelease period, I ensured compatibility with the Django master branch, including contributing several fixes and improvements for Python.

I co-mentored a Google Summer of Code project by Akshesh Doshi to add support for class-based indexes. This work is included in Django 1.11. I also made the final push to finish the template-based widget rendering patch that Preston Timmons started several years ago, and this is also included in 1.11.

While working toward the 1.11 feature release, we've had monthly bug fix releases for the 1.10 branch that have fixed over 40 regressions or bugs in new features.

On the code review front, I review an average of fifteen non-trivial patches a week from community members. Providing timely code reviews helps prevent would-be contributors from abandoning us.

I hope that gives you a good taste of what I've been doing. As always, please encourage your employer to become a corporate member of the Django Software Foundation and consider a gift to the Django Software Foundation to allow the fellowship to continue. I'm grateful for this opportunity and for the community's support. Thank you!

December 28, 2016 08:02 PM


Trey Hunner

The Iterator Protocol: How for Loops Work in Python

We’re interviewing for a job and our interviewer has asked us to remove all for loops from a block of code. They then mentioned something about iterators and cackled maniacally while rapping their fingers on the table. We’re nervous and frustrated about being assigned this ridiculous task, but we’ll try our best.

To understand how to loop without a for loop, we’ll need to discover what makes for loops tick.

We’re about to learn how for loops work in Python. Along the way we’ll need to learn about iterables, iterators, and the iterator protocol. Let’s loop. ➿

Looping with indexes: a failed attempt

We might initially try to remove our for loops by using a traditional looping idiom from the world of C: looping with indexes.

1
2
3
4
5
colors = ["red", "green", "blue", "purple"]
i = 0
while i < len(colors):
    print(colors[i])
    i += 1

This works on lists, but it fails on sets:

1
2
3
4
5
6
7
8
9
>>> colors = {"red", "green", "blue", "purple"}
>>> i = 0
>>> while i < len(colors):
...     print(colors[i])
...     i += 1
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'set' object does not support indexing

This approach only works on sequences, which are data types that have indexes from 0 to one less than their length. Lists, strings, and tuples are sequences. Dictionaries, sets, and many other iterables are not sequences.

We’ve been instructed to implement a looping construct that works on all iterables, not just sequences.

Iterables: what are they?

In the Python world, an iterable is any object that you can loop over with a for loop.

Iterables are not always indexable, they don’t always have lengths, and they’re not always finite.

Here’s an infinite iterable which provides every multiple of 5 as you loop over it:

1
2
from itertools import count
multiples_of_five = count(step=5)

When we were using for loops, we could have looped over the beginning of this iterable like this:

1
2
3
4
for n in multiples_of_five:
    if n > 100:
        break
    print(n)

If we removed the break condition from that for loop, it would go on printing forever.

So iterables can be infinitely long: which means that we can’t always convert an iterable to a list (or any other sequence) before we loop over it. We need to somehow ask our iterable for each item of our iterable individually, the same way our for loop works.

Iterables & Iterators

Okay we’ve defined iterable, but how do iterables actually work in Python?

All iterables can be passed to the built-in iter function to get an iterator from them.

1
2
3
4
5
6
>>> iter(['some', 'list'])
<list_iterator object at 0x7f227ad51128>
>>> iter({'some', 'set'})
<set_iterator object at 0x7f227ad32b40>
>>> iter('some string')
<str_iterator object at 0x7f227ad51240>

That’s an interesting fact but… what’s an iterator?

Iterators have exactly one job: return the “next” item in our iterable. They’re sort of like tally counters, but they don’t have a reset button and instead of giving the next number they give the next item in our iterable.

You can get an iterator from any iterable:

1
>>> iterator = iter('hi')

And iterators can be passed to next to get their next item:

1
2
3
4
5
6
7
8
>>> next(iterator)
'h'
>>> next(iterator)
'i'
>>> next(iterator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

So iterators can be passed to the built-in next function to get the next item from them and if there is no next item (because we reached the end), a StopIteration exception will be raised.

Iterators are also iterables

So calling iter on an iterable gives us an iterator. And calling next on an iterator gives us the next item or raises a StopIteration exception if there aren’t any more items.

There’s actually a bit more to it than that though. You can pass iterators to the built-in iter function to get themselves back. That means that iterators are also iterables.

1
2
3
4
>>> iterator = iter('hi')
>>> iterator2 = iter(iterator)
>>> iterator is iterator2
True

That fact leads to some interesting consequences that we don’t have time to go into right now. We’ll save that discussion for a future learning adventure…

The Iterator Protocol

The iterator protocol is a fancy term meaning “how iterables actually work in Python”.

Let’s redefine iterables from Python’s perspective.

Iterables:

  1. Can be passed to the iter function to get an iterator for them.
  2. There is no 2. That’s really all that’s needed to be an iterable.

Iterators:

  1. Can be passed to the next function which gives their next item or raises StopIteration
  2. Return themselves when passed to the iter function.

The inverse of these statements should also hold true. Which means:

  1. Anything that can be passed to iter without an error is an iterable.
  2. Anything that can be passed to next without an error (except for StopIteration) is an iterator.
  3. Anything that returns itself when passed to iter is an iterator.

Looping with iterators

With what we’ve learned about iterables and iterators, we should now be able to recreate a for loop without actually using a for loop.

This while loop manually loops over some iterable, printing out each item as it goes:

1
2
3
4
5
6
7
8
9
def print_each(iterable):
    iterator = iter(iterable)
    while True:
        try:
            item = next(iterator)
        except StopIteration:
            break  # Iterator exhausted: stop the loop
        else:
            print(item)

We can call this function with any iterable and it will loop over it:

1
2
3
4
>>> print_each({1, 2, 3})
1
2
3

The above function is essentially the same as this one which uses a for loop:

1
2
3
def print_each(iterable):
    for item in iterable:
        print(item)

This for loop is automatically doing what we were doing manually: calling iter to get an iterator and then calling next over and over until a StopIteration exception is raised.

The iterator protocol is used by for loops, tuple unpacking, and all built-in functions that work on generic iterables. Using the iterator protocol (either manually or automatically) is the only universal way to loop over any iterable in Python.

For loops: more complex than they seem

We’re now ready to complete the very silly task our interviewer assigned to us. We’ll remove all for loops from our code by manually using iter and next to loop over iterables. What did we learn in exploring this task?

Everything you can loop over is an iterable. Looping over iterables works via getting an iterator from an iterable and then repeatedly asking the iterator for the next item.

The way iterators and iterables work is called the iterator protocol. List comprehensions, tuple unpacking, for loops, and all other forms of iteration rely on the iterator protocol.

I’ll explore iterators more in future articles. For now know that iterators are hiding behind the scenes of all iteration in Python.

December 28, 2016 07:00 PM


PyCharm

What’s New Webinar, Behind The Scenes

Earlier this month I did a What’s New in PyCharm 2016.3 webinar which toured the new features in 2016.3: Python 3.6, Django, web, VCS, and platform. Rather than a simple feature list, I took a different approach. We received some useful feedback, so I thought I’d write a recap and share some thoughts.

First, these webinars are really fun for me, both on the preparation and the webinar itself. But for full disclosure — it’s a surprising amount of work. Foremost, PyCharm itself is now so mature that the new features include some serious machinery. Branch coverage? If you don’t know it, you can’t cover it (pun intended). I had to spend a good bit of time learning more about coverage, profiling, and more.

I’ve recently been contributing to the arcade package for 2d Python games, so I used it as the testbed for exploring development stuff I should know, but don’t. Along the way, I came to a conclusion about webinars: I should show new features in the context of regular development, rather than a high-speed car chase through new functionality. This is something my boss Hadi Hariri has been pushing us developer advocates on: cover the why as much as the what.

I decided to show the Python features in the regular course of writing a 2d game. It meant, though, that my challenge greatly increased: I needed a sequential script that introduced disparate “What’s New” items without seeming contrived. My sequence went through a lot of throw-away-start-over cycles.

How did it go? It seemed to go well. It certainly felt more valuable — not to mention, more fun — to show “Faster VCS Log Searches” as part of regular open source project coding. The feedback seemed to agree: most of the input zeroed in on this aspect and said they liked it.

Here were some of the better suggestions on how to improve the webinar:

Our survey also asks for topics for future webinars. Some of the common themes:

Got other webinar ideas? Have something interesting to say and would like to do a webinar? Drop us a note in the comments, or send me an email, and let us know.

All in all, this new approach to doing What’s New webinars via actual development, instead of features-as-laundry-list, looks like a keeper. I’ll refine it to get better in the future. If you have a chance, watch the recording and let us know what you think.

December 28, 2016 04:38 PM


Ned Batchelder

D'oh: Coverage.py 4.3.1

Yesterday I released five months' of fixes as Coverage.py 4.3, and today I am releasing Coverage.py 4.3.1. This is not because releasing is fun, but because releasing is error-prone.

Two bad problems were very quickly reported by my legions of adoring fans, and they are now fixed. I'll sheepishly tell you that one of them was a UnicodeError in a bit of too-cute code in setup.py.

Perhaps I should have released a 4.3 beta. But my experience in the past is that betas do not get the kind of attention that final releases do. Partly this is just due to people's attention budget: lots of people won't install a beta. But it's also due to continuous integration servers. When a final release is out, hundreds if not thousands of CI servers will install it automatically as part of the next triggered build. They won't install pre-releases.

So there's a not-great choice to make: should I put out a beta, and hope that people try it and tell me what went wrong? Will enough people in enough disparate environments take that step to truly test the release?

Or should I skip that step, jump straight to a final release, and prepare instead to quickly fix whatever problems occur? I chose the latter course for 4.3. I guess I could use meta-feedback about which form of feedback I should pursue in the future...

December 28, 2016 04:37 PM


Real Python

Automating Django Deployments with Fabric and Ansible

Django + Ansible

In the last post, we covered all the steps required to successfully develop and deploy a Django app on a single server. In this tutorial we will automate the deployment process with Fabric (v1.12.0) and Ansible (v2.1.3) to address these issues:

  1. Scaling: When it comes to scaling a web app to handle thousands of daily requests, relying on a single server is not a good approach. Put simply, as the server approaches maximum CPU utilization, it can cause slow load times which can eventually lead to server failure. To overcome this, the app must be scaled to run on more than one server so that the servers can cumulatively handle the incoming concurrent requests.
  2. Redundancy: Deploying a web app manually to a new server means a lot of repeated work with more chances of human error. Automating the process is key.

Specifically, we will automate:

  1. Adding a new, non-root user
  2. Configuring the server
  3. Pulling the Django app code from a GitHub repo
  4. Installing the dependencies
  5. Daemonizing the app

Setup and Config

Start by spinning up a new Digital Ocean droplet, making sure to use the Fedora 25 image. Do not set up a pre-configured SSH key; we will be automating this process later via a Fabric script. Since the deployment process should be scalable, create a separate repository to house all the deployment scripts. Make a new project directory locally, and create and activate a virtualenv using Python 2.7x.

Why Python 2.7? Fabric does NOT support Python 3. Don’t worry: We’ll be using Python 3.5 when we provision the server.

1
2
3
4
$ mkdir automated-deployments
$ cd automated-deployments
$ virtualenv env
$ source env/bin/activate

Fabric Setup

Fabric is a tool used for automating routine shell commands over SSH, which we will be using to:

  1. Set up the SSH keys
  2. Harden user passwords
  3. Install Ansible dependencies
  4. Upgrade the server

Start by installing Fabric:

1
$ pip install fabric==1.12.0

Create a new folder called “prod”, and add a new file called fabfile.py to it to hold all of the Fabric scripts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# prod/fabfile.py


import os
from fabric.contrib.files import sed
from fabric.api import env, local, run
from fabric.api import env

# initialize the base directory
abs_dir_path = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__)))


# declare environment global variables

# root user
env.user = 'root'

# list of remote IP addresses
env.hosts = ['<remote-server-ip>']

# password for the remote server
env.password = '<remote-server-password>'

# full name of the user
env.full_name_user = '<your-name>'

# user group
env.user_group = 'deployers'

# user for the above group
env.user_name = 'deployer'

# ssh key path
env.ssh_keys_dir = os.path.join(abs_dir_path, 'ssh-keys')

Take note of the inline comments. Be sure to add you remote server’s IP address to the env.hosts variable. Update env.full_name_user as well. Hold off on updating env.password; we will get to that shortly. Look over all the env variables – they are completely customizable based on your system setup.

Set up the SSH keys

Add the following code to fabfile.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def start_provision():
    """
    Start server provisioning
    """
    # Create a new directory for a new remote server
    env.ssh_keys_name = os.path.join(
        env.ssh_keys_dir, env.host_string + '_prod_key')
    local('ssh-keygen -t rsa -b 2048 -f {0}'.format(env.ssh_keys_name))
    local('cp {0} {1}/authorized_keys'.format(
        env.ssh_keys_name + '.pub', env.ssh_keys_dir))
    # Prevent root SSHing into the remote server
    sed('/etc/ssh/sshd_config', '^UsePAM yes', 'UsePAM no')
    sed('/etc/ssh/sshd_config', '^PermitRootLogin yes',
        'PermitRootLogin no')
    sed('/etc/ssh/sshd_config', '^#PasswordAuthentication yes',
        'PasswordAuthentication no')

    install_ansible_dependencies()
    create_deployer_group()
    create_deployer_user()
    upload_keys()
    set_selinux_permissive()
    run('service sshd reload')
    upgrade_server()

This function acts as the entry point for the Fabric script. Besides triggering a series of functions, each explained in further steps, it explicitly-

Preventing SSH access for the root user is an optional step, but it is recommended as it ensures that no one has superuser rights.

Create a directory for your SSH keys in the project root:

1
2
3
├── prod
│   └── fabfile.py
└── ssh-keys

Harden user passwords

This step includes the addition of three different functions, each executed serially to configure SSH password hardening…

Create deployer group

1
2
3
4
5
6
7
8
9
def create_deployer_group():
    """
    Create a user group for all project developers
    """
    run('groupadd {}'.format(env.user_group))
    run('mv /etc/sudoers /etc/sudoers-backup')
    run('(cat /etc/sudoers-backup; echo "%' +
        env.user_group + ' ALL=(ALL) ALL") > /etc/sudoers')
    run('chmod 440 /etc/sudoers')

Here, we add a new group called deployers and grant sudo permissions to it so that users can carry out processes with root privileges.

Create user

1
2
3
4
5
6
7
8
9
10
11
12
def create_deployer_user():
    """
    Create a user for the user group
    """
    run('adduser -c "{}" -m -g {} {}'.format(
        env.full_name_user, env.user_group, env.user_name))
    run('passwd {}'.format(env.user_name))
    run('usermod -a -G {} {}'.format(env.user_group, env.user_name))
    run('mkdir /home/{}/.ssh'.format(env.user_name))
    run('chown -R {} /home/{}/.ssh'.format(env.user_name, env.user_name))
    run('chgrp -R {} /home/{}/.ssh'.format(
        env.user_group, env.user_name))

This function-

Upload SSH keys

1
2
3
4
5
6
7
8
9
10
11
def upload_keys():
    """
    Upload the SSH public/private keys to the remote server via scp
    """
    scp_command = 'scp {} {}/authorized_keys {}@{}:~/.ssh'.format(
        env.ssh_keys_name + '.pub',
        env.ssh_keys_dir,
        env.user_name,
        env.host_string
    )
    local(scp_command)

Here, we-

Install Ansible dependencies

Add the following function to install the dependency packages for Ansible:

1
2
3
4
5
6
def install_ansible_dependencies():
    """
    Install the python-dnf module so that Ansible
    can communicate with Fedora's Package Manager
    """
    run('dnf install -y python-dnf')

Keep in mind that this is specific to the Fedora Linux distro, as we will be using the DNF module for installing packages, but it could vary by distro.

Set SELinux to permissive mode

The next function sets SELinux to permissive mode. This is done to overcome any potential Nginx 502 Bad Gateway errors.

1
2
3
4
5
6
def set_selinux_permissive():
    """
    Set SELinux to Permissive/Disabled Mode
    """
    # for permissive
    run('sudo setenforce 0')

Again, this is specific to the Fedora Linux distro.

Upgrade the server

Finally, upgrade the server:

1
2
3
4
5
6
7
8
def upgrade_server():
    """
    Upgrade the server as a root user
    """
    run('dnf upgrade -y')
    # optional command (necessary for Fedora 25)
    run('dnf install -y python')
    run('reboot')

Sanity check

With that, we’re done with the Fabric script. Before running it, make sure you SSH into the server as root and change the password:

1
2
3
4
5
6
$ ssh root@<server-ip-address>
You are required to change your password immediately (root enforced)
Changing password for root.
(current) UNIX password:
New password:
Retype new password:

Be sure to update env.password with the new password. Exit the server and return to the local terminal, then execute Fabric:

1
$ fab -f ./prod/fabfile.py start_provision

If all went well, new SSH keys will be generated, and you will be asked to create a password (make sure to do this!):

1
2
3
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

A number of tasks will run. After the deployer user is created, you will be prompted to add a password for the user-

1
[104.236.66.172] out: Changing password for user deployer.

-which you will then have to enter when the SSH keys are uploaded:

1
deployer@104.236.66.172s password:

After this script exits successfully, you will NO longer be able to log into the remote server as a root user. Instead, you will only be able to use the non-root user deployer.

Try it out:

1
2
$ ssh root@<server-ip-address>
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

This is expected. Then, when you run-

1
$ ssh -i ./ssh-keys/104.236.66.172_prod_key deployer@104.236.66.172

-you should be able to log in just fine:

1
[deployer@fedora-512mb-nyc2-01 ~]$

Ansible Primer

Ansible is a configuration management and provisioning tool used to automate deployment tasks over SSH.

You can fire individual Ansible tasks against the app servers from your shell remotely and execute tasks on the go. Tasks can also be combined into Playbooks – a collection of multiple plays, where each play defines certain specific tasks that are required during the deployment process. They are executed against the app servers during the deployment process. Playbooks are written in YAML.

Playbooks

Playbooks consist of a modular architecture as follows:

  1. Hosts specify all the IP addresses or domain names of our remote servers that need to be orchestrated. Playbooks always run on a targeted group of hosts.
  2. Roles are divided into sub parts. Let’s look at some sample roles:
    • Tasks are a collection of multiple tasks that need to be carried out during the deployment process.
    • Handlers provide a way to trigger a set of operations when a module makes a change to the remote server (best thought of as hooks).
    • Templates, in this context, are generally used for specifying some module-related configuration files – like nginx.
  3. Variables are simply a list of key-value pairs where every key (a variable) is mapped to a value. Such variables can be used in the Playbooks as placeholders.

Sample Playbook

Now let’s look at a sample single-file Playbook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
---
# My Ansible playbook for configuring Nginx
- hosts: all

  vars:
    http_port: 80
    app_name: django_bootstrap

  tasks:
    - name: Install nginx
      dnf: name=nginx state=latest

    - name: Create nginx config file
      template: src=django_bootstrap.conf dest=/etc/nginx/conf.d/{{ app_name }}.conf
      become: yes
      notify:
        - restart nginx

  handlers:
    - name: Restart nginx
      service: name=nginx state=restarted enabled=yes
      become: yes

Here, we defined the-

Playbook Setup

Now let’s set up a Playbook for Django. Add a deploy.yml file to the “prod” directory:

1
2
3
4
5
6
7
8
##
# This playbook deploys the whole app stack
##
- name: apply common configuration to server
  hosts: all
  user: deployer
  roles:
    - common

The above snippet glues together the Ansible hosts, users, and roles.

Hosts

Add a hosts (plain text format) file to the “prod” directory and list the servers under their respective role names. We are provisioning a single server here:

1
2
[common]
<server-ip-address>

In the above snippet, common refers to the role name. Under the roles we have a list of IP addresses that need to be configured. Make sure to add your remote server’s IP address in place of <server-ip-address>.

Variables

Now we define the variables that will be used by the roles. Add a new folder inside “prod” called “group_vars”, then create a new file called all (plain text format) within that folder. Here, specify the following variables to start with:

1
2
3
4
5
6
7
8
9
# App Name
app_name: django_bootstrap

# Deployer User and Groups
deployer_user: deployer
deployer_group: deployers

# SSH Keys Directory
ssh_dir: <path-to-your-ssh-keys>

Make sure to update <path-to-your-ssh-keys>. To get the correct path, within the project root, run:

1
2
3
$ cd ssh-keys
$ pwd
/Users/michael.herman/repos/realpython/automated-deployments/ssh-keys

With these files in place, we are now ready to coordinate our deployment process with all the roles that need be carried out on the server.

Playbook Roles

Again, Playbooks are simply a collection of different plays, and all these plays are run under specific roles. Create a new directory called “roles” within “prod”.

Did you catch the name of the role in the deploy.yml file?

Then within the “roles” directory add a new directory called “common” – the role. Roles consists of “tasks”, “handlers”, and “templates”. Add a new directory for each.

Once done your file structure should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
├── prod
│   ├── deploy.yml
│   ├── fabfile.py
│   ├── group_vars
│   │   └── all
│   ├── hosts
│   └── roles
│       └── common
│           ├── handlers
│           ├── tasks
│           └── templates
└── ssh-keys
    ├── 104.236.66.172_prod_key
    ├── 104.236.66.172_prod_key.pub
    └── authorized_keys

All the plays are defined in a “tasks” directory, starting with a main.yml file. This file serves as the entry point for all Playbook tasks. It’s simply a list of multiple YAML files that need to be executed in order.

Create that file now within the “tasks” directory, then add the following to it:

1
2
3
4
5
6
7
8
9
10
11
12
##
# Configure the server for the Django app
##
- include: 01_server.yml
- include: 02_git.yml
- include: 03_postgres.yml
- include: 04_dependencies.yml
- include: 05_migrations.yml
- include: 06_nginx.yml
- include: 07_gunicorn.yml
- include: 08_systemd.yml
# - include: 09_fix-502.yml

Now, let’s create each task. Be sure to add a new file for each task to the “tasks” directory and add the accompanying code to each file. If you get lost, refer to the repo.

01_server.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
##
# Update the DNF package cache and install packages as a root user
##
- name: Install required packages
  dnf: name={{item}} state=latest
  become: yes
  with_items:
    - vim
    - fail2ban
    - python3-devel
    - python-virtualenv
    - python3-virtualenv
    - python-devel
    - gcc
    - libselinux-python
    - redhat-rpm-config
    - libtiff-devel
    - libjpeg-devel
    - libzip-devel
    - freetype-devel
    - lcms2-devel
    - libwebp-devel
    - tcl-devel
    - tk-devel
    - policycoreutils-devel

Here, we list all the system packages that need to be installed.

02_git.yml

1
2
3
4
5
6
7
8
9
10
##
# Clone and pull the repo
##
- name: Set up git configuration
  dnf: name=git state=latest
  become: yes

- name: Clone or pull the latest code
  git: repo={{ code_repository_url }}
        dest={{ app_dir }}

Add the following variables to the group_vars/all file:

1
2
3
4
5
# Github Code's Repo URL
code_repository_url: https://github.com/realpython/django-bootstrap

# App Directory
app_dir: /home/{{ deployer_user }}/{{app_name}}

Make sure to fork then clone the django-bootstrap repo, then update the code_repository_url variable to the URL of your fork.

03_postgres.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
##
# Set up and configure postgres
##
- name: Install and configure db
  dnf: name={{item}} state=latest
  become: yes
  with_items:
    - postgresql-server
    - postgresql-contrib
    - postgresql-devel
    - python-psycopg2

- name: Run initdb command
  raw: postgresql-setup initdb
  become: yes

- name: Start and enable postgres
  service: name=postgresql enabled=yes state=started
  become: yes

- name: Create database
  postgresql_db: name={{ app_name }}
  become_user: postgres
  become: yes

- name: Configure a new postgresql user
  postgresql_user: db={{ app_name }}
                                name={{ db_user }}
                                password={{ db_password }}
                                priv=ALL
                                role_attr_flags=NOSUPERUSER
  become: yes
  become_user: postgres
  notify:
    - restart postgres

Update group_vars/all with the database configuration needed for the playbook:

1
2
3
4
5
# DB Configuration
db_url: postgresql://{{deployer_user}}:{{db_password}}@localhost/{{app_name}}
db_password: thisissomeseucrepassword
db_name: "{{ app_name }}"
db_user: "{{ deployer_user }}"

Update the db_password variable with a secure password.

Did you notice that we restart the postgres service within the main.yml file in order to apply the changes after the database is configured? This is our first handler. Create a new file called main.yml in the “handlers” folder, then add the following:

1
2
3
- name: restart postgres
  service: name=postgresql state=restarted
  become: yes

04_dependencies.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
##
# Set up all the dependencies in a virtualenv required by the Django app
##
- name: Create a virtualenv directory
  file: path={{ venv_dir }} state=directory

- name: Install dependencies
  pip:    requirements={{ app_dir }}/requirements.txt
          virtualenv={{ venv_dir }}
          virtualenv_python=python3.5

- name: Create the .env file for running ad-hoc python commands in our virtualenv
  template: src=env.j2 dest={{ app_dir }}/.env
  become: yes

Update group_vars/all like so:

1
2
3
# Application Dependencies Setup
venv_dir: '/home/{{ deployer_user }}/envs/{{ app_name }}'
venv_python: '{{ venv_dir }}/bin/python3.5'

Add a template called env.j2 to the “templates” folder, and add the following environment variables:

1
2
3
4
5
#!/bin/bash
export DEBUG="True"
export DATABASE_URL="postgresql://deployer:thisissomeseucrepassword@localhost/django_bootstrap"
export DJANGO_SECRET_KEY="changeme"
export DJANGO_SETTINGS_MODULE="config.settings.production"

Be very careful with the environment variables and their values in env.j2 since these are used to get the Django Project up and running.

05_migrations.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
##
# Run db migrations and get all static files
##
- name: Make migrations
  shell: ". {{ app_dir }}/.env; {{ venv_python }} {{ app_dir }}/manage.py makemigrations "
  become: yes

- name: Migrate database
  django_manage: app_path={{ app_dir }}
                                 command=migrate
                                 virtualenv={{ venv_dir }}

- name: Get all static files
  django_manage: app_path={{ app_dir }}
                                 command=collectstatic
                                 virtualenv={{ venv_dir }}
  become: yes

06_nginx.yml

1
2
3
4
5
6
7
8
9
10
11
12
##
# Configure nginx web server
##
- name: Set up nginx config
  dnf: name=nginx state=latest
  become: yes

- name: Write nginx conf file
  template: src=django_bootstrap.conf dest=/etc/nginx/conf.d/{{ app_name }}.conf
  become: yes
  notify:
    - restart nginx

Add the following variable to group_vars/all:

1
2
3
# Remote Server Details
server_ip: <remote-server-ip>
wsgi_server_port: 8000

Don’t forget to update <remote-server-ip>. Then add the handler to handlers/main.yml:

1
2
3
- name: restart nginx
  service: name=nginx state=restarted enabled=yes
  become: yes

Then we need to add the django_bootstrap.conf template. Create that file within the “templates” directory, then add the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
upstream app_server {
    server 127.0.0.1:{{ wsgi_server_port }} fail_timeout=0;
}

server {
    listen 80;
    server_name {{ server_ip }};
    access_log /var/log/nginx/{{ app_name }}-access.log;
    error_log /var/log/nginx/{{ app_name }}-error.log info;

    keepalive_timeout 5;

    # path for staticfiles
    location /static {
            autoindex on;
            alias {{ app_dir }}/staticfiles/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://app_server;
            break;
        }
    }
}

07_gunicorn.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
##
# Set up Gunicorn and configure systemd to execute gunicorn_start script
##
- name: Create a deploy directory
  file: path={{ deploy_dir }} state=directory
  become: yes

- name: Create the gunicorn_start script for running our app from systemd service
  template: src=gunicorn_start
                    dest={{ deploy_dir }}/gunicorn_start
  become: yes

- name: Make the gunicorn_start script executable
  raw: cd {{ deploy_dir }}; chmod +x gunicorn_start
  become: yes

Add more variables to groups_vars/all:

1
2
3
4
5
6
7
8
# Deploy Dir in App Directory
deploy_dir: '{{ app_dir }}/deploy'

# WSGI Vars
django_wsgi_module: config.wsgi
django_settings_module: config.settings.production
django_secret_key: 'changeme'
database_url: '{{ db_url }}'

Add the gunicorn_start template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/bash

### Define script variables

# Name of the app
NAME='{{ app_name }}'
# Path to virtualenv
VIRTUALENV='{{ venv_dir }}'
# Django Project Directory
DJANGODIR='{{ app_dir }}'
# The user to run as
USER={{ deployer_user }}
# The group to run as
GROUP={{deployer_group }}
# Number of worker processes Gunicorn should spawn
NUM_WORKERS=3
# Settings file that Gunicorn should use
DJANGO_SETTINGS_MODULE={{django_settings_module}}
# WSGI module name
DJANGO_WSGI_MODULE={{ django_wsgi_module }}


### Activate virtualenv and create environment variables

echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $VIRTUALENV
source bin/activate
cd $DJANGODIR
# Defining the Environment Variables
export DJANGO_SECRET_KEY='{{ django_secret_key }}'
export DATABASE_URL='{{ db_url }}'
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH


### Start Gunicorn

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
        --name $NAME \
        --workers $NUM_WORKERS \
        --user=$USER --group=$GROUP \
        --log-level=debug \
        --bind=127.0.0.1:8000

08_systemd.yml

1
2
3
4
5
6
7
8
9
10
##
# Set up systemd for executing gunicorn_start script
##
- name: write a systemd service file
  template: src=django-bootstrap.service
                    dest=/etc/systemd/system
  become: yes
  notify:
    - restart app
    - restart nginx

Add the template – django-bootstrap.service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/sh

[Unit]
Description=Django Web App
After=network.target

[Service]
PIDFile=/var/run/djangoBootstrap.pid
User={{ deployer_user }}
Group={{ deployer_group }}
ExecStart=/bin/sh {{ deploy_dir }}/gunicorn_start
Restart=on-abort

[Install]
WantedBy=multi-user.target

Add the following to the handlers:

1
2
3
- name: restart app
  service: name=django-bootstrap state=restarted enabled=yes
  become: yes

09_fix-502.yml

1
2
3
4
5
6
##
# Fix the 502 nginx error post deployment
#
- name: Fix nginx 502 error
  raw: cd ~; cat /var/log/audit/audit.log | grep nginx | grep denied | audit2allow -M mynginx; semodule -i mynginx.pp
  become: yes

Sanity Check (final)

With the virtualenv activated, install Ansible locally:

1
$ pip install ansible==2.1.3

Create a new file called deploy_prod.sh in the project root to run the playbook, making sure to update <server-ip>:

1
2
3
#!/bin/bash

ansible-playbook ./prod/deploy.yml --private-key=./ssh_keys<server-ip>_prod_key -K -u deployer -i ./prod/hosts -vvv

Then run following command to execute the playbook:

1
$ sh deploy_prod.sh

If any errors occur, consult the terminal for info on how to correct them. Once fixed, execute the deploy script again. When the script is done visit the server’s IP Address to verify your Django web app is live and running!

live Django app

Make sure to uncomment this line in prod/roles/common/tasks/main.yml if you see the 502 error, which indicates that there is a problem with communication between nginx and Gunicorn:

1
# - include: 09_fix-502.yml

Then execute the playbook again.

If you execute the playbook more than once, make sure to comment out the Run initdb command found in 03_postgres.yml since it needs run only once. Otherwise, it will throw errors when trying to reinitialize the DB server.

Conclusion

This post provides a basic understanding of how you can automate the configuring of a server with Fabric and Ansible. Ansible Playbooks are particularly powerful since you can automate almost any task on the server via a YAML file. Hopefully, you can now start writing your own Playbooks and even use them in your workplace to configure production-ready servers.

Please add questions and comments below. The full code can be found in the automated-deployments repository.

December 28, 2016 02:18 PM