Sunday, 22 May 2016

Simplifying Django

Despite Django’s popularity and maturity, some developers believe that it is an outdated web framework made primarily for “content-heavy” applications. Since the majority of modern web applications and services tend not to be rich in their content, this reputation leaves Django seeming like a less than optimal choice as a web framework.
Let’s take a moment to look at Django from the ground up and get a better idea of where the framework stands in today’s web development practices.

Plain and Simple Django

A web framework’s primary purpose is to help to generate the core architecture for an application and reuse it on other projects. Django was built on this foundation to rapidly create web applications. At its core, Django is primarily a Web Server Gateway Interface (WSGI) application framework that provides HTTP request utilities for extracting and returning meaningful HTTP responses. It handles various services with these utilities by generating things like URL routing, cookie handling, parsing form data and file uploads.
Also, when it comes to building those responses Django provides a dynamic template engine. Right out of the box, you are provided with a long list of filters and tags to create dynamic and extensible templates for a rich web application building experience.
By only using these specific pieces, you easily see how you can build a plain and simple micro-framework application inside a Django project.
We do know that there are some readers who may enjoy creating or adding their own utilities and libraries. We are not trying to take away from this experience, but show that using something like Django allows for fewer distractions. For example, instead of having to decide between Jinja2, Mako, Genshi, Cheetah, etc, you can simply use the existing template language while you focus on building out other parts. Fewer decisions up front make for a more enjoyable application building process.

Onboarding New Django Users

A bigger issue the Django community, and other web frameworks, continue to battle is the onboarding process of new users. For example, these new users typically begin learning Django through it’s official tutorial where you build a polling application. Many of us seasoned Django developers consider it a “rite of passage” into the Django community. But is it the best way to begin learning Django? Probably not.
Currently, there are a total of six parts to complete the polls app tutorial. While each part has it’s significance, it isn’t until part three that you finally write your first public facing view and start building out your HTTP responses. This is a far cry from the more simple “Hello World” tutorial you’ll see on the front pages of popular Python micro-frameworks (e.g. Flask or Bottle). The answer we see happening is to create less of a barrier to entry for learning the parts and pieces of Django and focus on the basic request to response interaction. New users can then build from there to see how the other pieces of the framework help you with common web tasks, like session management, user authentication or the built-in admin interface.
To show what we mean, let’s build out a sample of what a more simplified Django tutorial might look like:
Simple, right? This small bit of code is all you need to run a Django project. Let’s break down each component to explain the necessity for each part.
First, we’ll need to make sure to include Django’s HTTP response request utility and return the values we want to have in that response:
Normally, this code would be implemented in the standard views.py file of a typical Django project. For the simplicity of this project, we’ll be placing most of the code to run our application in this single file.
The next portion of the application ties in nicely in with this portion is the url structure. The code above expects the index url, so we’ll need to create that:
From only seven lines of code we have already created the basics to run an application in Django! Now, we’ll implement the basic settings to make the application runnable:
You’ll notice in the example that we have stripped down the settings and have specifically excluded the database configuration. We see these options as a particular barrier to entry for new users with the confusion it causes when trying to determine what databases they should use. We want to make sure that we focus on specific parts to implementing our project to drop the barrier levels.
NOTE: Be sure to make a private and random SECRET_KEY value in yoursettings.configure for the default session and cross-site request forgery (CSRF) protection.
Since we are not generating this structure by using the startproject command, we are missing the typical manage.py file that is generated. We’ll need to add the relevant portions that are part of manage.py and used to run our project:
You should now be able to go to your command line to start your application:
Now when you browse out to your localhost at 127.0.0.1:8000, you’ll get the output of “Powered by Django” in the window!
simplifying_django_fig_1
Now you may be asking yourself, “where is the views.py or models.py?!” First off, take a deep breath and relax. Remember what Django really is: it’s a Python web framework with a whole host of utilities you can easily import to do the things you need to do to run your application. This is where we see the next portion of the tutorial in teaching new users how to import those utilities. For example, building out a simple template seems like the most natural progression in this process. So, let’s do that!
The basic understanding of adding templates is through the way we define our settings and urls. We’ll need to first tell Django where our template files are located by adding the necessary settings. Let’s start by adding a variable to point to your where your project lives:
You’ll notice at the top, we’ve added an import of the os.path Python module. By doing this, we have created an easy way for new users to point to their project folder. Now we can easily add in our TEMPLATE_DIRS setting to point to this template directory and start taking advantage of Django’s built-in tags and filters!
As you can see, by decomposing the basics of creating a Django application into smaller parts, we can create an easier way to onboard new users. We need to re-learn how to teach Django by building Django applications without the ORM and without the Django admin. These parts of Django need to be seen for what they really are: built-in features. They aren’t necessary in order to use the framework and you don’t lose much if you don’t feel the need to implement them. We should start with the pieces of Django, just like you would learn the Python standard library, for the good parts and not feel the weight. Let’s start moving past that and see it for the open source, feature rich utility it really is.
So, with all of this in mind, what are some applications you are considering building that could be developed in this light-weight manner?

Wednesday, 18 May 2016

How start your first django programing



This framework so easy and nice it just write little and get more

Django is an MVC framework. However, the controller is called the "view", and
the view is called the "template". The view in Django is the component which
retrieves and manipulates data, whereas the template is the component that presents data to the user. For this reason, Django is sometimes called an MTV framework (MTV stands for model template view). This different terminology not changes the fact that Django is an MVC framework, nor affects how applications are developed. But keep the terminology in mind to avoid possible confusion if you have worked with other MVC frameworks in the past

now i will create a empty project



create a empty folder like "django" just for collection

To create your first Django project, open a terminal type the following command, and hit enter:

$cd django
$ django-admin.py startproject store

 This command will make a folder named store in the current directory, and create the initial directory structure inside it. where you can see kinds of file created like:

store/
      __init__.py (django project is a python package so and this file create
                           current folder like a package)
      manage.py (use for manage project)
      settings.py (configuration file of django project)
      urls.py (this is another configuration file. You can think of it as a mapping
                   between URLs and Python functions)

next open setting.py file and find bellow section 

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

when you find this section then edit this section to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "store",
        'USER': "root",
        'PASSWORD':"root",
    }
}

we will try to connect mysql thats why we have set database module name "django.db.backends.mysql" this is a class that are in django/db/backends and class name is mysql this will load when django server will run and also i have set database name ,username and password(this is password that you have given on mysql intalletion) this all mysql information

next you need to create database so open terminal and type

$mysql -uroot -p

next give your mysql password if you right password you will see mysql command prompt

next type this command

mysql>create database store

this command for create store database

Finally, we will tell Django to populate the configured database with tables.
Although we haven't created any tables for our data, Django requires several tables in the database for some of its features to function properly. Creating these tables is easy just follow and type this command in terminal and you will see your result:

first of all go to your django folder next store folder from your terminal

$cd django
$cd store

when you at store folder then type bellow command

$ python manage.py syncdb

this command for syncronized with database

If you have entered the above command and everything is correct, status messages will scroll on the screen indicating that the tables are being created. When prompted for the superuser account, enter your preferred username, email address and password. It is important to create a superuser account otherwise you won't be able to gain access to your initial webpage once you have created it. If, on the other hand, the database is mis-configured, an error message will be printed to help you troubleshoot the issue like bellow screenshot


and finally you can launching the development server
go to store folder from terminal and type this command:

$ python manage.py runserver

this command for run your django server 
Next, open your browser, and navigate to http://localhost:8000/. You should see a welcome message as in the image below:

Now Enjoyyyyy.........

Django: Using Caching to Track Online Users


Recently I wanted a simple solution to track whether a user is online on a given Django site.  The definition of "online" on a site is kind of ambiguous, so I'll define that a user is considered to be online if they have made any request to the site in the last five minutes. 

I found that one approach is to use Django's caching framework to track when a user last accessed the site.  For example, upon each request, I can have a middleware set the current time as a cache value associated with a given user.  This allows us to store some basic information about logged-in user's online state without having to hit the database on each request and easily retrieve it by accessing the cache.

My approach below.  Comments welcome.

In settings.py:

# add the middleware that you are about to create to settings

MIDDLEWARE_CLASSES = (
    ....
    'middleware.activeuser_middleware.ActiveUserMiddleware',
    ....
)

# Setup caching per Django docs. In actuality, you'd probably use memcached instead of local memory.

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'default-cache'
    }
}

# Number of seconds of inactivity before a user is marked offline

USER_ONLINE_TIMEOUT = 300

# Number of seconds that we will keep track of inactive users for before 
# their last seen is removed from the cache

USER_LASTSEEN_TIMEOUT = 60 * 60 * 24 * 7

In activeuser_middleware.py:

import datetime
from django.core.cache import cache
from django.conf import settings

class ActiveUserMiddleware:

    def process_request(self, request):
        current_user = request.user
        if request.user.is_authenticated():
            now = datetime.datetime.now()
            cache.set('seen_%s' % (current_user.username), now, 
                           settings.USER_LASTSEEN_TIMEOUT)

In your UserProfile module or some other model associated with the user:

class UserProfile(models.Model):
    ....
    ....

    def last_seen(self):
        return cache.get('seen_%s' % self.user.username)

    def online(self):
        if self.last_seen():
            now = datetime.datetime.now()
            if now > self.last_seen() + datetime.timedelta(
                         seconds=settings.USER_ONLINE_TIMEOUT):
                return False
            else:
                return True
        else:
            return False

Then in the template where you want to display whether the user is online or not:

{% with request.user.get_profile as profile %}

 <table>
   <tr><th>Last Seen</th><td>{% if profile.last_seen %}{{ profile.last_seen|timesince }}{% else %}awhile{% endif %} ago</td></tr>
   <tr><th>Online</th><td>{{ profile.online }}</td></tr>
 </table>

{% endwith %}

Pros:
 - Simple solution
 - Doesn't need to hit the database for saving the timestamp each request

Cons:
  - Last user access times are cleared if the server is rebooted or cache is reset
  - Last user access times are accessible only as long as they exist in the cache.

Django Admin Override Save for Model

Sometimes it's nice to be able to add custom code to the save method of objects in the Django Admin. So, when editing an object on the Admin object detail page (change form), adding the following method override to your ModelAdmin in admin.py will allow you to add custom code to the save function. 

In admin.py:

class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        # custom stuff here
        obj.save()

This is documented in the Django Docs, but I found it particularly useful

Tuesday, 10 May 2016

Google reCAPTCHA integration in Django



Introduction


reCAPTCHA is a free service to protect your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive captcha to keep automated software from engaging in absive activities on your site. it does this while letting your valid users pass through with ease.reCAPTCHA offers more than just spam protection. Every time our CAPTCHAs are solved. that

human effort helps digitize text,annotate images, and build machine learning datasets.This in turn helps preserve books,improve maps, and solve hard Al problems.

demo for reCAPTCHA in your website

How to integrate google reCAPTCHA with django ?


step 1 .Install django-nocaptcha-recaptcha in your Virtual Environment
        pip install django-nocaptcha-recaptcha
        
step 2 .Configuration
        Add  nocaptcha_recaptcha to your INSTALLED_APPS setting
        Add the following to settings.py

        NORECAPTCHA_SITE_KEY  (string) = the Google provided site_key
        NORECAPTCHA_SECRET_KEY (string) = the Google provided secret_key
        
        Reffer  this link : https://developers.google.com/recaptcha/intro
        Add the field to a form that you want to protect.
        
        from nocaptcha_recaptcha.fields import NoReCaptchaField

        class DemoForm(forms.Form):
            captcha = NoReCaptchaField()

        Add Google's JavaScript library to your base template or elsewhere, so it is available on the 
        page  containing the django form.

        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        (optional) You can customize the field.

        You can add attributes to the g-recaptcha div tag through the following
            captcha = NoReCaptchaField(gtag_attrs={'data-theme':'dark'}))    
        You can override the template for the widget like you would any other django template.

step 3 : Demo project
           
          demo project for google recaptcha integration

Friday, 6 May 2016

Asynchronous Tasks With Django and Celery

Introduction


When i was working on projects in  Django ,  one of the most frustrating thing I faced was need to run a bit of code periodically, i wrote my own function is for sending newsletter on the Monday morning 10 am , this time i faced lots of problem because some times my function did not working properly don't mean's syntactically , so i may think to start where i done wrong , is right no ? then how the problem is occurring , after that finally i found a solution for do some task periodically we can use Celery.




What is Celery ?

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.” For this post, we will focus on the scheduling feature to periodically run a job/task.
Why is this useful?
  • Think of all the times you have had to run a certain task in the future. Perhaps you needed to access an API every hour. Or maybe you needed to send a batch of emails at the end of the day. Large or small, Celery makes scheduling such periodic tasks easy.
  • You never want end users to have to wait unnecessarily for pages to load or actions to complete. If a long process is part of your application’s workflow, you can use Celery to execute that process in the background, as resources become available, so that your application can continue to respond to client requests. This keeps the task out of the application’s context.
What you need ?

Celery requires a message transport to send and receive messages. The RabbitMQ and Redis broker transports are feature complete, but there’s also support for a myriad of other experimental solutions, including using SQLite for local development.
Celery can run on a single machine, on multiple machines, or even across data centers.

First Steps with Celery

Celery is a task queue with batteries included. It is easy to use so that you can get started without learning the full complexities of the problem it solves. It is designed around best practices so that your product can scale and integrate with other languages, and it comes with the tools and support you need to run such a system in production.

In this blog you will learn the absolute basics of using Celery. You will learn about;
  • Choosing and installing a message transport (broker).
  • Installing Celery and creating your first task.
  • Starting the worker and calling tasks.
  • Keeping track of tasks as they transition through different states, and inspecting return values.
     Choosing a Broker
         Celery requires a solution to send and receive messages; usually this comes in the form of                 a separate service called a message broker.
      There are several choices available, including: (please search google for more details )
  •        RabbitMQ
  •        Redis
  •        Using a database
  •        Other brokers

 Installing Celery

 Celery is on the Python Package Index (PyPI), so it can be installed with standard Python tools like  pip or easy_install:
$ pip install celery
Example :

Let’s create the file tasks.py
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y
Example Project :
Clone my project  url : git cloe https://github.com/renjithsraj/photogallery.git
Project Description :
This Project mainly looking for basic understand about the periodic task ( scheduling task ) in django. The scope of the project is collect the images from the flickr latest images and store in to data base in every two minute (change with your own time ) make it a gallery.

heroku url : https://flickercollection.herokuapp.com/
Configuration:
step 1 : Create Virtualenv using (virtualenv env)
step 2 : open terminal activate the env
step 3 : clone the project command ( git clone https://github.com/renjithsraj/photogallery.git )
step 4 : make the path to project ( cd photogallery in linux )
step 5 : install packages which we required for this project ( pip install -r requrements.txt )
step 6 : install broker here im used redis ( if install redis server also in your local machine )
step 7 : open new terminal start the redis server ( redis-server command )
step 8 : Running Locally
Ready to run this thing?
With your Django App and Redis running, open two new terminal windows/tabs. In each new window, navigate to your project directory, activate your virtualenv, and then run the following commands (one in each window):
 $ celery -A pincha worker -l info
 $ celery -A pincha beat -l info
    When you visit the site on http://127.0.0.1:8000/ you should now see one image. Our app gets one image from Flickr every 2 minutes: ( here i just take images frequent interval please make your intervel )