1. Django Notes: read values from settings in a safe way

    Working on Django projects I find very often that many developers access the values that are defined in settings in this way

    ``` {.lang:python .decode:true} from django.conf import settings

    my_value = settings.MY_SETTING

    What happens if **MY\_SETTING** has not been defined in **settings.py**?
    The code will raise an error and crash, of course. How can we make the
    code more reliable? We could *try/except* the code block that tries to
    read the value and maybe set a value if we get an exception, but this
    would not be a clean way to do this job.
    
    A cleaner way to do it is to use **getattr** in this way:
    
    ``` {.lang:python .decode:true}
    from django.conf import settings
    
    my_value = getattr(settings, 'MY_SETTING', 'my-default-value')
    

    getattr will try to read MY_SETTING value from settings.py, if the value doesn't exist my_value will be assigned with my-default-value.

    read more

    comments

  2. How to write a custom Django Middleware

    To understand how a Django Middleware works we need to remember that the basic architecture of Django is composed by a request and a response. A middleware is something that stays in the middle. Let's give a look to the next diagram, taken from official Django documentation:

    middleware

    Important things to know

    There are four important things to know about middlewares:

    • You need to write a class that just inherit from object
    • The order where you place your middleware in settings.py is important: middlewares are processed from top to bottom during a request and from bottom to top during a response.
    • You don't need to implement all the available methods of a middleware. For example you can just implement process_request and process_template_response
    • If you implement process_request and you decide to return an HttpResponse, all the other middlewares, views etc... will be ignored and only your response will be returned

    Writing a middleware

    In my example I wanted to implement a feature that saves the time when a request is made and the time when a request has been processed, then calculates the time delta and exposes this value in the context so that is accessible from our templates. How to implement a similar feature using a middleware? Here is my example:

    from datetime import datetime
    
    
    class BenchmarkMiddleware(object):
        def process_request(self, request):
            request._request_time = datetime.now()
    
        def process_template_response(self, request, response):
            response_time = request._request_time - datetime.now()
            response.context_data['response_time'] = abs(response_time)
            return response
    

    Please don't care about how I calculated the time. I'm aware that there are better ways to do it, but I just wanted to keep it simple and show how to implement a simple middleware.

    If you want to see a complete example of a project that includes and uses this middleware, here you can find the complete source code: https://github.com/andreagrandi/benchmark-middleware-example

    References

    read more

    comments

  3. Using virtualenv to manage multiple Python/Django environments in the same machine

    Developing Python applications sometimes it's useful to be able to test the code with different environments, for example a particular version of Python or a specific Django version etc... Setting up many different virtual machines would be really too much work and even using a chroot environment is not what you need in some cases. Thanks to virtualenv is it possible to create a self contained Python environment with all the specific libraries you may need. Using virtualenv is very easy:

    • Creating the virtual environment: virtualenv myenv --no-site-packages
    • Entering the virtual environment: source myenv/bin/activate
    • Deactivating the virtual environment: deactivate

    That's it! Once you're inside the virtual environment you will be using the Python libraries inside it. I suggest you to install all the Python libraries you need using pip.

    read more

    comments

« Page 2 / 2

social