Tuesday, October 4, 2011

Setting constraints on Registration form


We have already discussed about setting machine generated mails up on user registration. Now think about setting constraints on the registration form. We mainly use JavaScript for that purpose. If the user forgot to enter first name in the registration form, we can prompt him regarding that.

Different types of constraints can be done on the registration form fields. To check whether first name or second name is not filled, we need to check whether it is blank or not. Following lines of code can be used for that,

var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }

myForm is the form name and fname is the name of textbox for first name. ["myForm"]["fname"].value is used for getting the value from textbox named fname from the form myForm. In the case of checking a radio button, codes are different. In the case of Gender, we need to check whether the radio buttons are checked or not.

for (var i=0; i < document.myForm.gender.length; i++)
   {
   if (document.myForm.gender[i].checked)
      {
          x = document.myForm.gender[i].value;
      }
   }
if (x!='male' && x!='female')
   {
    alert("Gender must be selected");
    return false;
   }

The above code is used for checking the radio buttons. The first if condition is used for getting the value from the radio buttons. Next if condition is used for checking whether it is not male/female.

Now we can check whether the entered mail id is of a valid format. Mail id with a format abc@xyz.com will be accepted. Otherwise the user need will be prompted about invalid mail id.

var x=document.forms["myForm"]["email"].value
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }

Check the above code. It will check whether ‘@’ comes at the beginning or ‘.’ comes atleast 2 letters after ‘@’ or the mailed ends at 2 letter after the ’.’

Now let’s check the password field. We have to check 3 conditions here. First one is to check whether password is entered or not. Second one is to check Password has atleast 8 characters. Then we have to check the entered password and confirm password fields match with one another.

var x=document.forms["myForm"]["pswd1"].value
var y=document.forms["myForm"]["pswd2"].value
if (x==null || x=="")
  {
  alert("Password must be filled out");
  return false;
  }
if (x.length<8)
  {
  alert("Password must be of atleast 8 characters");
  return false;
  }
if (x!=y)
  {
  alert("Passwords doesn't match");
  return false;
  }

I think there is no need to explain these codes. Now let’s think about a valid date. There are lots of conditions that must be filled out to get a valid date. Date must be entered. Date must not exceed their higher values. Leap years must be checked.

var x=document.forms["myForm"]["dd"].value
var y=document.forms["myForm"]["mm"].value
var z=document.forms["myForm"]["yyyy"].value
if(x<1 || x>31)
  {
    alert("Not a valid date");
    return false;
  }
if(y<1 || y>12)
  {
    alert("Not a valid Month");
    return false;
  }
if(z<1940 || z>2005)
  {
  alert("Not a valid year range");
  return false;
  }

First checks whether the entered dates exceeds the common limits. After entering dd, mm and yyyy values, we need to check the following constraints also.

if(z%400 ==0 || (z%100 != 0 && z%4 == 0))
  {
    leap=1;
  }
else
  {
    leap=0;
  }
if(leap==1 && y==2)
  {
    if(x<1 || x>29)
    {
    alert("Not a valid date");
    return false
    }
  }
if(leap==0 && y==2)
  {
    if(x<1 || x>28)
    {
    alert("Not a valid date");
    return false;
    }
  }

The above codes check the leap year conditions. The code given below checks the months with 30 days and 31 days,

if(y==1 || y==3 || y==5 || y==7 || y==8 || y==10 || y==12 )
  {
    if(x<1 || x>31)
    {
    alert("Not a valid date");
    return false;
    }
  }
if(y==4 || y==6 || y==9 || y==11 )
  {
    if(x<1 || x>30)
    {
    alert("Not a valid date");
    return false;
    }
  }

That’s all about the JavaSript codes used. The entire JavaScript is written inside a function called validateForm(). Just have a look at the form tag in the html code.

<form name="myForm" onsubmit="return validateForm()"  method="POST">

Don’t forget to add the JavaScript function name in the onsubmit attribute of form.
Hope you got a overall idea about the registration form constraints.

Thanks

AJAY

Session handling in Python


My project has registered users and I need to keep login accounts for them. It is very important that I need to handle the sessions of each user, efficiently. Session handling in python is not a big deal, but for a beginner it will be difficult to find correct documentation for it. So I think it will be useful to those people who are working with the same tools. We need to set the following lines of code outside all classes,

store = web.session.DiskStore('sessions')
if web.config.get('_session') is None:
        session = web.session.Session(app,store,initializer={'login': 0, 'privilege': 0, 'user':'anonymous', 'loggedin':False})
        web.config._session = session
else:
        session = web.config._session

We need to first set the user as anonymous and loggedin as false. Then we need to change these values upon the sign in operation. When a user sign in to the wiki using his mail id and password, we need to add the following lines with that operation,

session.loggedin = True
session.email = fi.email
session.user = fi.fname

You can decide whether the session.user has to store mail id or first name. It is important that session.user holds the login id. In my project session.email holds the unique login id.

Now we can think about sign out operation. On sign out, we need to destroy the session of that particular user. Her we got the code,

session.kill()

This line will kill the current session and now the user needs to log in again. That’s all about the basic session handling. If you want to know more about the session you can refer webpy site.

Thanks

AJAY

Machine generated mails

We have seen many sites, which send confirmation mails on registration. They are the system generated mails and it will not send any reply if we send mails to that address. I also think about setting a machine generated mail for my git wiki. If a user register into git wiki or he creates an article, the machine will generate a mail and send it to him.

We need to import smtplib for this.

import smtplib

We also need to set some information in our python code basically regarding the smtp server,port, mail id, password etc. I used a gmail id for this purpose. I created a mail id noreplygitwiki@gmail.com. Now I need to set the smtp server of gmail and its port number. Its smtp server address is smtp.gmail.com and port number is 587. Use the following code outside all classes.

web.config.smtp_server = 'smtp.gmail.com'
web.config.smtp_port = 587
web.config.smtp_username = 'noreplygitwiki@gmail.com'
web.config.smtp_password = '12345678'
web.config.smtp_starttls = True

You need to enter your mail id and password instead. Now it is very simple to generate a mail. Just use the following code wherever or whenever you need,

web.sendmail('noreplygitwiki@gmail.com', session.email, subject, message)

Here first parameter is the sender email id. Second parameter is destination mail address. Third one is the email subject and the last one is the message content. You need to set the message content very carefully. Show your creativity here. Because it decides the beauty of your message. I used the following code for mailing the user on registration.

message = ("Dear %s,\n\n\t Thanks for joining our site.\n\t Your Account Details : \n\n\t\t\t username = %s\n\t\t\t password = %s\n\n\t Keep updated with regular articles.\n\n\t Thank you.\n\t Admin.\n\t Git Wiki\n\t\t\t\tBlog : http://ajaysoman.blogspot.com/" % (fi.fname,fi.email,fi.pswd1))

It will be displayed as,


Dear Ajay,

Thanks for joining our site.
Your Account Details :

username = ajaysoman007@gmail.com
password = 12121212

Keep updated with regular articles.

Thank you.
Admin.
Git Wiki
Blog : http://ajaysoman.blogspot.com/


You can try for better mail formats. Try for it in your projects.

Thanks

AJAY

Git in Python using Subprocess


I already introduced you the DVCS used in my project, Git. Git is a powerful open source tool which is used for the version control system. It is developed by the Linus Torvards who has already gifted us the powerful kernel of Linux. In this post, I want to describe you how I integrated git with python.

We need to import subprocess module for this. We are calling the git commands using the subprocess.

import subprocess
from subprocess import call

Subprocess allows us to call the command that run in terminal. We know the command for displaying files in the current directory is “ls”. For calling “ls” from the python program using the subprocess module,

subprocess.Popen(["ls"],cwd = accpath)

cwd is the current working directory. We need to specify the path of the current directory like /home/ajay/Documents. It can be assigned to a variable like accpath.

dirpath = os.path.dirname(os.path.realpath('articles'))
accpath = dirpath + '/articles'

In my project I need to initialize the git repository first. So I need to write the following code,

subprocess.Popen(["git","init"],cwd = accpath)

Now I need to write the proper codes for calling the git commands, whenever an article is created/modified. When an article is created, the following codes are used to add the modified files and to commit them.

subprocess.Popen(["git","add",title.lower()],cwd = accpath)
subprocess.Popen(["git","commit","-m","'committed'"],cwd = accpath)

title.lower() is used save the article name in small letters.

Now we need to save the details of hash codes of particular commits, because we need that hash code in order to perform rollbacks in future. So we need to extract the hash code from each commit. Git log command helps to see the commits and its hash codes. "git log -p -1” command displays the last commit and its hash code. We need to save that message in a file. Use the following code for that.

p = subprocess.Popen(["git","log","-p","-1"], cwd = accpath, stdout = subprocess.PIPE,)
stdout_value = p.communicate()[0]
t1 = repr(stdout_value)

Now “t1” has the message which is displayed by entering "git log -p -1”. We need to extract the hash code from it using the regular expressions. I will write post about regular expression soon.

The same commands can be used whenever an article is modified. I will post more issues I faced during the project development.

Thanks

AJAY

Monday, October 3, 2011

My Academic Project – Git Based Wiki Implementation


As my university curriculum insists, I need to do an individual project in the end of my master of computer application course. I decided to do it completely using the open source technologies. And my project topic is “Git based wiki implementation”. I am not a fool to say that my wiki is more efficient than the existing Wikipedia. Existing Wikipedia is the brain work of hundreds of experienced software engineers. Then what’s about my wiki?

The main point about my project is, the efficient distributed version control system, Git is used here. Why a version control system is needed in a wiki? We know, wiki is basically an information resource where an efficient content management system is established. Any registered user has the privilege to edit the article. If a user edits an article and adds some misleading/unwanted/abusing information, then we need to retain the previous published version of the particular article. So it is very important that, a wiki needs an efficient version control system. Git is a distributed version control system with an emphasis on speed.

Python is used as the back end. Basic HTML/JavaScript/CSS is used for the interface. Here webpy framework is used in the development of my project. Webpy has a built in server. SQLite3 database is used for saving user information. Nginx server can be used for the application on implementation.

My project uses only the open source tools for its development and gives the freedom to any one of the world to modify it under GPL license. Wiki software (Wiki engine or wiki application) is collaborative software that runs a wiki, i.e., a website that allows users to create and collaboratively edit web pages using a web browser. Git is more powerful tool to implement the Wiki system.

The application has following type of users,

Administrator : Administrator have the privilege to mail all the registered users, rollback all articles etc.
Registered users : Registered users can  create articles and edit them.
Author : Author is registered user who can rollback his articles.
Viewers : Viewers are the normal users who can only view the articles.

I will add more posts about the project in the coming days.

Thanks

AJAY

Saturday, October 1, 2011

Teeny URL


Google has many services like plus, gmail, orkut, blogger which is familiar to the youth. But many of them are unaware of Google’s App Engine service. App engine allows the developers to host their applications online. Google gives free domain names to us. Python and Java are the current supporting platforms.

When I heard about this service, I eagerly started a url shortening application in python. Many of our urls, especially blog links and articles are large and bulky. It is difficult to use them on twitter and SMS where character limit is a big problem. So I think about a url shortening application for reducing the length of the large urls. The main advantage of shortened url is, it can be used anywhere on the web instead of the original url. Another import fact is every large url will get a unique shortened url. So it will not let the user into any problem.

Here I used python as the back end. Webapp framework is used and the database is Datastore. Datastore is a database by Google and it is different from other traditional databases. It uses an object oriented database management system. HTML and CSS is used for the interface.

url for Teeny URL application is,


Some screenshots of the Teeny URL application is given below,


































You can download the source code also. Click on the tab given below.


If you have any doubts with the codes, you can also read my posts regarding the source code of the Teeny URL. Links for my Teeny URL posts are,


Google App Engine - An Introduction
Creating application in Google App Engine
Two main classes in Teeny URL
Implementing application on App Engine

Thanks

AJAY

Implementing application on App Engine server



I have explained you about the source code in my previous posts. Now I will explain you how to run this in local machine and how to upload to appengine.

We need to keep the google_appengine folder and our teenyurl folder in same directory. After that we need to run the following command in order to run the application in our localhost.

google_appengine/dev_appserver.py teenyurl/

We can now open the browser and type the localhost address to view the application. If you want to make the application online, you need to first register for a free available domain name. Then you can upload the project by typing the code given below,

google_appengine/appcfg.py update teenyurl/

This will ask your gmail address to which the Google appengine domain name is associated. You need to enter your Google account password also. After that it will be deployed on appengine server. Now you can type the url of your application in the browser to access the application. My application’s url is 


If you want to upload an updated version, then change the version number in app.yaml file from 1 to 2. Then 2 versions will be available in the appengine dashboard. You need to change the default version to 2 in order to see the updated version. Versions tab will help you to manage the various versions. You can also see the various versions by prefixing version number on appspot url. Like below,


Dashboard will show you the daily quotas. Datastore viewer will help you to view the data by querying.

I feel nice to work with Google’s apengine service and thinking about developing other appengine applications also. You can host upto 10 applications using your one Google account. Explore the world of appspot projects and get inspired from those applications.
Let’s do an appengine project dude!!!

Thanks

AJAY

Two main classes in Teeny URL


I have explained that I have 2 main classes- Home and TeenyURL – in my application. Lets start with Home class.

Home class

This class has two basic functions, get() and post(). In the get(), we need to render the index.html file. When our application is executed, index file will be loaded first. We need to pass some parameters/variables to the index.html file. For that we use the following code.

template_values = {
            'title': "TeenyURL",
}

Now the template_values hold the string value “TeenyURL” which will be replaced by the variable ‘title’ in the index.html file.

<html>
<head>
<title> {{title}} </title>

This is the code in the index.html file. The ‘title’ variable is written inside {{}} so  that the compiler will understand it as a variable. The ‘title’ is replaced with “TeenyURL”. To render the index.html, we need to specify the path to the index.html and its parameters (ie., template_values). Look at the below code,

path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))

Thus our index.html file is loaded and the user will see interface to enter the long url. When the user inputs some url and then submits, the post() of the Home class works.

url = self.request.get('url')

This code is used to get the value from the form where the user has given his input. Think about a situation where a user inputs his url and captures his short url and the again inputs the same large url. In that situation we need to provide the same short url which is provided earlier. So we need to first check, whether the submitted url is already in the datastore.  The following code is used for that.

x = db.GqlQuery("SELECT * FROM Data WHERE url=:1",url)
count = x.fetch(1)
z = len(count)
if (z>0):
                turl = count[0].turl

If the large url is a new one to datastore, we need to create a new short url for it.

while y>0 :
                word = "".join(random.choice(char_array) for i in range(4))
                x = db.GqlQuery("SELECT * FROM Data WHERE code=:1",word)
                count = x.fetch(1)
                y = len(count)

Here also checks whether the random generated code is already generated before for other large urls. I stored the large url and the corresponding short url along with the 4 letter code in the datastore. We need to create an object of the Data class. The below code is used to enter the values to the datastore,

data = Data()
data.url = url
data.code = word
data.turl = turl
data.put()

The below code is used to render the index.html file with original url and its corresponding short url.

template_values = {
            'title': title,
            'url' : url,
            'teenyurl' : turl,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))

TeenyURL class

When anyone uses this short url, I need to redirect it to its original url. That is the purpose of TeenyURL class. The following code is used for that,

x = Data.all()
x = db.GqlQuery("SELECT * FROM Data WHERE code=:1" , path)
count = x.fetch(1)
ourl = count[0].url
self.redirect(ourl)

In order to efficiently call the corresponding classes, I defined the templates paths as below,

application = webapp.WSGIApplication( [('/',Home),
                              ('/(.+)',Teenyurl)],
                              debug=True)

Now I have explained about all the code. In my next post I will explain you how to run the application in local machine and how to upload it to the appengine.

Thanks

AJAY