Skip to main content

Non capturing group in regular expression and it's use

Recently I have been stuck in a regular expression where I had to use grouping in places, values of which were not required. It won't make sense to explain the problem without the text. So here it is


Controller Id Connection Status Connection State Secure Role
------------- ----------------- ---------------- ------ ------
1             Connected         Active           No     Slave
25            Disconnected      Idle             No     Master


My goal was to get the numeric values at the beginning of the line while still matching the whole line for safety (so that any other numeric values in the output don't match). As you see in the output, each column can contain a value from a list of fixed values. e.g. Connection Status can only contain Connected or Disconnected. That demands the following regular expression -




But with the above expression, we are fetching all the columns when all we want is the first column. This is where the non capturing group of regular expression comes …

Simple employee table with OpenStack Horizon DataTable module

I was working on OpenStack dashboard (aka Horizon) few past few months and I will share a simple way to build your data tables based on Horizon.
To give a brief introduction of Horizon, it is the official dashboard project of OpenStack, the cloud operating system. Horizon is a python Django application. It provides pre-defined modules for common web application requirements like tabs, workflow, table etc. From Grizzly release onward Horizon modules are separated from OpenStack specific code. It allows one to use Horizon modules independently.

To build a data table in Horizon you need to simply create a model class for your data. The important thing to remember here is that the class must have an "id" attribute. Horizon will build rows based on this id. It can be alpha numeric also. Though it is not mandatory to display the id column in the table, you can still have it. Below is the data model for my Employee table -

class Employee:
    """
    Employee class represents the employee data
    """

    def __init__(self, emp_id, name, addr, salary):
        self.id = emp_id
        self.name = name
        self.addr = addr
        self.salary = salary
 
The employee class has 4 attributes - id, name, address and the salary. Each of these attributes can be displayed in a column of our Horizon DataTable. I use below code in my views.py


from horizon import tables
from .tables import TabledisplayTable

class IndexView(tables.DataTableView):
    table_class = TabledisplayTable
    template_name = 'project/tabledisplay/index.html'

    def get_data(self):
        strobj = '[{"id": 111, "name": "emp1", "salary": 1000, "addr": "kolkata"}, {"id": 222, "name": "emp2", "salary": 5000, "addr": "bangalore"}]'
        instances = json.loads(strobj)
        ret = []
        for inst in instances:
            ret.append(Employee(inst['id'], inst['name'], inst['addr'], inst['salary']))
        return ret
 

We need to create a tables.py with TabledisplayTable class which allows us to map the columns to model attributes. Like this -

from horizon import tables
from django.utils.translation import ugettext_lazy as _

class TabledisplayTable(tables.DataTable):
    name = tables.Column("name",
                         verbose_name=_("Employee Name"))
    salary = tables.Column("salary", verbose_name=_("Salary in Rs"))
    addr = tables.Column("addr",
                         verbose_name=_("Address"))

    class Meta:
        name = "emptable"
        verbose_name = _("Employee Table")
 

Finally we need a Django template to render this table. I have used the following code -
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Table Display" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Employee Table Display") %}
{% endblock page_header %}

{% block main %}
  {{ table.render }}
{% endblock %}
 

This should create the Employee table with 2 rows using Horizon DataTable module. Try it out.

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I have followed your this tutorials and it helps me a lot.

    I would like to ask some help, I am a newbie developer using django-framework, its been several months since i started to learning it.

    My boss ask me to develop some custom modules for openstack horizon and this tutorial makes me understand it a little.

    I am having a problem passing a data to a horizon datatable. Can you please have me some example fetching a data from openstack_dashboard.api.nova and pass it to a table.
    I have tried to do this but it always gives me an error telling the object is not itterable, i am using

    usage = api.nova.usage_get(self.request, self.tenant_id, start, end)

    ReplyDelete
    Replies
    1. For making the DataTable, you need a list (iterable) object. NovaUsage object is not a list. You need to extract the fields from the usage object and make a list before you return from get_data() method.

      Delete
  3. hii.. such a nice tutorial .. really helpful for me. actually i'm customizing horizon, i've created on tab with datatable and i have to fill that table from rest api which give json format in response. i used same code which you've written but i m getting one error "string indices must be integers, not str". please help me if you know how to fix it. here is my code for view http://pastebin.com/2NBnDrea

    ReplyDelete
    Replies
    1. I think you missed to convert the swobj variable, which is a string, to a python object. Try to use
      x = json.loads(swobj)
      then use the x variable in your for loop.

      Delete
    2. yes yes, that's my mistake. now i have table with data and table action. when i click on button it show ajax-model but in my case instead of drawing form inside ajax-model i have to create table which full fill by ajax-call response and need to draw html inputs like text and radio button. travel lots of horizon tutorial but didn't get any clue. . hope you understand my point. hoping some helpful suggestion from you.

      Thanks a lot :)

      Delete
    3. I am not in touch with Horizon for almost a year now. Can't be of much help to you.

      Delete

Post a Comment

Popular posts from this blog

Call an external program from MySQL trigger

MySQL is the choice of many when it comes to database. Its free and quite robust.
During one of our prototype implementations we had a requirement of calling some external processes when there is a change in a MySQL table. MySQL triggers are provided for the same purpose. They get executed when the table is changed in certain ways that is specified by the programmer. Now it is very easy (rather trivial) to do some thing in other MySQL database tables when trigger gets fired. But, our requirement was to call a C program.

Fortunately MySQL provides a way to implement your own functions, its called User Defined Functions (UDF). The "how to" is here. Now that we know, how to define your own functions and call them from MySQL events, we need to write our logic in a C program by following the interface provided by MySQL and we are done.

Wait a minute. That is already done by somebody. They have made a library of UDFs. One of them, LIB_MYSQLUDF_SYS does exactly what we want. It al…

Using Multi threading with Drools

Drools is a very popular rule engine. It is based on Rete algorithm. To understand what is a rule engine and how to use it check here. But here I will assume that you have some working knowledge on Drools.

What I am going to discuss in this post is 'how to use multi-threading with Drools'. Below is a snippet which creates a KnowledgeBase from a DRL file.



public void buildKnowledgeBase() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newUrlResource( "file://myrules.drl" ), assertFalse( kbuilder.hasErrors() ); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); }
If this method is called from multiple threads I get below exception -



Exception in thread "Thread-60" [Error: incomplete statement: (possible
use of reserved keyword as identifier: )]

[Near : {... globals != empt ....}]

^

[Line: 0, Column: 0]

at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterp…

Get JSON data response with JQuery Form plugin for a file upload form

My latest project involves JQuery for UI development. Frankly speaking, I did not have much idea of JQuery before. But I found it very easy to understand. All APIs are well documented with lots of examples available on Internet. The best feature of JQuery is its plugins. There are thousands of plugins available to play with. For every need of my web app I could find a plugin.



In my web app I am using JQuery Form plugin to submit the forms through AJAX. The return from my servlet is JSON object. The form plugin works great for all my forms. Well almost all, there is a HTML form which has a file upload box along with other input fields. This form was not able to get the response in JSON format. Though it worked in Google Chrome, but Firefox was presenting me with a file save dialog box.
I did a lot of googling to find out whats going on. Finally I observed that the problem is with HTTP headers that the form submit request has. Here are the headers captured by Chrome







As you can see the