Friday, 6 May 2016

Packages that make you developing apps in django awesome that make developing django application awesome

Introduction

There are many reasons why I like developing web applications with Python and Django but the main one is the awesome community and projects around the language and framework. Every time I search for something there’s always a Django or Python project available to make my life easier.

Here’s an incomplete list of Python and django related packages that I have used or I’m planning to test. This might help someone starting out to get an idea of how awesome is to work with this packages.


Packages are

Django Debug Toolbar

https://github.com/dcramer/django-debug-toolbar
The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/response and when clicked, display more details about the panel’s content.

South

http://south.aeracode.org
South brings migrations to Django applications. Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications.

Django Paypal

https://github.com/johnboxall/django-paypal
Django PayPal is a pluggable application that implements with PayPal Payments Standard and Payments Pro.

Django Avatar

https://github.com/ericflo/django-avatar
A reusable django application for handling Avatars.

Fabulous

https://github.com/gcollazo/Fabulous
Shameless plug. I made this. It deploys django apps to Amazon EC2 with ONE command.

Django Exceptional

https://github.com/zacharyvoase/django-exceptional
A Django client for Exceptional (www.getexceptional.com)

Django Easy Maps

https://bitbucket.org/kmike/django-easy-maps
This app makes it easy to display a map for given address in django templates. No API keys, manual geocoding, html/js copy-pasting or django model changes is needed.

Django Extensions

https://github.com/django-extensions/django-extensions
It provides a plethora of useful manage.py commands, and a couple other little goodies as well.

Pinax

https://github.com/pinax/pinax
Django-based platform for rapidly developing websites

Django CMS

https://github.com/divio/django-cms
A Django application for managing hierarchical pages of content, possibly in multiple languages and/or on multiple sites.

Django Sentry

https://github.com/dcramer/django-sentry
Sentry provides you with a generic interface to view and interact with your error logs. By default, it will catch any exception thrown by Django and store it in a database.

Django Haystack

https://github.com/toastdriven/django-haystack
Haystack provides modular search for Django. It features a unified, familiar API that allows you to plug in different search backends (such as Solr, Whoosh, Xapian, etc.) without having to modify your code.

Django Celery

https://github.com/ask/django-celery
Provides Celery integration for Django; Using the Django ORM and cache backend for storing results, autodiscovery of task modules for applications listed in INSTALLED_APPS, and more.


Django-tastypie

https://github.com/toastdriven/django-tastypie
Creating delicious APIs for Django apps since 2010.

python-social-auth 

https://github.com/omab/python-social-auth
Django social authentication made simple.

django-filter

https://github.com/alex/django-filter
Django-filter is a reusable Django application for allowing users to filter queryset dynamically.

django-mingus

https://github.com/montylounge/django-mingus
A Django blog engine leveraging reusable apps for all its features.

django-devserver

https://github.com/dcramer/django-devserver
A drop in replacement for Django’s built-in runserver command. Features include: An extendable interface for handling things such as real-time logging. Integration with the werkzeug interactive debugger. An improved runserver allowing you to process requests simultaneously.

FeinCMS

https://github.com/matthiask/feincms
FeinCMS is an extremely stupid content management system. It knows nothing about content — just enough to create an admin interface for your own page content types. It lets you reorder page content blocks using a drag-drop interface, and you can add as many content blocks to a region (f.e. the sidebar, the main content region or something else which I haven’t thought of yet). It provides helper functions, which provide ordered lists of page content blocks. That’s all.

django-schedule

https://github.com/thauber/django-schedule
A calendaring/scheduling application, featuring: one-time and recurring events, calendar exceptions (occurrences changed or cancelled), occurrences accessible through Event API and Period API, relations of events to generic objects, ready to use, nice user interface, view day, week, month, three months and year and project sample which can be launched immediately and reused in your project.

django-mailer

https://github.com/jtauber/django-mailer
A reusable Django app for queuing the sending of email

django-notification

https://github.com/jtauber/django-notification
Many sites need to notify users when certain events have occurred and to allow
configurable options as to how those notifications are to be received. The project aims to provide a Django app for this sort of functionality. This
includes: submission of notification messages by other apps, notification messages on signing in, notification messages via email (configurable by user) and notification messages via feed.

django-pagination

https://github.com/ericflo/django-pagination
A set of utilities for creating robust pagination tools throughout a django application.

Other not django specific projects that help me with web development

Flask

http://flask.pocoo.org/
Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

Supervisor

http://supervisord.org/
Supervisor is a client/server system that allows its users to monitor and control a number of processes on UNIX-like operating systems.

Gunicorn

http://gunicorn.org/
Gunicorn ‘Green Unicorn’ is a Python WSGI HTTP Server for UNIX. It’s a pre-fork worker model ported from Ruby’s Unicorn project.

Fabric

http://docs.fabfile.org/en/1.1.1/index.html
Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

Thursday, 5 May 2016

Interview Questions For Django Developers

Django an open source framework written in Python, was designed to save Web developers time and money by promoting the idea of reusing code and avoiding replication. As with any language, programmers interviewing for a job involving Django are going to face a series of specialized questions. The questions based on my  interview experience 

Questions are:

  1. Tell about Django Framework and working of Django Framework ?
  2. What is ORM ?
  3. Why we call as Django Framework is MVT architecture ?
  4. What is Middleware ? what is Important ? How to write Custom middlewares in Django?
  5. What is role of ALLOWED_HOSTs in Django ?
  6. What is CSRF ?
  7. What is Decorator ? How to Write Custom Decorator ? 
  8. what are built in Decorators in Django ?
  9. What is Template Tags ? How to write custom template tags ? 
  10. what are the built in template tags?
  11. How to inherit the A template in B template ?( template inheritance )
  12. Tell about few packages which you used in your Django career?
  13. Difference between FBV and CBV ?
  14. Difference between Form and Model Form ?
  15. User authentication Django ? where you can find the User(importing) ?
  16. What is Hashing ? difference between hashing and encryption ?
  17. What is __init __ method ?
  18.  What is diff List,Dictionary and Tuple ?( Some times the lead will ask these questions in twice or thrice , they checking the whether you are good in your anwser ?
  19.   What is Message ?
  20. How to Handle Load Management in python ?
  21. What is Memcache ?  what is redis server ? 
  22. What is Scheduling ? the packages which we used ?
  23. what is caching ?
  24. What is South ?
  25. What is Unicode ?
  26. Built in data types in Python ?
  27. Why python is interpreter ?  
  28. Memory management in Python ?
  29. In python Call by reference or Call by value ?
  30. Which version you familiar with in Django ?
  31. What is generater function ?
  32. List comprehensions?
  33. Why we use lamda function ? real time example ?
  34. What is signals  ?
  35. Map function ?
  36. Database ( if PostgreSQL,Mysql study the package name ) ?
  37. NoSql Database ?
  38. Mongodb with django ?
  39. What query set and Instance ?
  40. Difference between value and value_list ?
  41. What is __set method ?
  42. what is __init__method ?
  43. Aggregate and Annotate  ?
  44. What is lambada, where we use lambda ?
  45. How to make a meta list to normal list ?

Django override save method


We can override the save method into two ways,

1)
 class Blog(models.Model):
         name = models.CharField(max_length=100)
         tagline = models.TextField()

       def save(self, *args, **kwargs):
             do_something()
             # Call the "real" save() method in the base class 'models.Model'
             super(Blog, self).save(*args, **kwargs) <-----
            do_something_else()

 is equal to

2)
  class Blog(models.Model):
           name = models.CharField(max_length=100)
           tagline = models.TextField()

         def save(self, *args, **kwargs):
              do_something()
              # Call the "real" save() method in the base class 'models.Model'.
              models.Model.save(self, *args, **kwargs) <----- Note: self
              do_something_else()

Wednesday, 4 May 2016

Tips for django settings.py



Make a like this function for locate the directories in your django project settings  insted of calling "os.path.abspath(os.path.join(os.path.dirname ()" every where ( like : static,templates,media )

Help tips

add below function in your settings.py

import os

def root(x):
    return os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..',x))

then you can call it like this

TEMPLATE_DIRS = (

    root('templates')
)

Tuesday, 3 May 2016

Host your Django Website In Ubuntu Server With Ngnix and Uwsgi.

Introduction 

What is Ngnix ?

     Nginx (pronounced engine-x) is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Igor Sysoev started development of Nginx in 2002, with the first public release in 2004. Nginx now hosts nearly 12.18% (22.2M) of active sites across all domains. Nginx is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.



What is Uwsgi ?

      The uWSGI project aims at developing a full stack for building hosting services.applicaton servers( for various programing languages and protocols),proxies , process managers and monitors are all implemented using a common api and common configuration style.



Working Diagram for Ngnix, uWSGI with Python frameworks.



Request and Response Diagram



Configuration  

First install required applications:

sudo apt-get install nginx uwsgi uwsgi-plugin-python python-virtualenv, Here we are installing all the packages in single command ( ngnix , uwsgi and uwsgi packages and virtual env ) .I think you guys have ready  project in Django . Now I'm going to explain about the configuration for Hosting our django project with Ubuntu Server.

Versions of packages that will be used:
  • Nginx 
  • Uwsgi
  • Virtualenv
  • Django 1.7.7

Step 1 :  Activate your virtual env and run your django project ,

Example : 
  •  cd `/myprojects/
  •  virtualenv  global
  •  source gobal/bin/activate
  •  pip install django 
  •  django-admin.py startprojeect logiconline
Step 2 : Nginx configuration.

open Ubuntu terminal 

        Configuration files are stored in /etc/ngnix/site-available. Go to this Directory and create new file for our project logiconline.

  • cd /etc/nginx/site-available
Example . create a file

sudo subl logiconline.in  ( This command will create  a file for project , subl( Sublime text editor )


Example configuration :

server {
     listen  80;
    server_name logiconline.in www.logiconline.in;
    access_log /var/log/nginx/logiconline.in_access.log;
    error_log /var/log/nginx/logiconline.in_error.log;

    location / { 
        uwsgi_pass  unix:///tmp/logiconline.in.sock;
        include     uwsgi_params;
    }   

    location /media/  {
         alias /home/myprojects/logiconline/media/;
    }

    location  /static/ {
        alias /home/myprojects/logiconline/static/;
    }
}

We must  to enable this file in Ngnix conf

cd /etc/ngnix/sites-enabled

ln -s ../sites-available/logiconline.in.

Uwsgi configuration 

Like with Nginx.. configuration files are stored in /etc/uwsgi/apps-available. Go  to this directory and create a new file.

  • cd /etc/uwsgi/apps-available 
sudo subl logiconline.in.ini

Example : Uwsgi File 

[uwsgi]
vhost = true
plugins = python
socket = /tmp/logiconline.in.sock
master = true
enable-threads = true
processes = 2
wsgi-file = /home/myprojects/logiconline/logiconline/wsgi.py
virtualenv = /home/global
chdir = /home/myprojects/logiconline
touch-reload = /home/myprojects/logiconline/reload

Enable this.

cd /etc/uwgi/apps-enabled/
ln -s ../apps-available/logiconline.in.ini

Step 3 : That's all. Now, run this services.

  • sudo service nginx start
  • sudo service uwsgi start




Monday, 2 May 2016

Braintree payment gateway integration with Django

Introduction

Here Im going to tell you How to integrate the Braintree payment gateway with Django based application. I really thankful to Braintree support team because when i t try tart to integrate  it  feel really hard. But their help me lot and i completed my project successfully . In this blog i have attached the demo code for the same.

Workflow diagram






Step by Step Integration

    Step 1 :  Create Sandbox account with  Barintree  :- Create sandox account
    Step 2 :  Setup Client
    Step 3 :  Setup Server
    Step 4  :  Have fun .... with Brain tree

BrainTree Integration with Django Project

  Create the Sandbox account with  braintree , they will provide the merchant id, private and public key
Install braintree in your env using pip ( pip install braintree ).

Add the keys and merchant id with project settings

settings.py

BRAINTREE_MERCHANT = 'dznq5k44zc3qrycm'
BRAINTREE_PUBLIC_KEY = 'ttkr358rbpfnjvgn'
BRAINTREE_PRIVATE_KEY = 'dcfa177a5f71e00370323f17221e6cea'

Configure the Braintree with this above credentials

Views.py

from django.conf import settings

import braintree

braintree.Configuration.configure(braintree.Environment.Sandbox,
         merchant_id=settings.BRAINTREE_MERCHANT,
         public_key=settings.BRAINTREE_PUBLIC_KEY,

         private_key=settings.BRAINTREE_PRIVATE_KEY)



Genrate a client token in server side and render to the client side for processing 
payment method nonce.

Views.py

@login_required
@csrf_exempt
def checkout(request):
    rg = request.POST.get
    amount =  request.POST.get('prise') // when user click the subscription for payment
    user = Staff.objects.get(id=request.user.id)
    a_customer_id = ''
    if not user.customer_id:
        result = braintree.Customer.create
          ({
            "first_name": user.first_name,
            "last_name": user.last_name,
            "company": "Braintree",
            "email": user.email,
            "phone": "312.555.1234",
            "fax": "614.555.5678",
            "website": "www.example.com"
            })
  if result.is_success:
      user.customer_id = result.customer.id
      user.save()
      a_customer_id = user.customer_id
  else:
      a_customer_id = user.customer_id
  if not user.client_token:
      client_token = client_token = braintree.ClientToken.generate
        ({
          "customer_id": a_customer_id
        })
      user.client_token = client_token
      user.save()
  else:
      client_token = user.client_token
  varibles ={'amount':amount,'client_token':client_token}
  return render(request, 'checkout.html',varibles)

Setup Client 

checkout.html

<div class="form-style-5">
    {{amount}}
<input type='hidden' id='client_token' value='{{client_token}}'> // client token from server side
<form id="checkout" method="post" action="/payment">
    <div id="payment-form">
       <input type='hidden' name='amount' value='{{amount}}'> // amount
       <input type='text' name='amount' value='{{amount}}' readonly>
    </div>
    <input type="submit" value="Subcribe"> // Submit Button
</form>

</div>
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>

var clientToken = document.getElementById('client_token').value;
// creating payment method nonse

braintree.setup(clientToken, "dropin", {
  container: "payment-form"
});
</script>

How the Client look ?


When the user click on the submit button it will post the payment method nonce to server side.


Create Transcation

@login_required
@csrf_exempt
def payment(request):
if request.POST:
if request.POST.get("payment_method_nonce"):
                        // payment method nonce from client side.
nonce_from_the_client =  request.POST.get("payment_method_nonce")
staff = Staff.objects.get(id=request.user.id)
sub = Subscription()
sub.staff = staff
sub.payment_nonce = nonce_from_the_client
sub.amount = request.POST.get("amount")
sub.save()
result = braintree.Transaction.sale({
    "amount": sub.amount,
    "payment_method_nonce": sub.payment_nonce
})
transaction_id =  result.transaction.id
sub.txnid = transaction_id
sub.save()
message = ''
if result.is_success: // transaction success or not
sub.result = True
sub.save()
message =  'Transaction successfully completed'+' : '+ transaction_id
varibles ={'message':message}
return render(request, 'success.html',varibles)
else:
message = 'Error Transaction Faild'

varibles ={'message':message,}
return render(request, 'checkout.html',varibles)
else:
message = 'No transaction'

varibles ={'message':message,}
return render(request, 'checkout.html',varibles)


Transaction Results in my braintree account


Demo Project i have pushed in to the github , you can download and check it yourself.

Braintree payment gateway django demo project

Deploying a Django App to AWS Elastic Beanstalk

Introduction

Amazon Web Services (AWS) comprises dozens of services, each of which exposes  an area of functionality.While the variety of services offers flexibility for how you want to manage your AWS infrastructure, it can be challenging to figure out which services to use and how to provision them.With Elastic Beanstalk, you can quickly deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs those applications. AWS Elastic Beanstalk reduces management complexity without restricting choice or control. You simply upload your application, and Elastic Beanstalk automatically handles the details of capacity provisioning, load balancing, scaling, and application health monitoring.



The following steps is tell you  how to setup and deploy a Django application to Amazon Web services (AWS) all while remaining same.


Technology/Tool used

  • Python
  • Django
  • Amazon Elastic Beanstalk,EC2,S3 and RDS
  • EB CLI . 3 . X
  • Postgresql/mysql 
Note: Amazon Elastic Beanstalk does not support Python 3 natively




The following step will guide you for the  deployment

Step 1 :
  •       Create main root directory 
  •       Create  a virtualenv [ (1)pip install virtualenv,virtualenv envname ]
  •       Install packages using pip commands [pip install django==1.8.5]
  •       Create a package using command (django-admin.py startproject main_website
  •       Create a apps inside the main_website project using[python manage.py startapp home]
  •       Install the apps in settings.py
  •       Set the database according your needs
  •       Create a requirements.txt file inside the root directory [ pip freeze > requirements.txt]
  •       add file .gitignore in root directory
Step 2 :

  •       Install awsebcli in your machine (using pip , pip install awsebcli)
  •       Configure aws in your machine with key and access id [ aws configure command  in your         machine it will ask you to enter the credentials , add the credentials 
  •       then  aws will created ]
  •       Locate the project root directory [ using cd command cd eb_main_website ]
Step 3 :
  •       Test eb Installation is working fine [ eb --version ]
Step 4 :
  •         Configure EB - Initialize project with aws 
  •         Enter eb init        
Your need to enter the Credentials,Application name,Python version,SSH,RSA  keypair Once you enter the these data eb init will create a file in .elasticbeanstalk  in main directory , there you can see the file called config.yml

Project structure

eb_main_website [ Main Directory ]
    .ebextensions
        01-main_website.config
        02_python.config
    .elasticbeanstalk
        .config.yml
        .iod-test.env.yml
    main_website
      apps
        staffs
        home
          __init__.py
          management
            __init__.py
          commands
            __init__.py
            createsu.py
      main_website
        __init__.py
        settings.py
        urls.py
        wsgi.py
      www
        static
      .gitignore
      error.txt

      requirements.txt