Skip to main content

Create an integer within a range.

Project description

Construct integer within a given range to prevent DoS attacks.

Pulling data from the Internet and feeding it to Python’s builtin int function exposes you to a potential DoS attack. Python supports arbitrary precision integers. Unlike other languages like C++, Java or even Javascript which will eventually overflow, Python can represent any number you have the memory to store. For instance, in the following code:

s = '9' * 1000000  # Generate a string with one million 9s
i = int(s)

Python keeps on going and will stuff 10^1000000 - 1 into i after 7 seconds of CPU work and 400kb of RAM. 7 seconds during which your gevent based web server cannot perform a context switch and service other requests. A single machine running a few hundred greenlets on a cable modem would be enough to cripple a web server with APIs that accepts integers. is a drop-in replacement for int to help parse untrusted data coming from the Internet. You use it like this:

import safeint

def my_controller():
    foo =

By default will raise a ValueError if your input string is too long. The default is 10 digits, but you can raise or lower that as your application requires with the keyword parameter digits. So for example,, digits=2) limits you to numbers in the range -9 to 99 inclusive. also supports a few extra parameters and features beyond what int normally supports. If you pass it None or an empty string it returns None, saving you from the hassle of writing code that looks like this:

if is None:
    foo = None
    foo = int(

Instead you can write this:

import safeint

foo = also has some syntactic sugar to save time when enforcing bounds. Instead of writing this:

import safeint

foo =
if foo > high:
    raise ValueError(...)
elif foo < low:
    raise ValueError(...)

you can just write this:

import safeint

foo =, low=low, high=high)


Bug reports and pull requests welcome!


Peloton for supporting open source!

Dan Sokolsky and Adam DePrince for implementing this solution!

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

safeint-0.0.3.tar.gz (3.8 kB view hashes)

Uploaded source

Built Distribution

safeint-0.0.3-py2.py3-none-any.whl (4.9 kB view hashes)

Uploaded py2 py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page