Search This Blog

Thursday 28 November 2013

Read Data from xml using Dom in Python

Here is sample code for how we can use dom in python for extracting data from xml.

import xml.dom.minidom

document = """<root><firstname>Anil</firstname>
            <middlename>R.</middlename>
            <surname>Kesariya</surname></root>"""
         
dom = xml.dom.minidom.parseString(document)

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def handleTok(tokenlist):
    texts = ""
    for token in tokenlist:
        texts += " "+ getText(token.childNodes)
    return texts

first_name = dom.getElementsByTagName("firstname")
first_name = handleTok(first_name)

middle_name = dom.getElementsByTagName("middlename")
middle_name = handleTok(middle_name)

last_name = dom.getElementsByTagName("surname")
last_name = handleTok(last_name)

print "Name Detail :::",first_name + " " + middle_name + " " + last_name

Setup Aeroo Report Configuration Step by Step In ubuntu



Here is the link for Aeroo library installation and configuration of aeroo report in your system

Click Here 

List Date between Two Dates using Python



Here is sample code for listing the all dates for between two dates


    from dateutil import rrule
    from datetime import datetime

    def get_date_range(date_from, date_to):
   
        date_list = []
   
        for dd in rrule.rrule(rrule.DAILY,
                  dtstart=datetime.strptime(date_from, "%Y-%m-%d"),
                  until=datetime.strptime(date_to, "%Y-%m-%d")):
   
            date_list.append(datetime.strftime(dd,"%Y-%m-%d"))
    return date_list


    date_from = '2013-11-02'
    date_to = '2013-11-13'

    date_data = get_date_range(date_from, date_to)

    print "List Dates ::::::",date_data


O/P :
List Dates :::::: ['2013-11-02', '2013-11-03', '2013-11-04', '2013-11-05', '2013-11-06', '2013-11-07', '2013-11-08', '2013-11-09', '2013-11-10', '2013-11-11', '2013-11-12', '2013-11-13']

Saturday 21 September 2013

Step by Step Configure OpnERP 7.0 Development Environment on Ubuntu



Required Openrep 7.0 source code.

 If you don't have the source code than no worry you can download it from launchpad.

Note: Before using launchpad command, Register in Launch Pad  and share the ssh key of your system.

SSH Key config.

Register SSH key(https://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair)
1) sudo apt-get install openssh-client
2) ssh-keygen -t rsa
3) When prompted, press Enter to accept the default file name for your key.
4) Next, enter then confirm a password to protect your SSH key. Your key pair is stored in ~/.ssh/ as id_rsa.pub (public key) and id_rsa (private key)
5) Then the public and private keys are available in the directory .ssh
6) open the id_rsa.pub in text editor. copy its contents to your clipboard
7) Visit your SSH keys page(https://launchpad.net/people/+me/+editsshkeys)
8) Paste your public key into the text box and then click the Import public key button to continue.

for downloading you need to install bzr in your system. if it is already install than its fine. other wise you can install it by using this command.

sudo apt-get install bzr

sudo apt-get install bzrtools

Create Separate Directory for OpenERP and download all these branches branches one by one.

bzr branch lp:openobject-server

bzr branch lp:openobject-addons

bzr branch lp:openerp-web/7.0


Required Basic Library to be Install 
(These lib are used in Openerp Existing Modules so basically you need to install these All,Just copy and paste into your commmand prompt.)

sudo apt-get install python-dateutil python-docutils python-feedparser python-gdata python-jinja2 python-ldap python-libxslt1 python-lxml python-mako python-mock python-openid python-psycopg2 python-psutil python-pybabel python-pychart python-pydot python-pyparsing python-reportlab python-simplejson python-tz python-unittest2 python-vatnumber python-vobject python-webdav python-werkzeug python-xlwt python-yaml python-zsi python-psutil

Download the Eclipse from below link.

     Download Linux 32 Bit

     Download Linux 64 Bit 



Now All downloading procedure is finished.

Steps for Setup the OpenERP Source code into your Eclipse.

1) Create One directory for your Workspace and inside that Workspace directory create directory for OpenERP. .

2) Paste your all three branches into OpenERP directory which are downloaded from launchpad.

3) Go to Eclipse Create new project select under General category and than select Project and than click Next.

4) It will ask for the project name give the project as , your directory name which is in Workspace

Eg : Your source directory name is OpenERP which is inside the work space than give your Project name as OpenERP.

5) Click on Finish button. 

All the OpenERP source code will be available on your project directory.


Setup OpenERP Eclipse Template

    Download OpenERP XML Template files.

       sudo apt-install subversion

       svn checkout http://openerp-eclipse-template.googlecode.com/svn/trunk/








Friday 23 August 2013

Generate Random password using Python


#Random Password Generatation

    import random, string

    rand_obj = random.SystemRandom()
    length = 10 #specify lenth of your password
    password_string = string.letters[0:52] + string.digits  # concate the small , big alaphabet & numbers
    password = str().join(rand_obj.choice(password_string) for _ in range(length))
    #generate the password based on your alphabet string and lenght.

    print "Random Generated Password with 10 size lenght",password

Sunday 26 May 2013

Importance of space while applying Group Acess on menu item in OpenERP

How to apply more than one groups to menu item on Openerp.

E.g.

Xml file :

<menuitem id="sub_menu_id" parent="main_menu" name="Reports" groups="base.group_hr_manager,user_define_group" />

Here I have given two groups to the Menu item. so this menu only visible to those user who has access of this two groups.


Note :  (Improtance of space).

When you apply more than two groups on specific menu than don't give space between two groups just separate it with comma ','  other wise there will be an error raise No such external ID.

Wrong Ways.

 <menuitem id="sub_menu_id" parent="main_menu" name="Reports" groups="base.group_hr_manager, user_define_group" />



Monday 13 May 2013

HTMl page-break solution for webkit report in OpenERP

HTML page break solution for webkit report in OpenERP


    table {
               page-break-inside:auto
    }


    table tr {
                page-break-inside:avoid; page-break-after:auto;
  }


Eg:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
<style type="text/css">
    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }
</style>
</head>
<body>
    <table>
        <thead>
            <tr><th>heading</th></tr>
        </thead>
        <tfoot>
            <tr><td>notes</td></tr>
        </tfoot>
        <tr>
            <td>x</td>
        </tr>
        <tr>
            <td>x</td>
        </tr>
        <!-- Number ofrows -->
        <tr>
            <td>x</td>
        </tr>
    </tbody>
    </table>
</body>
</html>

 Applied this code in your CSS File or inside the <style> tag.
 


Monday 22 April 2013

Steps for How to create simple webkit report Demo Module in Openerp

Sample module for  webkit report on purchase Order  (OpenERP- 7.0)


Module Name :   webkit_report_purchase_order

Requrired things to implement Webkit report

 1) Download webkit to pdf library file from below link and set the system parameter.

   The file is for linux and 32 bit.
 
     Click here to Download   for Linux 32 bits.
     Click here to Download   for Linux 64 bits.

 If you have another system configuration than you can find your specific file   from below link.

http://code.google.com/p/wkhtmltopdf/downloads/list

If your file is downloaded than set the path of your file inside the system parameter for that follow this menu structure

Setting >> Technical >> Parameters >> System Parameters

Create new record inside the System parameter.

Here you will ask for two fields Key and value :

Key  : webkit_path
Value : set full  path of your downloaded lib file (wkhtmltopdf) .

File & Directory Structure inside the module :


>>webkit_report_purchase_order
     >>report
          >>__init__.py
          >>purchase_webkit.py
          >>purchase_rep_webkit.mako

     >>__init__.py
     >>__openerp__.py
     >>report_view.xml


Code and Description of each files :

1) webkit_report_purchase_order/__init__.py

 * Code :
    import report


* Descriptoin :

     Simply initalize the report direcotry.

2) webkit_report_purchase_order/__openerp__.py

  * Code :

       {
             "name": "Report Webkit 7",
             "version": "1.0",
            "depends": ["purchase","report_webkit"],
            "author": "Serpent Consulting Services",
             "category": "Purchase",
            "description": """
               This module is providing webkit report for purchase order
             """,
              'update_xml': ["report_view.xml"],
              'installable': True,
              'application':True,
              'auto_install':False,
     }

   * Descriptoin :

      The openep is the Main cofig. file in module if you are not defining openerp file you will not able to see your module while you updating module list.

Inside the dependency you must give the dependancy of atleast two  modules

    i) report_webkit :
       which is the core module for webkit report . you must give the dependency of this module.

   ii) purchase:

      The module name , which contain model on which you are going to generating report .

      Here i have used purchase.order model , which defined inside the purchase module. like wise on whatever model you are going to create report you must give that module name.

  
3)  webkit_report_purchase_order/report_view.xml

  * Code :


        <?xml version="1.0" encoding="UTF-8"?>

        <openerp>
   
                 <data>
                         <record id="purchase_rep_webk_head" model="ir.header_webkit">
                           <field name="footer_html"><![CDATA[
            <html>
                <body>
                    <center>Serpent Consuting Services</center>
                </body>
            </html>]]>
            </field>
            <field name="orientation">Portrait</field>
            <field name="format">A4</field>
            <field name="html"><![CDATA[
                <html>

                    <body style="border:0; margin:15;" onload="subst()">
                        <table class="header" style="border-bottom: 0px solid black; width: 100%">
                            <tr>
                                <td style="text-align:left; font-size:15px; font-weight: bold;"><span style="text-transform:uppercase; font-size:12px;">Heading 1</td>
                            </tr>
                            <tr>
                                <td style="text-align:left; font-size:12px; font-weight: bold;"><span style="text-transform:uppercase; font-size:12px;">Heading 2</td>
                            </tr>
                        </table> ${_debug or ''|n} </body>
                </html>]]>
                </field>
                <field eval="20" name="margin_top"/>
                <field eval="10" name="margin_bottom"/>
                <field name="css"><![CDATA[
   
                    body {
                        font-family:Arial;
                        font-size:12;
                    }
                   
                    .cell{
                        border-spacing: 0;
                        border-collapse: collapse;
                        border-style:solid;
                        border: 1px solid grey;
                        font-size:10px;
                        text-align:center;
                    }
                ]]>
                          </field>
                          <field name="name">Purchase Webkit Header</field>
                      </record>
              </data>

             <data>
                      <report auto="False"
                        id="purchase_rep_webkit_view_id"
                        model="purchase.order"
                        name="purchase.rep.webkit"
                        file="report_webkit_7/report/purchase_rep_webkit.mako"
                        string="Purchase Extended Webkit"
                        report_type="webkit"
                       webkit_header ="purchase_rep_webk_head" />
            </data>

        </openerp>


 *  Description : 

    This xml file contain the xml id for the report and Header record.

    Inside the header record you can define you Custom Header & Footer
   Css and All the configuration of your Report Page.

4) webkit_report_purchase_order/report/__init__.py

  * Code :

  import purchase_webkit

 * Description :

  This init file initalize the your parser class file.

5) webkit_report_purchase_order/report/purchase_rep_webkit.mako

Code :

`<html>
<head>
<style>
${css}
</style>
</head>

<body>
           %for obj in objects:

<table width="100%" border="0" class="cell_extended">
            <tr class ="table_parent_data">
               <td width="5%" align="center" >
                   <small>Description</small>
               </td>
               <td width="5%" align="left" class="head_bottom_border">
                   <small>Taxes</small>  
               </td>
               <td width="40%" align="center" >
                   <small><b> Date Req.</small>  
               </td>
               <td width="40%" align="right" >
                   <small><b>Qty</b></small>  
               </td>
               <td width="5%" align="left" class="head_bottom_border">
                   <small>Unit Price</small>  
               </td>
               <td width="5%" align="center">
                   <small>Net Price</small>  
               </td>
       </tr>
                  %for line in obj.order_line:
                   <tr class ="table_parent_data">
                <td width="5%" align="center" >
                    ${ line.name or ''}
                </td>
                <td width="5%" align="left" class="head_bottom_border">
                    ${ ', '.join(map(lambda x: x.name, line.taxes_id)) }  
                </td>
                <td width="40%" align="center" >
                    ${ formatLang( line.date_planned, date=True) }
                </td>
                <td width="40%" align="right" >
                    ${ formatLang(line.product_qty )  line.product_uom.name }  
                </td>
                <td width="5%" align="left" class="head_bottom_border">
                    ${formatLang(line.price_unit, digits=get_digits(dp='Product Price') ) }  
                </td>
                <td width="5%" align="center">
                    ${ formatLang(line.price_subtotal, digits=get_digits(dp='Account'), currency_obj=o.pricelist_id.currency_id ) }
                </td>
        </tr>
             %endfor
         </table>
       %endfor

Description :

I just did sample code for purchase or mako file you can customize by your own. this is the sample how you can code in mako template file.
You can easily write your python code in mako template file.


6)  webkit_report_purchase_order/report/purchase_webkit.py

Code :

      from openerp.report import report_sxw

      class purchase_webkit_report(report_sxw.rml_parse):
            def __init__(self, cr, uid, name, context):
       
        super(purchase_webkit_report, self).__init__(cr, uid, name, context=context)

        report_sxw.report_sxw('report.purchase.rep.webkit','purchase.order','addons/webkit_report_purchase_order/report/purchase_rep_webkit.mako',parser=purchase_webkit_report) 

* Descriptoin :


Note :  This file is not necessary but whenever you want to use your own user define method on the report you can define inside this parser class file.



If you have any query or doubt you can ask me on comment.

Monday 4 March 2013

Dictionary Sort by Key in Python

You can easily  sort your dictionary by using collections class in python
Either your key is string or integer, you can sort it.


E.g : Sort Dictionary by key (key in string format)

import collections

dict_data = {'a': 'Anil', 'p': 'pinal', 'c': 'chintan', 'z': 'zinal', 'b': 'Bonil','A':'Atul','h':'Haridk','d':'Dhanvit'}

sorted_dict = collections.OrderedDict(sorted(dict_data.items()))

print "Sorted Dict :::",sorted_dict

O/p : Sorted Dict::: OrderedDict([('A', 'Atul'), ('a', 'Anil'), ('b', 'Bonil'), ('c', 'chintan'), ('d', 'Dhanvit'), ('h', 'Haridk'), ('p', 'pinal'), ('z', 'zinal')])

Returns list of tuples

Same way you can sort your dictionary having integer key.

 dict_data = {2:3, 1:89, 4:5, 3:0}
 
 sorted_dict = collections.OrderedDict(sorted(dict_data.items()))
 
 print "Sorted Dict :::",sorted_dict 

Thursday 28 February 2013

Convert Jalali Date to Gregorian and Gregorian to Jalali Using Python

You are required to download the jdatetime library

you can download from here

Download jdatetime library from here

Click Here Download



Install this library in your system :.

Extract the library folder and reach inside that library folder in command prompt and install .

- apt get install setup.py

Try this script :

from jdatetime import JalaliToGregorian, GregorianToJalali


gregorian_date_obj = JalaliToGregorian(1391,02,21)


gregorian_date =gregorian_date_obj.getGregorianList()

print " gregorian_date  :::::::",gregorian_date


same way you can use the ,


jalali_date_obj =  GregorianToJalali(2012,1,31)


jalali_date = jalali_date_obj.getJalaliList()


print  "jalali_date :::::::::::::",jalali_date