Scrapy: Scraping each type of Item to it’s own collection in mongodb

I am using Scrapy and I have two different Items. I want to store entries for each specific item to it’s own mongo collection. For example, let’s assume this is what I have in the file:

I want to store Student items to student collection and Course items to course collection. How do we do that?

If you have used Scrapy before, you already know that for storing data, we use Pipelines. Here’s our own MongoPipeline that stores items to their own collection:

So this is what’s happening:

  • We’re using PyMongo as the mongodb driver
  • I have the MongoDB related configurations to settings. I am getting them and constructing a mongodb client. I am also selecting the database based on a setting
  • In the process_item function, we are getting the type of the item and lowering it’s name. This type name would serve as the mongodb collection name for us.
  • We are inserting the item. We’re calling dict() on the item to get a dictionary representation which we can directly save using PyMongo.

That’s it. Now if you run your spiders, items of each type will go to it’s own collection on mongodb.

Fixing fatal error: ‘openssl/aes.h’ file not found on OS X

OS X recently started using their own library instead of OpenSSL. So new installations for anything that depends on OpenSSL might fail. If you already have OpenSSL installed on your system, for example using Homebrew, you just need to point to the library while compiling your program.

For example, if you’re trying to install the popular cryptography package from PyPI, you can do these:

The above mentioned package is a common dependency of many other packages, for example Scrapy. So if you encounter an issue like this, try installing that single dependency first and then the dependent package. In this case, first use the above command to install the cryptography package and later install Scrapy.

Python asyncio: Future, Task and the Event Loop

Event Loop

On any platform, when we want to do something asynchronously, it usually involves an event loop. An event loop is a loop that can register tasks to be executed, execute them, delay or even cancel them and handle different events related to these operations. Generally, we schedule multiple async functions to the event loop. The loop runs one function, while that function waits for IO, it pauses it and runs another. When the first function completes IO, it is resumed. Thus two or more functions can co-operatively run together. This the main goal of an event loop.

The event loop can also pass resource intensive functions to a thread pool for processing. The internals of the event loop is quite complex and we don’t need to worry much about it right away. We just need to remember that the event loop is the mechanism through which we can schedule our async functions and get them executed.

Futures / Tasks

If you are into Javascript too, you probably know about Promise. In Python we have similar concepts – Future/Task. A Future is an object that is supposed to have a result in the future. A Task is a subclass of Future that wraps a coroutine. When the coroutine finishes, the result of the Task is realized.


We discussed Coroutines in our last blog post. It’s a way of pausing a function and returning a series of values periodically. A coroutine can pause the execution of the function by using the yield yield from or await (python 3.5+) keywords in an expression. The function is paused until the yield statement actually gets a value.

Fitting Event Loop and Future/Task Together

It’s simple. We need an event loop and we need to register our future/task objects with the event loop. The loop will schedule and run them. We can add callbacks to our future/task objects so that we can be notified when a future has it’s results.

Very often we choose to use coroutines for our work. We wrap a coroutine in Future and get a Task object. When a coroutine yields, it is paused. When it has a value, it is resumed. When it returns, the Task has completed and gets a value. Any associated callback is run. If the coroutine raises an exception, the Task fails and not resolved.

So let’s move ahead and see example codes.

As you can see already:

  • @asyncio.coroutine declares it as a coroutine
  • loop.create_task(slow_operation()) creates a task from the coroutine returned by slow_operation()
  • task.add_done_callback(got_result) adds a callback to our task
  • loop.run_until_complete(task) runs the event loop until the task is realized. As soon as it has value, the loop terminates

The run_until_complete function is a nice way to manage the loop. Of course we could do this:

Here we make the loop run forever and from our callback, we explicitly shut it down when the future has resolved.

Python: Generators, Coroutines, Native Coroutines and async/await

NOTE: This post discusses features which were mostly introduced with Python 3.4. And the native coroutines and async/await syntax came in Python 3.5. So I recommend you to use Python 3.5 to try the codes, if you don’t know how to update python, make sure to visit this website.


Generators are functions that generates values. A function usually returns a value and then the underlying scope is destroyed. When we call again, the function is started from scratch. It’s one time execution. But a generator function can yield a value and pause the execution of the function. The control is returned to the calling scope. Then we can again resume the execution when we want and get another value (if any). Let’s look at this example:

Please notice, a generator function doesn’t directly return any values but when we call it, we get a generator object which is like an iterable. So we can call next() on a generator object to iterate over the values. Or run a for loop.

So how’s generators useful? Let’s say your boss has asked you to write a function to generate a sequence of number up to 100 (a super secret simplified version of range()). You wrote it. You took an empty list and kept adding the numbers to it and then returned the list with the numbers. But then the requirement changes and it needs to generate up to 10 million numbers. If you store these numbers in a list, you will soon run out of memory. In such situations generators come into aid. You can generate these numbers without storing them in a list. Just like this:

We didn’t dare run after the number hit 9. But if you try it on console, you will see how it keeps generating numbers one after one. And it does so by pausing the execution and resuming – back and forth into the function context.

Summary: A generator function is a function that can pause execution and generate multiple values instead of just returning one value. When called, it gives us a generator object which acts like an iterable. We can use (iterate over) the iterable to get the values one by one.


In the last section we have seen that using generators we can pull data from a function context (and pause execution). What if we wanted to push some data too? That’s where coroutines comes into play. The yield keyword we use to pull values can also be used as an expression (on the right side of “=”) inside the function. We can use the send() method on a generator object to pass values back into the function. This is called “generator based coroutines”. Here’s an example:

OK, so what’s happening here? We first take the value as usual – using the next() function. This comes to yield "Hello" and we get “Hello”. Then we send in a value using the send() method. It resumes the function and assigns the value we send to hello and moves on up to the next line and executes the statement. So we get “World” as a return value of the send() method.

When we’re using generator based coroutines, by the terms “generator” and “coroutine” we usually mean the same thing. Though they are not exactly the same thing, it is very often used interchangeably in such cases. However, with Python 3.5 we have async/await keywords along with native coroutines. We will discuss those later in this post.

Async I/O and the asyncio module

From Python 3.4, we have the new asyncio module which provides nice APIs for general async programming. We can use coroutines with the asyncio module to easily do async io. Here’s an example from the official docs:

The code is pretty self explanatory. We create a coroutine display_date(num, loop) which takes an identifier (number) and an event loop and continues to print the current time. Then it used the yield from keyword to await results from asyncio.sleep() function call. The function is a coroutine which completes after a given seconds. So we pass random seconds to it. Then we use asyncio.ensure_future() to schedule the execution of the coroutine in the default event loop. Then we ask the loop to keep running.

If we see the output, we shall see that the two coroutines are executed concurrently. When we use yield from, the event loop knows that it’s going to be busy for a while so it pauses execution of the coroutine and runs another. Thus two coroutines run concurrently (but not in parallel since the event loop is single threaded).

Just so you know, yield from is a nice syntactic sugar for for x in asyncio.sleep(random.randint(0, 5)): yield x making async codes cleaner.

Native Coroutines and async/await

Remember, we’re still using generator based coroutines? In Python 3.5 we got the new native coroutines which uses the async/await syntax. The previous function can be written this way:

Take a look at the highlighted lines. We must define a native coroutine with the async keyword before the def keyword. Inside a native coroutine, we use the await keyword instead of yield from.

Native vs Generator Based Coroutines: Interoperability

There’s no functional differences between the Native and Generator based coroutines except the differences in the syntax. It is not permitted to mix the syntaxes. So we can not use await inside a generator based coroutine or yield/yield from inside a native coroutine.

Despite the differences, we can interoperate between those. We just need to add @types.coroutine decorator to old generator based ones. Then we can use one from inside the other type. That is we can await from generator based coroutines inside a native coroutine and yield from native coroutines when we are inside generator based coroutines. Here’s an example:

Django REST Framework: Custom Exception Handler

While using DRF, do you need to handle the exceptions yourselves? Here’s how to do it. First, we need to create an exception handler function like this:

In the exception handler, we get exc which is the exception raised and the context contains the context of the request. However, we didn’t do anything fancy with these. We just called the default exception handler and joined the errors in a flat string. We also added the exception to our response.

Now, we need to tell DRF to call our custom exception handler when it comes across an exception. That is easy:

Open up your and look for the REST_FRAMEWORK dictionary. Here you need to add the exception handler to the EXCEPTION_HANDLER key. So it should look something like this:

Django: Handling broken migrations

Often for one reason or another, migrations don’t apply properly and we have to fix them manually. If there’s a faulty migration that throws errors when run, we first have to identify what went wrong. Very often on MySQL, we see half applied migrations (probably because MySQL doesn’t have transactions?). In this case we need to do the other half ourselves.

We can easily connect to the database prompt by typing the dbshell command.

The command opens the shell for the respective database engine using the configurations provided in the settings file. That is you don’t have to remember the username or password for the database connection.

Now you have to fix the issues and then you can try running the migration again. In case it fails again, you should alter the database to match the state the migration would have created. For example, if the migration was supposed to alter a column from store_type to store_type_id (from a char field to foreign keys), you have to manually run the query, something like:

Then you have to fake the migration. When a migration is run, Django stores the name of the migration in a table. It helps track which migrations have already run and which needs to be run. When we fake a migration, Django stores the faked migration name in that table without actually running it. If we don’t do this, when we next run migrate command, Django will try to run this migration again and fail.

This is how we fake it:

You can also specify one particular migration when you have multiple migrations running.

Python: Writing custom log handler and formatter

Log Handlers dictate how the log entries are handled. For example FileHandler would allow us to pipe our logs to a file. HTTP Handler makes it possible to send the logs over HTTP to a remote server. We can write our own log handlers if we need to customize the way our logs are processed. Writing a custom handler is pretty simple. We have to subclass it from logging.Handler class and must define the emit method. This method is called with each log record so we can process it.

Here’s an exmaple of a custom log handler which POSTs the logs to a remote server using the popular requests library.

Now we have our custom handler that will post the logs to another server. What if we want to send the message in a specific format? We write our custom formatter. A formatter has a format method which gets the record. We can take the record and return a message formatted according our need. Here’s an example for logstash format:

So we have got ourselves a custom log handler and a formatter. But how do we use them? Here’s a short code snippet:

Django REST Framework: Displaying full URL for ImageField or FileField

If you have any ImageField or FileField in your model, you can easily display the full URL (including the hostname/domain) for the file/image. Django REST Framework’s model serializers would do it for you. However, to get the hostname/domain name, the serializer needs a “request context” so it can infer the necessary parts and build a full url.

So if you’re manually invoking a serializer, please pass a request context like this:

If you use ModelViewSet, DRF will automatically pass the request context while initializing the serializer. So in that case you don’t need to do anything. You need to pass the context only when you’re manually creating a serializer instance.

Django REST Framework: Dynamic Fields in Serializers

Here’s the use case, I need to add some extra fields to my serializer depending on a request. For example, if the query string contains “extra=true”, then add the extra fields. Luckily, serializers get a “context” argument when they are initialized. We can use this to customize our serializers as needed.

The fields defined on a serializer are available in a instance variable named “fields”. So we can add/delete/edit fields from it. Let’s see an example:

Please note, here we have used another serializer (UserLocationSerializer) from inside our main serializer. The second one is being initialized by us. So it would not get the context. If we need to do something down there as well, then we need to pass it ourselves.

Now the second serializer will get the request too and we can use the same way to customize it!

Docker Workflow of Python Workers

If you’re planning to use with Python, their new docker workflow is pretty cool. In this blog post, I shall walk you through the setup.

Setup Docker

The first step would be to install Docker. Here’s a pretty nice installation guide from Digital Ocean: 🙂

If you’re not using Ubuntu (eg. Windows or OS X), you might consider using Ubuntu in a virtualbox. I usually use Vagrant to do that.

If you’re using another Linux distro, please go through the official docker docs, I’m sure it’s quite easy 🙂

Once the setup is complete, run the following command to confirm that Docker has successfully installed and currently running:

You would see something like this:

Installing PIP Dependencies

Now it’s the time to install the dependencies for our projects. Change directory to our project root and use the requirements.txt file to install the packages. Please note we shall install them into a separate directory than the usual system path.

Here we have asked docker to run a new container based on the “iron/images:python-2.7” image. Inside the container we run the pip command. The “-t” flag would install packages in a separate target directory.

Since this is the first time we’re using this image, docker will need to pull it first. Then it will continue to install the dependencies. Once it’s done, feel free to examine the packages directory.

Locally Running Workers

The command is similar, except we have the packages installed in “packages” directory. So we need to set the PYTHONPATH env variable.

That would work 🙂

Bundling workers

To bundle the workers, we need to first zip everything:

You must remember to zip everything in, including the packages directory.

Now, we can start using the iron cli. In case you don’t have it installed, it’s easy:

Now let’s upload the zip file:

I think the command is pretty self explanatory. However, for the env argument, you need a file named “iron.json” which would contain the project id and tokens for your different environments. Here’s a sample:

Also note, we’re using PYTHONPATH=”packages” before invoking Python.

If everything goes right, your worker will be packaged and uploaded. Try running it to see how it goes.