Python-reCaptcha

How to integrate reCaptcha with django?

Following gives you a brief idea of how to integrate reCaptcha to django application

  • First get the corresponding public key and private key from reCaptcha site and keep them in your settings.py
in settings.py
CAPTCHA_PUBLIC = 'XXXXXXXXXXXXXXXXXX'
CAPTCHA_PRIVATE = 'XXXXXXXXXXXXXXXXXX'
  • Render the reCaptcha to corresponding html page
in views.py
recaptcha = captcha.displayhtml(CAPTCHA_PUBLIC) 
    #displayhtml() gives the captcha object to be displayed on html
return render_to_response('demo.html','recaptcha':recaptcha)
in demo.html
<form action="/" method="post" >
{{recaptcha|safe}}
        <button class="submit" type="submit">Submit</button>
</form>
  • Validate the challenge field and response fields..
in views.py
capresponse = captcha.submit( request.POST.get('recaptcha_challenge_field'),
                              request.POST.get('recaptcha_response_field'),
                              CAPTCHA_PRIVATE,
                              request.META.get('REMOTE_ADDR'))
'''checks if the catpcha is valid or not(challenge field and response fields    are equal or not '''
if capresponse.is_valid:
     do_some_work()
else:
     return HttpResponse('wrong captcha text')
Google+FacebookTwitterLinkedInRedditEmail

Get tweets with Javascript

Due to change in twitter API, its been hard to get tweets from twitter to your site using javascript.

We got new API version 1.1 and the old version 1 is not working any more, so we have to live with what ever 1.1 offers.

This version of API supports widgets to keep in our sites, but thats not enough if we want to customize tweets using javascript to fit our sites look and functionality. We want json of the tweets, then we can do what ever we want with those.

Its simple as creating a widget in twitter and then we get tweets from it to form json.

  1. Go to www.twitter.com and sign in then go to your settings page.
  2. Go to “Widgets” on the left hand side.
  3. Create a new widget as you like.
  4. Check “exclude replies” if you dont want replies in results.
  5. Now go back to settings -> widgets page, you will see the widget you just created. Click edit.
  6. Now look at the URL in your web browser, you will see a long number like this: 441110970094473216.
  7. Use this as your ID below!
var tw = function () {

    return {
        fetch: function (twid, tc, cbf) {
            (tweets_count=tc, cbfunc = cbf,  c = document.createElement("script"), c.type = "text/javascript", c.src = "//cdn.syndication.twimg.com/widgets/timelines/" + twid + "?&lang=en&callback=tw.callback&suppress_response_codes=true&rnd=" + Math.random(), document.getElementsByTagName("head")[0].appendChild(c))
        },
        callback: function (e)
        {
        	var c = document.createElement("div");
            c.setAttribute("id", "twitter-stage");
            c.innerHTML = e.body;
            c.style.display="none";
            document.body.appendChild(c);

        	var tweet_json = [];    
			usr_imgs = document.querySelectorAll('#twitter-stage div ol.h-feed li div.header div a.u-url.profile img.u-photo.avatar');
			usr_names = document.querySelectorAll('#twitter-stage ol li div.header span.full-name span');
			usr_screen_names = document.querySelectorAll('#twitter-stage ol li div.header a.u-url.profile span b');

			tweets = document.querySelectorAll('#twitter-stage ol li div.e-entry-content p.e-entry-title');
			dates = document.querySelectorAll('#twitter-stage ol.h-feed li div.header a time');
			tweetids = document.querySelectorAll('#twitter-stage ol.h-feed li div ul li:first-of-type a');

			for(i=0;i<tweets_count ;i++)
			{
				var tobj = {};
				tobj.img = usr_imgs[i].src; 
				tobj.name = usr_names[i].innerHTML;
				tobj.screen_name = '@' + usr_screen_names[i].innerHTML; 
				tobj.tweet = tweets[i].innerHTML;
				tobj.date = dates[i].innerHTML;
				tobj.id = tweetids[i].href.split('=')[1];

				tweet_json.push(tobj);
			}
			document.body.removeChild(c)
            cbfunc(tweet_json);
        }
    }
}();

Now include the file and use it as following

function tweets(tws){
        $.each(tws, function(i,o){
            // You can do as you wish with the values in 'o' objects.
            console.log(o);
        }); 
    }
// this will fetch tweets of the given widget id and pass the tweets to tweets function
tw.fetch('441110970094473216', 20, tweets);

This is much straight forward approach, you can extend it as you like.

Google+FacebookTwitterLinkedInRedditEmail

AngularJS Form Validation [Built-in Directives]

 

A few HTML 5 attributes and angular directives both gives the same result. However, angualrJS provides 2 way binding from model to view, but its not the case for HTML5. Example: HTML 5 attribute is required, AngularJS directive is ng-required both gives the same output.

AngularJS builtin directives:

required: html5 attribute

ng-pattern: for the regular expression

ng-minlength: condition that the string length must be greater than the minlength

ng-maxlength:condition that the string length must be less than the maxlength

<input type=”text” ng-model=”{string}”, name=”{string}”, required, ng-required=”{string}”, ng-minlength=”{string}”, ng-maxlength=”{string}”, ng-pattern=”{string}”,ng-change=”{string}”>

AngularJS form properties:

<form name=”NewForm” novalidate ng-submit=”Myfunction()”>

<input type=”text” ng-model=”username” name=”username”>

<input type=”email” ng-model=”emailid” name=”emailid”>

<button type=”submit”>Submit</button>

</form>

[formName].[inputFieldName].property

NewForm.username.$valid: checks based on our own validation rules whether the field is valid.

NewForm.username.$invalid: checks based on our own validation rules whether the field is invalid.

NewForm.username.$dirty: checks the field has been used, then its true

NewForm.username.$pristine : checks the field not yet used, then its true

NewForm.username.$error: is a object that contains all the form field names.

Novalidate: prevents the default html5 validation

Note: Its a basic AngularJS form validation.Well, in the next part you would see custom one’s.

Google+FacebookTwitterLinkedInRedditEmail

Django on GAE(google app engine)

What is GAE?

Google App Engine (often referred to as GAE or simply App Engine) is a platform as a service (PaaS) cloud computing platform for developing and hosting web applications in Google-managed data centers. Applications are sandboxed and run across multiple servers.App Engine offers automatic scaling for web applications—as the number of requests increases for an application, App Engine automatically allocates more resources for the web application to handle the additional demand.

We can upload any kind of web applications developed in any programming language like Java,Python,PHP…. etc.,Here in this blog let us see how to upload a simple Django application into the Google App Engine.

Simple procedure to upload a Simple django applicaion to GAE:

STEP 1:First create a simple PyDev Google App Engine Project by following the steps given below.

  1. Go to File > New > Project
  2. Choose PyDev Google App Engine Project under PyDev folder.
  3. Choose your own project name.
  4. If the Python interpreter for Eclipse has not been configured, you would see the link Please configure an interpreter in the related preferences before proceeding.
  5. Clicking the link will lead you to the Python Interpreters set up. ClickAuto Config. The system will help add the necessary paths to your PythonPath. Just click OK to proceed.
  6. Choose the Default interpreter and click Next.
  7. Browse your installed Google App Engine sdk directory.
  8. Click OK to include the recommended packages and then click Next.
  9. Fill in your registered App ID. (given as application identifier while creating the app)
  10. Choose one of the given starter template and click Finish.

STEP 2:Creating a Django Project folder:

  • Create a Django Stand Alone application to project folder of the Django on App Engine application the file manage.py and the folder Project_Name including the inside files __init__.py, settings.py, urls.py.
  • Create a new file named main.py in the project folder.

Your application folder should have the simple structure as below:

rsz_screenshot_from_2014-02-07_102507

With this folder structure, we would modify the individual files accordingly as explained below.

main.py:

  • main.py Include the below content in your file. This is to define the WSGI for the web server.
import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

settings.py:

  • Remove the settings for DATABASES and WSGI_APPLICATION because we would be using Google App Engine datastore and have defined our WSGI in main.py above.
  • Change the setting for ROOT_URLCONF to the correct ‘Project_Name.urls’.
ROOT_URLCONF = 'Project_Name.urls'

manage.py:

  • Change the setting for DJANGO_SETTINGS_MODULE to the correct “Project_Name.settings”.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project_Name.settings")

app.yaml:

  • Change the runtime to python27 and add threadsafe: true to inform Google App Engine that we are running Python 2.7.
  • Change the handlers script to main.application because it is where we define our WSGI.
  • Include Django with the corresponding version in the list of libraries because we are going to use it here.
  • Set the env_variables – DJANGO_SETTINGS_MODULE to ‘Project_Name.settings’ so that the application can locate where our Django settings.py is.
application: django-demoapp
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:

- url: /.*
script: main.application

libraries:

- name: django
version: "1.4"

env_variables:
DJANGO_SETTINGS_MODULE: 'Project_Name.settings'

STEP 3:Creating your Django application folder:

Creating a Simple Application to show “Hello MicroPyramid”

To create our application, we would proceed with the following steps:

  1. Create the application folder
  2. Defining the models(if any)
  3. Defining the views
  4. Defining the templates(if any)
  5. Defining the static file folder(if any)
  6. Defining the urls
  • Create the Application Folder

Create an application folder In the root project folder (together with main.py and manage.py and at the same level with Project_Name folder). A folder with an __init__.py is created as a result.

  • Defining the Views

we will define our requierd views here.Here is the simple view that returns a simple Httpresponse to print “Hello MicroPyramid”.

from django.http import HttpResponse

def home(request):
    return HttpResponse("hello welcome to google app engine")
  • Defining the URLs

We would define a URL to serve the  view home. We first modify the urls.py file in the Project_Name package to direct all requests to your application:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^', include('firapp.urls')),
)

We would then create another PyDev module urls (which is just a fileurls.py) in the firapp package to process all requests related to your application:

from django.conf.urls.defaults import *
from firapp.views import home

urlpatterns = patterns('',
    (r'^home/$', home),

)

Our application has been completed! The final folder structure would look like below:

rsz_screenshot_from_2014-02-07_103453

STEP 4:To Test Run Your Application

Our application would run on the bundled Google Appp Engine development server.

  1. Right click on the Project Name
  2. Select Run As > PyDev: Google App Run
  3. According to the console, your application can now be accesed at http://localhost:8080 .
  4. Done!

STEP 5:To Deploy Your Application

These steps would deploy your application to the real system.

  1. Right click on the Project Name
  2. Select PyDev: Google App Engine > Upload
  3. Input your email and password in the Send to prompt when prompted.
  4. Your application is now available online at http://your-app-id.appspot.com/
  5. Done!
Google+FacebookTwitterLinkedInRedditEmail

FABRIC – LEARNING PART 2

Okay, this is day two and i want to put fabric to develop some thing meaningful.
Lets start with amazon EC2.

I want to develop an interactive script where i get to choose ec2 region, ec2 flavour etc.

being blessed with python we have boto, a swiss army knife for amazon web services.

i assume you have all set (aws account, security group, key pair, access key id, secret access key)

so this is not going to be fabric but i want this on the way as we need to create server then do stuff with faric.

from fabric.api import *
from fabric.colors import green as _green, yellow as _yellow
import boto
import boto.ec2
import time

def create_ec2():
	ubuntu_images = {	"ap-northeast-1":"ami-bfc0afbe",
						"ap-southeast-1":"ami-92aef9c0",
						"ap-southeast-2":"ami-57f16f6d",
						"eu-west-1":"ami-dea653a9",
						"sa-east-1":"ami-4da10150",
						"us-east-1":"ami-951524fc",
						"us-west-1":"ami-b0784af5",
						"us-west-2":"ami-36d6b006",
					}
	ec2_region = ""
	ec2_key = "your Access Key ID"
	ec2_secret = "Secret Access Key"
	ec2_key_pair = "key pair name you created in the region you will select in this program"
	ec2_security = ("default",)
	ec2_instancetype = "m1.small"
	regions = boto.ec2.regions()

	i=0
	for r in regions:
		r = str(r)
		if r[r.index(':')+1:] =="us-gov-west-1":
			continue

		print str(i) + " : " + r[r.index(':')+1:]
		i += 1

	i = raw_input("your choice : ")
	ec2_region = str(regions[int(i)])
	ec2_region = ec2_region[ec2_region.index(':')+1:]

	conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=ec2_key, aws_secret_access_key=ec2_secret)
	print(_green("connected to : "  + ec2_region))
	print ubuntu_images[ec2_region]
	
	reservation = conn.run_instances(ubuntu_images[ec2_region],
						key_name = ec2_key_pair,
						security_groups =  ec2_security,
						instance_type = ec2_instancetype
					)
	instance = reservation.instances[0]
	while instance.state == u'pending':
		print(_yellow("Instance state: %s" % instance.state))
		time.sleep(2)
		instance.update()
	print(_green("Instance state: %s" % instance.state))

	print(_green("Instance created succeffully!"))

	print(_green("Allocating new elastic ip..."))
	ip = conn.allocate_address()
	print(_green("Attaching elastic ip to instance..."))
	ip.associate(instance_id=instance.id)

	print(_green("Public dns: %s" % instance.public_dns_name))

	print "Instance created and attached to public ip : " + ip.public_ip
	return

now the out put is…

hotice@ashwin-ws:~$ fab create_ec2
0 : ap-southeast-1
1 : ap-southeast-2
2 : us-west-2
3 : us-east-1
4 : us-west-1
5 : sa-east-1
6 : ap-northeast-1
7 : eu-west-1
your choice : 3
connected to : us-east-1
ami-951524fc
Instance state: pending
Instance state: pending
Instance state: pending
Instance state: pending
Instance state: pending
Instance state: pending
Instance state: running
Instance created succeffully!
Allocating new elastic ip...
Attaching elastic ip to instance...
Public dns: ec2-54-196-108-1.compute-1.amazonaws.com
Instance created and attached to public ip : 54.204.13.213

okay… this is not fabric, this is just python boto script. as i said earlier, i will do the fabric stuff in next of this series…

Google+FacebookTwitterLinkedInRedditEmail