StructureMap using named instance during initialize in scanned assemblies in ASP.Net MVC4

I work on a project which use StructureMap as dependency injection manager in a C# Asp.Net MVC4 context.

Basically the structure of the project is a library project (we’ll call it Assembly 1) and a Web project (we’ll call it Assembly 2) which references the library project.

At some point I needed to register named instances in structuremap in the library project Assembly 1 and then use them in the web project Assembly 2.

If you’re in hurry here the working answer in order to have everything working without explanations:


//Assembly 1
public class MyRegistry : Registry
{
    private MyRegistry()
    {
        For().Add(new MyStuff()).Named("myInstance");           
    }
    public static void Setup()
    {
        MyRegistry initializer = new MyRegistry();
        ObjectFactory.Initialize(x =>
        {
            x.AddRegistry(initializer);
            x.Scan(y =>
            {
                y.AssembliesFromApplicationBaseDirectory();
                y.LookForRegistries();
            });

        });
    }       
}

//Assembly 2
public class MySubRegistry : Registry
{
    public Initializer()
    {
        //For().Use().Ctor("config").Is(ObjectFactory.GetNamedInstance("myInstance"));//Doesn't work
        For().Use().Ctor("config").Is(x => x.ConstructedBy(y => ObjectFactory.GetNamedInstance("myInstance")));//This work
    }       
}

Long(er) version

So you want to register named instances in the main registry, you want to use them in some other registries in a sub-assembly and you want to register other stuff in your sub-registry.

An approach could be to scan other assemblies after the container is initialized (example below).


//Assembly 1
public class MyRegistry : Registry
{
    private MyRegistry()
    {
        For().Add(new MyStuff()).Named("myInstance");           
    }
    public static void Setup()
    {
        MyRegistry initializer = new MyRegistry();
        ObjectFactory.Initialize(x =>
        {
            x.AddRegistry(initializer);
        });
        initializer.Scan(y =>
        {
            y.AssembliesFromApplicationBaseDirectory();
            y.LookForRegistries();
        });
    }       
}

This might works for you to use named instances elsewhere in your project but, from a bad experience I had, if after you add some instances (named or not) of some interfaces in a scanned registry they will not be registered.


//Assembly 2
public class MySubRegistry : Registry
{
    public Initializer()
    {
        //With the scan made outside the initialize the named instance can be retrieved as structuremap is already initialized
        For().Use().Ctor("config").Is(ObjectFactory.GetNamedInstance("myInstance"));
        //But this one will never be registered as structure is already initialized
        For().Add(new MyObject());
    }       
}

Thus the only way in order to have everything works is (as described at the top of this article) to scan other registries at structuremap initialisation time AND in scanned registries to use delegate to access things registered in the main registry.


//This
For().Use().Ctor("config").Is(x => x.ConstructedBy(y => ObjectFactory.GetNamedInstance("myInstance")));
//Instead of
For().Use().Ctor("config").Is(ObjectFactory.GetNamedInstance("myInstance"));

Indeed the delegate here will be lazy evaluated. So when it will be evaluated everything would have been registered.
This is really tricky, it worked for me and I hope it will work for you as well.

If you have question or something to fix in the code of this article feel free to comment 🙂

Posted in asp.net, C# | Tagged , , , | Leave a comment

Using Gmail smtp through VPN (on Synology)

I use my Synology NAS with a VPN which is always connected. In response to some events I wanted to send custom email notifications (btw if you are interested in this part I recommend this excellent article Send Custom (email) Notifications from scripts running on a Synology).

I use the Gmail’s smtp server with one of my email.
In general there are several things you need to do to make it work:

  1. Ask your vpn provider to whitelist the ip of the gmail smtp you resolve once connected (to get the ip you resolve from vpn: ssh/telnet to your nas with root user and ping -4 smtp.gmail.com). Indeed most providers block smtp in order to prevent spams. My provider (privateinternetaccess) has whitelisted the ip in 24h
  2. Fill the ip in the notification panel (as on the picture)
  3. Send a test mail
  4. If you receive a mail from Google saying your account might have been hacked log on gmail, then go to https://accounts.google.com/DisplayUnlockCaptcha and send a test mail again

Synology notification panel

It now should works! Hope it has helped 🙂

Posted in tutorial, vpn | Tagged , , , | Comments Off on Using Gmail smtp through VPN (on Synology)

Generate ASP classes

I wrote a simple python script in order to generate some ASP (classic not dot net) classes:
Here it is as it:

# -*- coding: windows-1252 -*-
# @author: Raphaël Beck
# ex: >> python generateAspClass.py -n Country -f code -f name -f id > Country.asp

import os
import string
import re
from collections import defaultdict
from optparse import OptionParser
from datetime import datetime

name = None


baseStruc = """<%%
' -----------------------------------------------------------------------------
' @File   : /%(name)s.asp
' @Desc   : %(name)s
' @Create : %(date)s
' @Author : R.BECK
' -----------------------------------------------------------------------------
class %(name)s

%(fields)s
    
    ' Constructor
    Private Sub Class_Initialize()
%(init_fields)s
    end sub
    
    ' Destructor    
    'Private Sub Class_Terminate()    
    'end sub
    
    'Getters
    %(getters)s
    
    ' Setters
    %(setters)s

end class
%%>
"""

field_format = "\tprivate %(private_field_name)s\n"

getter_format = """
    Public property get %(field_name)s    
        %(field_name)s = %(private_field_name)s
    End Property
"""

setter_format = """
    Public property let %(field_name)s(p_%(field_name)s)  
        %(private_field_name)s = p_%(field_name)s
    End Property
"""

init_format = """\t\t%(private_field_name)s = 0"""

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-f", "--fields",
                      action="append", dest="fields", default=[],
                      help="Class' fields")

    parser.add_option("-n", "--name", dest="name", 
                      help="Class' name")
                      
    (options, args) = parser.parse_args()
    
    if not options.name:
        print "The name of the class is mandatory"
        exit(-1)
    name = options.name
    
    private_fields = []
    getters = []
    setters = []
    init_fields = []

    for field_name in set(options.fields):
        field_dict = {"field_name": field_name, "private_field_name": "m_%s" % field_name}
        private_fields.append(field_format % field_dict)
        getters.append(getter_format % field_dict)
        setters.append(setter_format % field_dict)
        init_fields.append(init_format % field_dict)
    
    date = datetime.now()
    dateStr = "%s/%s/%s" % (date.day, date.month, date.year)
    
    print baseStruc % {
        "name": name,
        "fields": "".join(private_fields),
        "getters": "\n".join(getters),
        "setters": "\n".join(setters),
        "date": dateStr,
        "init_fields": "\n".join(init_fields),
    }
    
    
    
    
    
    

Usage:

python generateAspClass.py -n Country -f code -f name -f id > Country.asp

You can use the code, modify it (I’ll be happy to see your modifications, in case I have forgotten something) and distribute it (it’ll be great if you link to this site :D).

Posted in asp, python | Tagged , | Leave a comment

Working with IE7, jQuery and Forms

If you just want the solution skip the context

Context

For my work I had to make a register form from where the user had to send three separate files.

The non-javascript version is a simple form with three input file, like the following:

<form enctype="multipart/form-data" id="formMain">
  <input type="file" name="file1" />
  <input type="file" name="file2" />
  <input type="file" name="file3" />
  <button type="submit">Submit</button>
</form>

However the javascript version (meaning javascript enabled in the browser) had to have an “add” button next to each input so the chosen solution was to change at the loading time the structure of the form for this one:

<form enctype="multipart/form-data" target="iframe1" id="form1">
 <input type="file" name="file1"/>
 <button type="submit">Add</button>
</form>
<iframe class="hidden" onLoad="iframeLoaded(this);" id="iframe1" name="iframe1"/>

The purpose of the iframe is to upload the file without reloading the page. The user select a file, hit the add button and then the form will be submitted to the iframe thanks to the “target” attribute. When the iframe will be loaded it’ll return some json and the iframeLoaded function will manage the state of the page (depending if there were an error like file too big or else).

So, let’s make this structure with the previous form:

//Unwrap the main form
$("#formMain").replaceWith($("#formMain").contents()); 
//Creating the new form
var $newForm1 = $("<form/>").attr({"enctype":"multipart/form-data", "target":"iframe1", "id":"form1"});
//Wrapping the first input with the new form
$("input[type=file][name=file1]").wrap($newForm1);
//Creating the add button and adding to the form
$("<button/>").attr({"type":"submit"}).appendTo($newForm1);
//Creating the iframe, binding the onLoad event and appending it next to the form
$("<iframe/>").attr({"class":"hidden", "id":"iframe1", "name":"iframe1"}).appendTo($newForm1.parent()).on("load", function(){/*do your stuff*/});

Ok so you open your favorite browser (meaning a modern browser like chrome), you test it works! (Normally :D)

Then you open Internet Explorer because yes your agency has accepted the customer minimal requirement of IE7+ and it doesn’t work ! Why?

Solution

If you want to create (on-the-fly) forms and they work with IE7 you have to:

  • Write $(“<form></form>”) instead of $(“<form/>”). Both instructions are valid in all browsers but IE7. I don’t know why..
  • Change the name (put one if you haven’t) of the form every time you change its place in the page with something like $newForm1.attr(“name”, “newForm1″+(Math.floor(Math.random()*1000)));
  • More specific to my context the “.on(“load”, callback)” or “.load(callback)” doesn’t really work on iframeS in IE7 so you have to declare your iframe with the onLoad attribute at the generation time of the page.
Posted in tips, web | Tagged , , , | Leave a comment

Two bookmarklet for testing your responsive design

What really is a bookmarlet? 
Basically a bookmarklet is JavaScript code embedded in a web link. Generally they call an external JavaScript file/library in order to add features to your current browsed web page. The advantage of these is that you just have to drag the link into your bookmark bar and every time you hit it some features appears on your page. So, no plugin, browser-independent and if you sync your bookmarks you will have it in all your browsers on every machine you have. A more complete explanation about bookmarklets are available on wikipedia.

I have started to used bookmarklet for a while now, they are very useful only one click on your bookmark bar and *bam*you have access to great features without having any plugin installed. I use particularly two bookmarklets for testing my responsive designs.

Responsive design test bookmarklet

Available here

I have taken http://bradfrostweb.com/demo/mobile-first/ as exemple, here are the “regular” desktop version.

Once the bookmarlet is actived a nice toolbar appears on the top and you can switch between possible views. Here in portait tablet size:

and here in portrait mobile size:

Resizer // A responsive design bookmarklet

Available here

The second one is basically the same thing but it can be useful to have a look if you don’t know how to add bookmarklets to your browser.

Enjoy testing your responsive design 🙂

Posted in Uncategorized | Leave a comment

Defaults drawable(s) in Android

Recently I have begun to play with Android, for one of my project I wanted to use some default images embedded in the framework. I have found the page of the documentation with these images but there is no visual preview of images. So I have made a little application which displays all of these icons. I though it could be a good training and might be useful (for me at least).

Here is what the application will look like:

Image

There is nothing special about it just a simple GridView with a TextView and an ImageView for each row.

For this application only four files (in addition to standard ones) are required:

  • main.xml this will be our main layout which contains the GridView
  • DrawingTestActivity.java this will be our main activity
  • gridrow.xml this will be the layout of each row
  • GridAdapter.java which will be the adapter for the grid used
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

 <!-- The grid view -->
 <GridView
    android:id="@+id/gridViewMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit">

</GridView>

</LinearLayout>

 

DrawingTestActivity.java:
package com.rphbck;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class DrawingTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //We set the layout
        setContentView(R.layout.main);

        //We get the GridView by its id
        GridView gridview = (GridView) findViewById(R.id.gridViewMain);

        //We set the GridAdapter to the gridview
        gridview.setAdapter(new GridAdapter(this));
    }
}
We need to set an adapter to the GridView to tell it how to display. There are some standard ones but here we want to use our own.

 

gridrow.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

 <TextView
    android:id="@+id/draw_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="50dip"/>

 <LinearLayout android:id="@+id/thumbnail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="15dip"
    android:layout_alignParentLeft="true">

    <ImageView
        android:id="@+id/draw_image"
        android:layout_width="50dip"
        android:layout_height="50dip" />

 </LinearLayout>
</RelativeLayout>
We use for one row layout a TextView to display the name of the drawable property and an ImageView to display it as an image.

 

GridAdapter.java:
And finally we make our grid adapter
package com.rphbck;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter {//Don't forget to extends BaseAdapter

 private Context mContext; //The context of the application
 private static LayoutInflater mInflater=null; //A helper for setting a layout from the code
 private ArrayList mThumbsLabels; //The list of our labels
 private ArrayList mThumbsValues; //The list of our image references

 public GridAdapter(Context c) {
  mContext = c;
  mThumbsLabels = new ArrayList();
  mThumbsValues = new ArrayList();

  //We populate our arrays
  for (Map.Entry entry : mThumbs.entrySet()) {
    mThumbsLabels.add(entry.getKey());
    mThumbsValues.add(entry.getValue());
  }
  //We get the layout manager
  mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

 @Override
 public int getCount() {
  return mThumbs.size();
 }

 @Override
 public Object getItem(int arg0) {
  return null;
 }

 @Override
 public long getItemId(int arg0) {
  return 0;
 }

 //Here is our important function to set every row of the gridview
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  String label = mThumbsLabels.get(position);//We get the current drawable name
  Integer value = mThumbsValues.get(position);//We get the current drawable value
  View vi=convertView;

  // if it's not recycled, initialize some attributes
  if(convertView==null) vi = mInflater.inflate(R.layout.gridrow, parent, false);
 //We search the text view and the image view
  TextView tvLabel = (TextView) vi.findViewById(R.id.draw_name);
  ImageView ivValue = (ImageView) vi.findViewById(R.id.draw_image);
 //And we set their attributes
  tvLabel.setText(label);
  ivValue.setImageResource(value);

  return vi;
 }

//Here is the list of default system drawables. The key is only for displaying purposes and the value is the reference to the drawable
 private HashMap mThumbs = new HashMap(){{
	put("android.R.drawable.alert_dark_frame", android.R.drawable.alert_dark_frame);
	put("android.R.drawable.alert_light_frame", android.R.drawable.alert_light_frame);
	put("android.R.drawable.arrow_down_float", android.R.drawable.arrow_down_float);
	put("android.R.drawable.arrow_up_float", android.R.drawable.arrow_up_float);
	put("android.R.drawable.bottom_bar", android.R.drawable.bottom_bar);
	put("android.R.drawable.btn_default", android.R.drawable.btn_default);
	put("android.R.drawable.btn_default_small", android.R.drawable.btn_default_small);
	put("android.R.drawable.btn_dialog", android.R.drawable.btn_dialog);
	put("android.R.drawable.btn_dropdown", android.R.drawable.btn_dropdown);
	put("android.R.drawable.btn_minus", android.R.drawable.btn_minus);
	put("android.R.drawable.btn_plus", android.R.drawable.btn_plus);
	put("android.R.drawable.btn_radio", android.R.drawable.btn_radio);
	put("android.R.drawable.btn_star", android.R.drawable.btn_star);
	put("android.R.drawable.btn_star_big_off", android.R.drawable.btn_star_big_off);
	put("android.R.drawable.btn_star_big_on", android.R.drawable.btn_star_big_on);
	put("android.R.drawable.button_onoff_indicator_off", android.R.drawable.button_onoff_indicator_off);
	put("android.R.drawable.button_onoff_indicator_on", android.R.drawable.button_onoff_indicator_on);
	put("android.R.drawable.checkbox_off_background", android.R.drawable.checkbox_off_background);
	put("android.R.drawable.checkbox_on_background", android.R.drawable.checkbox_on_background);
	put("android.R.drawable.dark_header", android.R.drawable.dark_header);
	put("android.R.drawable.dialog_frame", android.R.drawable.dialog_frame);
	put("android.R.drawable.dialog_holo_dark_frame", android.R.drawable.dialog_holo_dark_frame);
	put("android.R.drawable.dialog_holo_light_frame", android.R.drawable.dialog_holo_light_frame);
	put("android.R.drawable.divider_horizontal_bright", android.R.drawable.divider_horizontal_bright);
	put("android.R.drawable.divider_horizontal_dark", android.R.drawable.divider_horizontal_dark);
	put("android.R.drawable.divider_horizontal_dim_dark", android.R.drawable.divider_horizontal_dim_dark);
	put("android.R.drawable.divider_horizontal_textfield", android.R.drawable.divider_horizontal_textfield);
	put("android.R.drawable.edit_text", android.R.drawable.edit_text);
	put("android.R.drawable.editbox_background", android.R.drawable.editbox_background);
	put("android.R.drawable.editbox_background_normal", android.R.drawable.editbox_background_normal);
	put("android.R.drawable.editbox_dropdown_dark_frame", android.R.drawable.editbox_dropdown_dark_frame);
	put("android.R.drawable.editbox_dropdown_light_frame", android.R.drawable.editbox_dropdown_light_frame);
	put("android.R.drawable.gallery_thumb", android.R.drawable.gallery_thumb);
	put("android.R.drawable.ic_btn_speak_now", android.R.drawable.ic_btn_speak_now);
	put("android.R.drawable.ic_delete", android.R.drawable.ic_delete);
	put("android.R.drawable.ic_dialog_alert", android.R.drawable.ic_dialog_alert);
	put("android.R.drawable.ic_dialog_dialer", android.R.drawable.ic_dialog_dialer);
	put("android.R.drawable.ic_dialog_email", android.R.drawable.ic_dialog_email);
	put("android.R.drawable.ic_dialog_info", android.R.drawable.ic_dialog_info);
	put("android.R.drawable.ic_dialog_map", android.R.drawable.ic_dialog_map);
	put("android.R.drawable.ic_input_add", android.R.drawable.ic_input_add);
	put("android.R.drawable.ic_input_delete", android.R.drawable.ic_input_delete);
	put("android.R.drawable.ic_input_get", android.R.drawable.ic_input_get);
	put("android.R.drawable.ic_lock_idle_alarm", android.R.drawable.ic_lock_idle_alarm);
	put("android.R.drawable.ic_lock_idle_charging", android.R.drawable.ic_lock_idle_charging);
	put("android.R.drawable.ic_lock_idle_lock", android.R.drawable.ic_lock_idle_lock);
	put("android.R.drawable.ic_lock_idle_low_battery", android.R.drawable.ic_lock_idle_low_battery);
	put("android.R.drawable.ic_lock_lock", android.R.drawable.ic_lock_lock);
	put("android.R.drawable.ic_lock_power_off", android.R.drawable.ic_lock_power_off);
	put("android.R.drawable.ic_lock_silent_mode", android.R.drawable.ic_lock_silent_mode);
	put("android.R.drawable.ic_lock_silent_mode_off", android.R.drawable.ic_lock_silent_mode_off);
	put("android.R.drawable.ic_media_ff", android.R.drawable.ic_media_ff);
	put("android.R.drawable.ic_media_next", android.R.drawable.ic_media_next);
	put("android.R.drawable.ic_media_pause", android.R.drawable.ic_media_pause);
	put("android.R.drawable.ic_media_play", android.R.drawable.ic_media_play);
	put("android.R.drawable.ic_media_previous", android.R.drawable.ic_media_previous);
	put("android.R.drawable.ic_media_rew", android.R.drawable.ic_media_rew);
	put("android.R.drawable.ic_menu_add", android.R.drawable.ic_menu_add);
	put("android.R.drawable.ic_menu_agenda", android.R.drawable.ic_menu_agenda);
	put("android.R.drawable.ic_menu_always_landscape_portrait", android.R.drawable.ic_menu_always_landscape_portrait);
	put("android.R.drawable.ic_menu_call", android.R.drawable.ic_menu_call);
	put("android.R.drawable.ic_menu_camera", android.R.drawable.ic_menu_camera);
	put("android.R.drawable.ic_menu_close_clear_cancel", android.R.drawable.ic_menu_close_clear_cancel);
	put("android.R.drawable.ic_menu_compass", android.R.drawable.ic_menu_compass);
	put("android.R.drawable.ic_menu_crop", android.R.drawable.ic_menu_crop);
	put("android.R.drawable.ic_menu_day", android.R.drawable.ic_menu_day);
	put("android.R.drawable.ic_menu_delete", android.R.drawable.ic_menu_delete);
	put("android.R.drawable.ic_menu_directions", android.R.drawable.ic_menu_directions);
	put("android.R.drawable.ic_menu_edit", android.R.drawable.ic_menu_edit);
	put("android.R.drawable.ic_menu_gallery", android.R.drawable.ic_menu_gallery);
	put("android.R.drawable.ic_menu_help", android.R.drawable.ic_menu_help);
	put("android.R.drawable.ic_menu_info_details", android.R.drawable.ic_menu_info_details);
	put("android.R.drawable.ic_menu_manage", android.R.drawable.ic_menu_manage);
	put("android.R.drawable.ic_menu_mapmode", android.R.drawable.ic_menu_mapmode);
	put("android.R.drawable.ic_menu_month", android.R.drawable.ic_menu_month);
	put("android.R.drawable.ic_menu_more", android.R.drawable.ic_menu_more);
	put("android.R.drawable.ic_menu_my_calendar", android.R.drawable.ic_menu_my_calendar);
	put("android.R.drawable.ic_menu_mylocation", android.R.drawable.ic_menu_mylocation);
	put("android.R.drawable.ic_menu_myplaces", android.R.drawable.ic_menu_myplaces);
	put("android.R.drawable.ic_menu_preferences", android.R.drawable.ic_menu_preferences);
	put("android.R.drawable.ic_menu_recent_history", android.R.drawable.ic_menu_recent_history);
	put("android.R.drawable.ic_menu_report_image", android.R.drawable.ic_menu_report_image);
	put("android.R.drawable.ic_menu_revert", android.R.drawable.ic_menu_revert);
	put("android.R.drawable.ic_menu_rotate", android.R.drawable.ic_menu_rotate);
	put("android.R.drawable.ic_menu_save", android.R.drawable.ic_menu_save);
	put("android.R.drawable.ic_menu_search", android.R.drawable.ic_menu_search);
	put("android.R.drawable.ic_menu_send", android.R.drawable.ic_menu_send);
	put("android.R.drawable.ic_menu_set_as", android.R.drawable.ic_menu_set_as);
	put("android.R.drawable.ic_menu_share", android.R.drawable.ic_menu_share);
	put("android.R.drawable.ic_menu_slideshow", android.R.drawable.ic_menu_slideshow);
	put("android.R.drawable.ic_menu_sort_alphabetically", android.R.drawable.ic_menu_sort_alphabetically);
	put("android.R.drawable.ic_menu_sort_by_size", android.R.drawable.ic_menu_sort_by_size);
	put("android.R.drawable.ic_menu_today", android.R.drawable.ic_menu_today);
	put("android.R.drawable.ic_menu_upload", android.R.drawable.ic_menu_upload);
	put("android.R.drawable.ic_menu_upload_you_tube", android.R.drawable.ic_menu_upload_you_tube);
	put("android.R.drawable.ic_menu_view", android.R.drawable.ic_menu_view);
	put("android.R.drawable.ic_menu_week", android.R.drawable.ic_menu_week);
	put("android.R.drawable.ic_menu_zoom", android.R.drawable.ic_menu_zoom);
	put("android.R.drawable.ic_notification_clear_all", android.R.drawable.ic_notification_clear_all);
	put("android.R.drawable.ic_notification_overlay", android.R.drawable.ic_notification_overlay);
	put("android.R.drawable.ic_partial_secure", android.R.drawable.ic_partial_secure);
	put("android.R.drawable.ic_popup_disk_full", android.R.drawable.ic_popup_disk_full);
	put("android.R.drawable.ic_popup_reminder", android.R.drawable.ic_popup_reminder);
	put("android.R.drawable.ic_popup_sync", android.R.drawable.ic_popup_sync);
	put("android.R.drawable.ic_search_category_default", android.R.drawable.ic_search_category_default);
	put("android.R.drawable.ic_secure", android.R.drawable.ic_secure);
	put("android.R.drawable.list_selector_background", android.R.drawable.list_selector_background);
	put("android.R.drawable.menu_frame", android.R.drawable.menu_frame);
	put("android.R.drawable.menu_full_frame", android.R.drawable.menu_full_frame);
	put("android.R.drawable.menuitem_background", android.R.drawable.menuitem_background);
	put("android.R.drawable.picture_frame", android.R.drawable.picture_frame);
	put("android.R.drawable.presence_audio_away", android.R.drawable.presence_audio_away);
	put("android.R.drawable.presence_audio_busy", android.R.drawable.presence_audio_busy);
	put("android.R.drawable.presence_audio_online", android.R.drawable.presence_audio_online);
	put("android.R.drawable.presence_away", android.R.drawable.presence_away);
	put("android.R.drawable.presence_busy", android.R.drawable.presence_busy);
	put("android.R.drawable.presence_invisible", android.R.drawable.presence_invisible);
	put("android.R.drawable.presence_offline", android.R.drawable.presence_offline);
	put("android.R.drawable.presence_online", android.R.drawable.presence_online);
	put("android.R.drawable.presence_video_away", android.R.drawable.presence_video_away);
	put("android.R.drawable.presence_video_busy", android.R.drawable.presence_video_busy);
	put("android.R.drawable.presence_video_online", android.R.drawable.presence_video_online);
	put("android.R.drawable.progress_horizontal", android.R.drawable.progress_horizontal);
	put("android.R.drawable.progress_indeterminate_horizontal", android.R.drawable.progress_indeterminate_horizontal);
	put("android.R.drawable.radiobutton_off_background", android.R.drawable.radiobutton_off_background);
	put("android.R.drawable.radiobutton_on_background", android.R.drawable.radiobutton_on_background);
	put("android.R.drawable.screen_background_dark", android.R.drawable.screen_background_dark);
	put("android.R.drawable.screen_background_dark_transparent", android.R.drawable.screen_background_dark_transparent);
	put("android.R.drawable.screen_background_light", android.R.drawable.screen_background_light);
	put("android.R.drawable.screen_background_light_transparent", android.R.drawable.screen_background_light_transparent);
	put("android.R.drawable.spinner_background", android.R.drawable.spinner_background);
	put("android.R.drawable.spinner_dropdown_background", android.R.drawable.spinner_dropdown_background);
	put("android.R.drawable.star_big_off", android.R.drawable.star_big_off);
	put("android.R.drawable.star_big_on", android.R.drawable.star_big_on);
	put("android.R.drawable.star_off", android.R.drawable.star_off);
	put("android.R.drawable.star_on", android.R.drawable.star_on);
	put("android.R.drawable.stat_notify_call_mute", android.R.drawable.stat_notify_call_mute);
	put("android.R.drawable.stat_notify_chat", android.R.drawable.stat_notify_chat);
	put("android.R.drawable.stat_notify_error", android.R.drawable.stat_notify_error);
	put("android.R.drawable.stat_notify_missed_call", android.R.drawable.stat_notify_missed_call);
	put("android.R.drawable.stat_notify_more", android.R.drawable.stat_notify_more);
	put("android.R.drawable.stat_notify_sdcard", android.R.drawable.stat_notify_sdcard);
	put("android.R.drawable.stat_notify_sdcard_prepare", android.R.drawable.stat_notify_sdcard_prepare);
	put("android.R.drawable.stat_notify_sdcard_usb", android.R.drawable.stat_notify_sdcard_usb);
	put("android.R.drawable.stat_notify_sync", android.R.drawable.stat_notify_sync);
	put("android.R.drawable.stat_notify_sync_noanim", android.R.drawable.stat_notify_sync_noanim);
	put("android.R.drawable.stat_notify_voicemail", android.R.drawable.stat_notify_voicemail);
	put("android.R.drawable.stat_sys_data_bluetooth", android.R.drawable.stat_sys_data_bluetooth);
	put("android.R.drawable.stat_sys_download", android.R.drawable.stat_sys_download);
	put("android.R.drawable.stat_sys_download_done", android.R.drawable.stat_sys_download_done);
	put("android.R.drawable.stat_sys_headset", android.R.drawable.stat_sys_headset);
	put("android.R.drawable.stat_sys_phone_call", android.R.drawable.stat_sys_phone_call);
	put("android.R.drawable.stat_sys_phone_call_forward", android.R.drawable.stat_sys_phone_call_forward);
	put("android.R.drawable.stat_sys_phone_call_on_hold", android.R.drawable.stat_sys_phone_call_on_hold);
	put("android.R.drawable.stat_sys_speakerphone", android.R.drawable.stat_sys_speakerphone);
	put("android.R.drawable.stat_sys_upload", android.R.drawable.stat_sys_upload);
	put("android.R.drawable.stat_sys_upload_done", android.R.drawable.stat_sys_upload_done);
	put("android.R.drawable.stat_sys_vp_phone_call", android.R.drawable.stat_sys_vp_phone_call);
	put("android.R.drawable.stat_sys_vp_phone_call_on_hold", android.R.drawable.stat_sys_vp_phone_call_on_hold);
	put("android.R.drawable.stat_sys_warning", android.R.drawable.stat_sys_warning);
	put("android.R.drawable.status_bar_item_app_background", android.R.drawable.status_bar_item_app_background);
	put("android.R.drawable.status_bar_item_background", android.R.drawable.status_bar_item_background);
	put("android.R.drawable.sym_action_call", android.R.drawable.sym_action_call);
	put("android.R.drawable.sym_action_chat", android.R.drawable.sym_action_chat);
	put("android.R.drawable.sym_action_email", android.R.drawable.sym_action_email);
	put("android.R.drawable.sym_call_incoming", android.R.drawable.sym_call_incoming);
	put("android.R.drawable.sym_call_missed", android.R.drawable.sym_call_missed);
	put("android.R.drawable.sym_call_outgoing", android.R.drawable.sym_call_outgoing);
	put("android.R.drawable.sym_contact_card", android.R.drawable.sym_contact_card);
	put("android.R.drawable.sym_def_app_icon", android.R.drawable.sym_def_app_icon);
	put("android.R.drawable.title_bar", android.R.drawable.title_bar);
	put("android.R.drawable.title_bar_tall", android.R.drawable.title_bar_tall);
	put("android.R.drawable.toast_frame", android.R.drawable.toast_frame);
	put("android.R.drawable.zoom_plate", android.R.drawable.zoom_plate);
 }};

}
You can find the final (unsigned) apk here, just think to remove the png extension that I’ve added because of wordpress.
Posted in Android, tutorial | Tagged , | Leave a comment

How contribute_to_model can handle ManyToMany fields ?

I work on a crm made in django (cremecrm.com), and sometimes for customers I use the snippet contribute_to_model in order to avoid to modify existing models. It’s the best solution we found for staying the most mainstream and avoid huge merges. The problem with this work around is it doesn’t handle many to many. Here’s the tip I found for managing m2m without modifying contribute to model.

The tips to deal with many to many :

# -*- coding: utf-8 -*-

from django.db import models
from django.db.models.fields import CharField, BooleanField
from django.db.models.fields.related import ManyToManyField
from django.utils.translation import ugettext_lazy as _

from contribute_to_model import contribute_to_model

class MyModel(models.Model):
    title = CharField(_(u'Title'), max_length=100)

    class Meta:
        app_label = "my_app"

class MyFutureM2MModel(models.Model):
    foo = CharField(_(u'Foo'), max_length=100)

    class Meta:
        app_label = "my_app"

class MyModelWhichContribute(models.Model):
    field_to_add1 = CharField(_(u'field_to_add1 to MyModel'), max_length=100, blank=True, null=True)
    field_to_add2 = BooleanField(_(u'field_to_add2 to MyModel'), default=False)

    class Meta:
        abstract = True
        db_table = 'my_app_mymodel'

MyModel.add_to_class('my_m2m_field_name', ManyToManyField(MyFutureM2MModel, verbose_name=_(u'My m2m'), blank=True, null=True))
contribute_to_model(MyModelWhichContribute, MyModel)

The contribute_to_model code (which is not from me):


from django.db import models
from django.utils.functional import curry


def contribute_to_model(contrib, destination):
    """
    Update ``contrib`` model based on ``destination``.

    Every new field will be created. Existing fields will have some properties
    updated.

    Methods and properties of ``contrib`` will populate ``destination``.

    Usage example:

    >>> from django.contrib.auth.models import User
    >>> from django.db import models
    >>> 
    >>> class MyUser(models.Model):
    >>>     class Meta:
    >>>         abstract = True
    >>>         db_table = 'user' # new auth_user table name
    >>>
    >>>     # New field
    >>>     phone = models.CharField('phone number', blank=True, max_length=20)
    >>> 
    >>>     # Email could be null
    >>>     email = models.EmailField(blank=True, null=True)
    >>>
    >>>     # New (stupid) method
    >>>     def get_phone(self):
    >>>         return self.phone
    >>> 
    >>> contribute_to_model(MyUser, User)
    """
    # Contrib should be abstract
    if not contrib._meta.abstract:
        raise ValueError('Your contrib model should be abstract.')

    protected_get_display_method = []
    # Update or create new fields
    for field in contrib._meta.fields:
        try:
            destination._meta.get_field_by_name(field.name)
        except models.FieldDoesNotExist:
            field.contribute_to_class(destination, field.name)
            if field.choices:
                setattr(destination, 'get_%s_display' % field.name, curry(destination._get_FIELD_display, field=field))
                protected_get_display_method.append ('get_%s_display' % field.name)
        else:
            current_field = destination._meta.get_field_by_name(field.name)[0]
            current_field.null = field.null
            current_field.blank = field.blank
            current_field.max_length = field.max_length

    # Change some meta information
    if hasattr(contrib.Meta, 'db_table'):
        destination._meta.db_table = contrib._meta.db_table

    # Add (or replace) properties and methods
    protected_items = dir(models.Model) + ['Meta', '_meta'] + protected_get_display_method #TODO: use a set() ??

    for k, v in contrib.__dict__.items(): #TODO: iteritems() instead ??
        if k not in protected_items:
            setattr(destination, k, v)
Posted in django, python | Leave a comment

How to translate slug with django-modeltranslation

I have been to a django conference this morning (DjangoCong / @djangocong) , and a talk was about django-modeltranslation. At the end of the presentation, someone ask the question: “How can I translate my slugs with this app ?”. I remembered I used this app and I do that but I could’nt remember HOW ! So, here is how I did that, I think it might be tricky but it worked in my case:

I’ll pass about how to use the app, there is a good documentation on the author site but just remember that the app add “_lang” (i.e: _en, _fr…) at the end of each translated attribute. 

So, let’s begin:

First make your model with a slug (or add to you existing model), I choose to describe a product :


#File models.py

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.template.defaultfilters import slugify

class Product(Model):
    name = models.CharField(max_length=200, help_text=_(u"Name of the product"))
    slug = AutoSlugField(_('slug'), populate_from='name', overwrite=True)

    class Meta:
        app_label = "my_app"
        verbose_name = _(u"Product") 
        verbose_name_plural = _(u"Products") 

 

Then in your translation.py, say that “slug” has to be translated:


#File translation.py
from modeltranslation.translator import translator, TranslationOptions

from my_app.models import Product

class ProductTranslationOptions(TranslationOptions):
    fields = ('name', 'slug')

translator.register(Product, ProductTranslationOptions)

 

So by now, your slug can be translated but it is never filled and I don’t want my clients to fill this information. The populate_from could’nt work with translations and I don’t want to translate myself each time someone added a Product. So I overrode the save of Product using the translated “name” (which is done by the person who add the Product).

I defined also “get_absolute_url” which we’ll talk later.


#File models.py

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.template.defaultfilters import slugify

class Product(models.Model):
    name = models.CharField(max_length=200, help_text=_(u"Name of the product"))
    slug = AutoSlugField(_('slug'), populate_from='name', overwrite=True)

    class Meta:
        app_label = "my_app"
        verbose_name = _(u"Product") 
        verbose_name_plural = _(u"Products") 

    #So for each defined language I set the slug with the name of the Product
    # I think the test of hasattr could be removed if you entirely "control" your application
    def save(self, *args, **kwargs):
        for lang_code, lang_verbose in settings.LANGUAGES:
            if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'name_%s' % lang_code):
                setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'name_%s' % lang_code, u"")))
        super(Product, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return "/product/%s-%s" % (self.id, self.slug)

 

Now all my Products have their slug automaticaly translated ! I defined the “get_absolute_url” to use the translated slug (as you know django-modeltranslation uses the defined attribute [here “slug”] as a wrapper for “slug_fr”, “slug_en”,…and returns you the translated attribute in the current choosen language).

But, which pattern will match with my translated url ?? Answer : No one ! Here is the tricky part:

I defined the detailview url of a product as its product_id and “a slug”:


#File urls.py

from django.conf.urls.defaults import *
urlpatterns = patterns('my_app.views',
    (r'^product/(?P\d+)-(?P([\w,-]+)*)$', "products.detail_product"),
)

 

And in my view, I set the default value slug to an empty string (maybe None works?), so it doesn’t matter which slug the url pattern will receive it matches only the product_id will be catched (and verified) !


#File products.py (== views.py)

def detail_product(request, product_id, slug=""):
    product = get_object_or_404(Product, pk=product_id)
    #Return your HttpResponse..

So my product could be found either by:
/products/product/1-my-product
or
/products/product/1-mon-produit

 

That’s it ! I hope I was enough clear otherwise tell me in comments 😉

Posted in django, python | 9 Comments

How to reorder chrome extensions buttons

It’s not a big deal, but today after bugfixing a downloaded chrome extension, I was wondering how can I order them ?

I wanted to change this :

chrome extensions

into this:

chrome extensions 2

So:

  • Go to extensions tab (chrome://extensions in the url bar) or Tools/Extensions
  • Disable all displayed extensions
  • Enable one by one extension in the order you want them appear

That’s all !

Posted in Uncategorized | 1 Comment

Make inline images to improve performance (with django template tags)

Despite we have now big connections and broadband lines, it’s still too long. So, as developpers, we have a role to play in web-performances.

Today, I’ll show you a snippet I have written a couple of weeks ago, to encode images in base64 on-the-fly.

Click here to go directly to the django part


Why encode images ?

You can b64-encode images to reduce your numbers of HTTP requests. A request has an average response time of 200ms and most of the browsers let you open 2 HTTP connections at the same time. Great famous tools/patterns, like YSLOW and Page speed recommend to reduce the number of HTTP request on a page.

There are various school on how to handle the image case, I know 2 :

Using css-sprites:

It’s a technique which consist to combine all you site images in one image, and then shift the visible area to the required coordonates of the big image.

How I do that ?

You can make your own big sprite by collecting all your site images and then pasting them on a big png or you can use sprites generators (Spritegen, csssprites.com, google).

After that you use the background-position attribute on a tag instead of writting a <img /> tag.  Which gives you pretty much this:


.my-bg-class  {background-image:url('../images/my_sprite.png')}
.info-icon    {background-position:0px -50px}
.warning-icon {background-position:0px -60px}
.error-icon   {background-position:0px -70px}

<div class="my-bg-class info-icon"></div>
<div class="my-bg-class warning-icon"></div>
<div class="my-bg-class error-icon"></div>

So, for displaying 3 icons, you’ll make only one HTTP request and then css handle the rest ! Just for 3 icons you can gain maybe 500ms !

Is that good to use css-sprites ?

Most of time yes, but there are some disadvantages of this technique. When number of images grows the sprite grows at the same time and even if sprite let you make only one HTTP request you’ll to have a big one !

 

Using image base64 encoded

How i do that ?

There are 2 ways to do that (at least I know):

inlining the src in the <img /> tag (for reading purposes I return to the line but your b64 code has to be in one line without “\n”) :

<img src="data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcp
LDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAeAB4D
ASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAk
M2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaX
mJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2XUdSnGofYYkZFAV3kBwSDngflTHjneRW
a7LThRgMAQuO4AxWL4/u73SI4NQspIQSwWRZQSCoOD/6ED+Fc3prvqHi6HUZdTmkkt4QXWEDy36gA+hO7oOu0ZrwcTUqRrT9pOy6fLZadzvp0ealzwW256Np+qxT+d5k
42qcqzLtBA4OPXB4rUVldQykFSMgjvXnkV5e20jm6tJTJGGZWePaACeW7gdRnk4rrtBmd7IRExskKqoaMHGcc/0/OunA491Zexmte/cyrUORcyehY1eOObS545VUow2n
Kg7QTgnn0BrjdJktbCzkt7W2ihmic7uOW5zye3pXc3k8dtaSSyqXQDBUDOc8f1rzDXreC80/7LY6bBZzXVx5Im+0u21QxBwMccr+X6LMqDqWfPb5XLwjveNrm7HrMWs3
BsreNJrqEiTySQcDpk9iOea7GxtI7Gzjt40VQo52jgnua4HRp1Pi9L8RBYo1TTEQHJUbQc/99GvRqvLqFOClKMm/X9CcVdNRasf/2Q==" alt=":'(" />

Or in your css:

.chocobo { background :url(data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBw
gJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI
yMjL/wAARCAAeAB4DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDK
BkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrK
ztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQ
AAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goO
EhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2XUdSnGofYYkZFAV
3kBwSDngflTHjneRWa7LThRgMAQuO4AxWL4/u73SI4NQspIQSwWRZQSCoOD/6ED+Fc3prvqHi6HUZdTmkkt4QXWEDy36gA+hO7oOu0ZrwcTUqRrT9pOy6fLZadzvp0ea
lzwW256Np+qxT+d5k42qcqzLtBA4OPXB4rUVldQykFSMgjvXnkV5e20jm6tJTJGGZWePaACeW7gdRnk4rrtBmd7IRExskKqoaMHGcc/0/OunA491Zexmte/cyrUORcye
hY1eOObS545VUow2nKg7QTgnn0BrjdJktbCzkt7W2ihmic7uOW5zye3pXc3k8dtaSSyqXQDBUDOc8f1rzDXreC80/7LY6bBZzXVx5Im+0u21QxBwMccr+X6LMqDqWfPb
5XLwjveNrm7HrMWs3BsreNJrqEiTySQcDpk9iOea7GxtI7Gzjt40VQo52jgnua4HRp1Pi9L8RBYo1TTEQHJUbQc/99GvRqvLqFOClKMm/X9CcVdNRasf/2Q==);}

Special attention on web browser support :

Base64 encoded images (and data URIs more generally)  are supported in:

  • Firefox 2+
  • Safari – all versions
  • Google Chrome – all versions
  • Opera 7.2+
  • Internet Explorer 8+

For IE < 8, you need to interest yourself in the MHTML alternative.

Is that good to b64-encode images ?

It depends on your needs, but it can be usefull if you haven’t to support old browsers and if you have small images. Base64 is pretty verbose and big (~30% bigger) but you haven’t to make a HTTP request and if you gzip your css file it is pretty much the same than a regular image.

 

 

Using image base64 encoded in django

As I said previously, I have written a django template tag which do the work of auto-inlining your images stored in your media directory and make a cached version of the image on the server.

You need to have:

  • PIL installed
  • A writable dir for cached version (in the code I used /tmp)

 

File image_tags.py:

# -*- coding: utf-8 -*-
"""
    django templates tags for images
    @author: R. BECK
    @version: 0.1
"""

#from __future__ import with_statement #Python 2.5

import base64
import os
import Image
from re import compile as compile_re
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO  import StringIO

from django.conf     import settings
from django.template import TemplateSyntaxError, Node, Library, Template

register = Library()

TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG
MEDIA_ROOT     = settings.MEDIA_ROOT
CACHE_DIR      = "/tmp"

templatevar_re = compile_re("\{\{(.+)\}\}")
media_re       = compile_re("\{\{MEDIA_ROOT|MEDIA_URL\}\}")

class EmbeddedImgNode(Node):
    """Image node parser for rendering html inline base64 image"""

    def __init__(self, attributes):
        self.attrs = {}
        attrs = self.attrs
        for attr_value in attributes:
            try:
                attr, value = attr_value.split('=', 1)
            except ValueError, val_err:
                raise TemplateSyntaxError(u"Syntax Error :", val_err)
            attrs[attr] = value

        src = attrs.get('src')
        if not src:
            raise TemplateSyntaxError(u"You have to specify a non-empty src \
                                        attribute")

    def _encode_img(self, file_path):
        """Returns image base64 string representation and makes a cache file"""
        filename   = file_path.rpartition(os.sep)[2]
        need_cache = True
        content    = ""

        cache_file = "%s_cache" % os.path.join(CACHE_DIR, filename)

        try:
            with open(cache_file, 'r') as cached_file:
                content = cached_file.read()
            need_cache = False
        except IOError:
            pass

        if need_cache:
            try:
                image = open(file_path, 'r')
                out   = StringIO()
                base64.encode(image, out)
                content = out.getvalue().replace('\n', '')
            except IOError:
                pass
            else:
                try:
                    with open(cache_file, 'w+') as cached_file:
                        cached_file.write(content)
                except IOError:
                    pass
        return content

    def _render_img(self):
        """Prepare image attributes"""
        attrs = self.attrs
        attrs_get = attrs.get
        src    = attrs_get('src')
        height = attrs_get('height')
        width  = attrs_get('width')

        if media_re.search(src):
            src = src.replace('{{MEDIA_ROOT}}', '') \
                     .replace('{{MEDIA_URL}}', '')

        src = src.replace('"', '')
        src = os.path.join(MEDIA_ROOT, src)

        try:
            img     = Image.open(src)
            _width, _height    = img.size
            _format = 'image/%s' % img.format

            if not height:
                attrs['height'] = '%spx' % _height

            if not width:
                attrs['width'] = '%spx' % _width

            b64encoded = self._encode_img(img.filename)

            attrs['src'] = "data:%s;base64,%s" % (_format, b64encoded)
        except IOError:
            attrs['src'] = ""

    def render(self, context):
        self._render_img()

        attrs  = self.attrs
        search = templatevar_re.search

        for k, v in attrs.iteritems():
            if search(v):
                attrs[k] = Template(v).render(context)

        return """<img %s/>""" % ' '.join(['%s=%s' % (k, v if v else '""')
                                             for k, v in attrs.iteritems()])

@register.tag(name="embedded_img")
def do_embedded_img(parser, token):
    return EmbeddedImgNode(token.split_contents()[1:])


How to use it:

  • Put the image_tags.py in templatetags dir of one of your installed app
  • In your template load it

You can use context variables in the template tag.

Your template.html:

{% load image_tags %}
{% embedded_img src="/media/images/002.gif" height="200px" width="200px" alt="{{my_var}}" %}
{% embedded_img src="{{MEDIA_URL}}upload/images/001.jpg" height="200px" width="200px" alt="lala" %}
{% embedded_img src="upload/images/logo_corp_264.png" alt="corp" %}
{% embedded_img src="{{MEDIA_URL}}upload/images/001.jpg" width="200px" alt="lala" %}
{% embedded_img src="{{MEDIA_URL}}upload/images/001.jpg" height="200px" width="200px" alt="lala" %}
{% embedded_img src="{{MEDIA_URL}}upload/images/001.jpg" %}

That’s it ! The template tag generates all for you ! You can inline all images you want in your HTML, even I recommend you to inline only small images.

If you find any bug in my code, or if you think there are some optimisations possible don’t hesitate to comment it !

Those snippets are now available at:

Posted in django, python, web | Leave a comment