Tag Archives: Python

Command Line Arguments and Interprocess Communication Simplified

aim to illustrate what command line arguments are to my young brother.

below is a c program which adds numbers obtained from command line arguments

#include<stdio.h>
#include<ctype.h>

int main(int argk, char** argv)
{
	int a,b;
	a = atoi(argv[1]);
	b = atoi(argv[2]);
	printf("The result is %dn",a+b);
	return 0;
}

this is how you use command line arguments

gcc file.c
./a.out 10 20
The result is 30

illustrating interprocess communication, below python program communicates with above c program

from subprocess import call
call(["./a.out", "10","20"])

executing the python program, obtaining result from the c program using command line arguments

python file2.py
The result is 30

Django new model and forignkey User/Auth with modelform

forms
modelforms, save(), exclude, commit=False
model field options, field types
models
models gender field

models.py

class Patient(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    doctor = models.ForeignKey(User)
    
    def __unicode__(self):
        return self.name

forms.py

class RegisterPatientForm(ModelForm):
     class Meta:
         model = Patient
         exclude = ('doctor',)

urls.py

     (r'^register/$', register),
     (r'^list/$', list),

views.py

@login_required
def register(request):
    if request.method == 'POST':
        form = RegisterPatientForm(request.POST)
        if form.is_valid():
            new_patient = form.save(commit=False)
            new_patient.doctor = request.user
            new_patient.save()
            return HttpResponseRedirect("/list/")
    else:
        form = RegisterPatientForm()
    return render_to_response("patient/register.html", 
    {'form': form,},
    RequestContext(request))

def list(request):
    patients = Patient.objects.filter(doctor=request.user)
    return render_to_response("patient/list.html",locals())

templates/patient/register.html

{% extends "base.html" %}

{% block title %}<h1>Register New Patient</h1>{% endblock %}

{% block content %}
  <form action="" method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="Create new patient">
  </form>
{% endblock %}

templates/patient/list.html

{% extends "base.html" %}

{% block title %}<h1>Patient List</h1>{% endblock %}

{% block content %}
<table>
    {% for patient in patients %}
        <tr><td>{{patient.name}}</td><td>{{patient.age}}</td><td>{{patient.gender}}</td></tr>
    {% endfor %}
</table>
{% endblock %}

django search form

forms
query reference
templates

urls.py

     url(r'^$', search),

views.py

def search(request):
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = "Please submit a search term."
        elif len(q) > 20:
            error = "Please submit a search term 20 char or less"
        else:
            docs = Doctor.objects.filter(name__icontains=q)
            return render_to_response('search_results.html',locals())
    return render_to_response('search_form.html',locals())

search_form.html

<html>
<head>
    <title>Search</title>
</head>
<body>
    {% if error %}
        {{error}}
    {% endif %}
    <form action="" method="get">
        <input type="text" name="q">
        <input type="submit" value="Search">
    </form>
</body>
</html>

search_results.html

<html>
<body>
<p>Found {{ docs|length }} doc{{ docs|pluralize }}.</p>
<table>
{% for doc in docs %}
<tr><td>{{doc.name}}</td><td>{{doc.email}}</td></tr>
{% empty %}
No doctors matching
{% endfor %}
</table>
</body>
</html>

post
—-

from django.template import RequestContext
def search(request):
    if 'q' in request.POST and request.POST['q']:
            q = request.POST['q']
            docs = Doctor.objects.filter(name__icontains=q)
            return render_to_response('search_results.html',locals())
    return render_to_response('search_form.html',locals(),RequestContext(request))
    <form action="" method="post">
        {% csrf_token %}
        <input type="text" name="q">
        <input type="submit" value="Search">
    </form>

Tastypie

getting started

install mimeparse
install setuptools
install dateutil

install django-tastypie

copy the dir

patientrecords/api.py

from tastypie.resources import ModelResource
from patientrecords.models import Doctor

class DoctorResource(ModelResource):
    class Meta:
        queryset = Doctor.objects.all()
        resource_name = 'doctor'

urls.py

from django.conf.urls import patterns, include, url
from patientrecords.api import DoctorResource
from tastypie.api import Api

patient_api = Api(api_name='patient')
patient_api.register(DoctorResource())

urlpatterns = patterns('',
     (r'^api/', include(patient_api.urls)),
)

Django Model

models

python manage.py startapp patientrecords

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_patientrecords',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}
INSTALLED_APPS = (
    'patientrecords',
)
from django.db import models

class Doctor(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()
    
    def __unicode__(self):
        return self.name

python manage.py validate

python manage.py sqlall patientrecords

python manage.py syncdb

from patientrecords.models import Doctor
d = Doctor(name="Suresh Kumar N",email="123@gmail.com")
d.save()
Doctor.objects.all()
Publisher.objects.filter(name__contains="press")
Publisher.objects.order_by("name")
Publisher.objects.order_by('name')[0:2]
Publisher.objects.order_by('-name')[0]
Publisher.objects.filter(id=52).update(name='Apress Publishing')
Publisher.objects.all().update(country='USA')
Publisher.objects.filter(country='USA').delete()
Publisher.objects.all().delete()

Django Project

setup
templates

python C:Django-1.4.1buildlibdjangobindjango-admin.py startproject mysite

views.py

from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
    current_date = datetime.datetime.now()
    return render_to_response('current_datetime.html', locals())

urls.py

url(r'^$', 'patientrecordsweb.views.current_datetime'),

settings.py

import os
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\','/'),
)

templatescurrent_datetime.html

<html><body>It is now {{ current_date }}.</body></html>

Python-MySQL CGI

code from django book first chapter
install python, django, mysql, apache & python-mysql as in link

usefull link

#!C:Python27python.exe -u
#!/usr/bin/env python

import MySQLdb

print "Content-Type: text/htmln"
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect('127.0.0.1','pma','123456','test')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")

for row in cursor.fetchall():
    print "<li>%s</li>" % row[0]

print "</ul>"
print "</body></html>"

connection.close()