Wednesday, 23 September 2015

create a RESTful API in Django without using thirdparty framework like Django Rest Framework and Tastypie


If you want to implement Rest API in django and you do not want to user Django Rest Framework , tastypie or any other third party framework then you can follow rules give below to implement REST API almost .

Use HTTP verbs  (GET, POST, PUT, DELETE, PATCH)

You should return response in JSON(you can also return in xml)

If you are writing one url to group all of your api related to a object calling by using proper HTTP verbs  then you can almost achieve it.

URL       /users/

Then REST API for user related operations can be -


GET  /users/        To get all users's information.
GET  /users/<pk>/    To get a user's information.
POST  /users/   To create a user.
PUT /users/<pk>   To update a user information.
PUT  /users/   To update all user's information at once.
DELETE /users/<pk>/  To delete a user.
DELETE /users/  To delete all users.


To implement view it will be great if you are writing class based views and you view can be .

class UserView(View):
    def get(self, request, *args, **kwargs):
        # logic
    def post(self, request, *args, **kwargs):
        # logic
    def put(self, request, *args, **kwargs):
        # logic
    def delete(self, request, *args, **kwargs):
        # logic


You can return JSON in response by following below pattern in each your method in your view.

import json

from django.http import HttpResponse

def method(arguments):
    # logic --
    # logic  --
    data = {'pk': '1'}
    response = json.dumps(data)
    return HttpResponse(response, content_type="application/json")









Friday, 17 January 2014

execute task only one time during next fix time after it's first execution

Hello Friends,


I am back :)

First Wish you a very happy new year.

I know it's too late ;)

Today we are going to learn how can we execute a task only one time for some some specific time period .

Example : You want to give bonus to any user only one time in a day when user access 'about-us' template.
So Let user access that page multiple times in a day still user will got bonus will once.
Guess  about-us is django view .
<pre>

from functools import wraps
from django.core.cache import cache

def execute_once_in(seconds):
    def decorator(func):
        def inner_decorator(*args, **kwargs):
            key = "%s.%s" % (func.__module__, func.__name__)
            #Django used localmemcache as local cache system
            key = key.replace(' ','_') # memcache doesn't like spaces
            # func() didn't execute or returned nothing
            if cache.get(key):
                return
            cache.set(key, True, seconds)
            return func(*args, **kwargs)
        return wraps(func)(inner_decorator)
    return decorator


@execute_once_in(5)   # function will execute only once in each 5 second .
def bonus():
    print "we are executing logic for bonus"

def about_us(request):
     bonus()
    #execution
</pre>





Wednesday, 25 December 2013

public and private objects into python


Python does not support privacy directly . Programmer need to know when it is safe to modify attribute from outside but anyway with python you can achieve something like private with little tricks.
wow this is awesome .

Now let's see a person can put anything private to it or not :P
class Person(object):
  
    def __priva(self):
        print "I am Private"
   
    def publ(self):
        print " I am public"
   
    def callpriva(self):
        self.__priva()



Now When we will execute :
>>> p = Person()
>>> p.publ()
 I am public
>>> p.__priva()
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    p.__priva()
AttributeError: 'Person' object has no attribute '__priva'

Explanation   : You can see  here we are not able to fetch that private method directly.

>>> p.callpriva()
I am Private
Explanation  : Here we can access private method inside class​


​Then how someone can access that variable  ???


You can do like :
>>>p._Person__priva
I am Private

​ wow ,  actually if python is getting any variable starting with  double underscore are “translated” by adding a single underscore and the class name to the beginning:

Note : If you do not want this name changing but you still want to send a signal for other  objects to stay away, you can use a single initial underscore names with an initial underscore aren’t imported with starred imports (from module import *)
Finally  : Python doesn’t really have an equivalent privacy support, although single
and double initial underscores do to some extent give you two levels of privacy

Friday, 27 September 2013

send fake email using python smtplib library


Hi All,

Today we will learn how can we send a fake email from any email account using python .

we are using python library smtplib which will call machine's smtp server and it will send email from provided From email .
While using ubuntu you can use postfix as smtp server .


import smtplib
To ="91prashantgaur@gmail.com"
Subject = "Test Fake Email "
Message  = "Hi How are you  ?"
Email = 'test@gmail.com'            # from this email id we will send email 
server = smtplib.SMTP('localhost')        # local smtp server of machine
Message = string.join(("From: %s" % Email,
                                   "To: %s" % To,
                                   "Subject: %s" % Subject,
                                  "",
                                  Message
                                  ),"\r\n")
server.sendmail(Email , [To], Message)
server.quit()

If any question let me know at  91prashantgaur@gmail.com


Prashant Gaur
Python/JavaScript Developer
9717353657

Friday, 23 August 2013

Block any particular IP address in django


in settings.py file ..

   BLOCKED_IPS = ('127.0.0.1',)    --- > touple of ip addressed

and in our view just simple  ---- >



    from django.conf import settings
    from django import http
    if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
          return http.HttpResponseForbidden('<h1>Forbidden</h1>')
    return render_to_response("home-page.html")

Wednesday, 21 August 2013

how to use __in with __startswith in django queryset

Hi All,

Today we will see the code which will help us to use __in  with __startswith or any other filter.

First we will learn use of __in .

__in   ----> it is used to filter data from a list

namelist = ['sachin', 'dravid', 'dhoni', 'khan']
Player.objects.filter(name__in=namelist)                                                                          

Use of __startswith or __endswith to filter data based on starting ,ending pattern in any string .
Player.objects.filter(name__startswith='sac')

if you want to filter query where name will start with words given in any list you will use.


from django.db.models import Q
def startwithin(namelist):
        q = Q()
        for names in namelist:
            q |= Q(name__startswith=names)    # | will union all objects 
        return Player.objects.filter(q)
     


Thanks
Prashant Gaur

Tuesday, 16 July 2013

Display AutoField(primary_key) as read only in Django admin

Generally It doesn't have an ID until you save it.


Please follow below code it will sure help you to overcome from None.

models.py
class A(models.Model):
    a = models.AutoField(primary_key=True)
   
    def __str__(self):
        return str(self.a)

admin.py 
class AAdmin(admin.ModelAdmin):
    list_display = ['a']
    readonly_fields = ['ass']

    def ass(self, obj):
        if obj.a is None:
            a = A.objects.all().order_by('-a')[:1]
            print a
            if a:
                return a[0].a + 1
            else:
                return 0
        else:
            return obj.a
admin.site.register(A, AAdmin)



Please check above code .if any issue please revert me.


Prashant Gaur
+91 9030015491