How to set session with Django Rest Framework - django

For my Django project, I'm implementing RestAPI using DRF. To preserve some variables needed by two APIs, I wish to use a Django session. However, when I called Api2 after setting the session on Api1, it was None.
Has anybody encountered it before? Thank you very much for your assistance!
Here is an example of my API code:
from rest_framework import viewsets
class BaseViewSet(viewsets.ViewSet):
#action(methods="post")
def lookup(self, request):
request.session['abc'] = 1
request.session.modified = True
request.session.save()
print(request.session.session_key) # p02sr0qlnzntagfkf9ekm8f8km4w82t4
return = {}
#action(methods="post")
def login(self, request):
print(request.session.session_key) # None, it should be key p02sr0qlnzntagfkf9ekm8f8km4w82t4
print(request.session.get('abc') # None
data = {}

Related

Django Throttling Not Working on Production mode

I'm using DJANGO REST FRAMEWORK to protect my API. Django Throttling that limits the number of requests on an API for Anonymous and authenticates Users.
The throttling is not working on production mode. By the way, I'm using Ubuntu and Nginx server for deploying my site.
I use two way but both didn't work for me. Here are the codes. Please help me. I'm noob in django.
1st Method, Which I use is described below.
Views.py
class SustainedAnon(AnonRateThrottle):
rate = '100/day'
class BurstAnon(AnonRateThrottle):
rate = '10/minute'
class SustainedUser(UserRateThrottle):
rate = '100/day'
class BurstUser(UserRateThrottle):
rate = '10/min'
class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin):
lookup_field= 'puid'
serializer_class = ProductApisSerializers
"""
Provides a get method handler.
"""
# permission_classes = (IsAuthenticated,)
throttle_classes = (SustainedAnon,SustainedUser,BurstAnon,BurstUser)
def get_queryset(self):
return ProductApis.objects.all()
def post(self, request,*args,**kwargs):
return self.create(request, *args, **kwargs)
URLS.PY
from django.contrib import admin
from django.urls import path, include
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('',views.index, name='index'),
path('api/<slug:puid>/',views.ProductApi.as_view()),
]
2nd Method- DRF
Views.py
class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin):
lookup_field= 'puid'
serializer_class = ProductApisSerializers
"""
Provides a get method handler.
"""
# permission_classes = (IsAuthenticated,)
throttle_classes = [UserRateThrottle,AnonRateThrottle]
def get_queryset(self):
return ProductApis.objects.all()
def post(self, request,*args,**kwargs):
return self.create(request, *args, **kwargs)
settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '20/minute',
'user': '10/minute',
}
}
Also, in first method I didn't makes any changes in settings.py file while to use 2nd method I add an additional code of DRF for controlling throttling.
Both methods do not work for me.
Using LocMemCache in production will lead to random results.
Chances are you are using more than one process which means each will have each own isolated cache.
Whatever will be cached in one process will not be available to the others.
Using a single process like you do with the runserver make the cache consistent.
TL;DR, don't use LocMemCache in production. Use Redis, Memcache or another shared cache instead.

Unable to implement django-rules authorization

I'm a new django user looking for some help with django-rules. I'm trying to set up an authorization system that is 'OR' based. I have a 'File' model. I would like only the creator to be able to delete it, but a specific set of users to edit it. I've been able to followed their tutorial and implementation throughout; it works in the shell but not on my site. At the moment no one can delete or update anything.
My view currently looks like:
class FileUpdateView(PermissionRequiredMixin, generics.RetrieveUpdateAPIView):
"""
View updating details of a bill
"""
queryset = File.objects.all()
serializer_class = FileSerializer
permission_required = 'fileupload.change_file'
raise_exception = True
class FileDeleteView(PermissionRequiredMixin, generics.RetrieveDestroyAPIView):
"""
View for deleting a bill
"""
queryset = File.objects.all()
serializer_class = FileSerializer
permission_required = 'fileupload.delete_file'
raise_exception = True
The rules themselves are:
import rules
#rules.predicate
def is_creator(user, file):
"""Checks if user is file's creator"""
return file.owner == user
is_editor = rules.is_group_member('ReadAndWrite')
rules.add_perm('fileupload.change_file', is_editor | is_creator)
rules.add_perm('fileupload.delete_file', is_creator)
I know I'm close I feel like I'm just missing one step.
Thanks in advance!
please check & add settings file authentication backend for Django-rules. Also, you are mixing Django rest permissions with Django-rules permission. you need to check Django-rules permission in Django-rest permissions on view.
in short.
define a custom permission in rest-framework like this.
from rest_framework import permissions
class RulesPermissions(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return request.user.has_perm('books.edit_book', obj)
in viewset.
class BookView(viewsets.ModelViewSet):
permission_classes = (RulesPermissions,)
I've been working with the django REST framework and django-rules for a project and found an answer to your question.
The django REST framework uses an API view which is not compatible with rules' views.PermissionRequiredMixin, the authorization workflow and methods called during the API dispatch is different from django's class based view.
Try the following mixin for django REST framework API views and their subclasses:
import six
from django.core.exceptions import ImproperlyConfigured
class PermissionRequiredMixin:
permission_required = None
def get_permission_object(self):
object_getter = getattr(self, 'get_object', lambda: None)
return object_getter()
def get_permission_required(self):
if self.permission_required is None:
raise ImproperlyConfigured(
'{0} is missing the permission_required attribute. Define '
'{0}.permission_required, or override '
'{0}.get_permission_required().'
.format(self.__class__.__name__)
)
if isinstance(self.permission_required, six.string_types):
perms = (self.permission_required, )
else:
perms = self.permission_required
return perms
def check_permissions(self, request):
obj = self.get_permission_object()
user = request.user
missing_permissions = [perm for perm in self.get_permission_required()
if not user.has_perm(perm, obj)]
if any(missing_permissions):
self.permission_denied(
request,
message=('MISSING: {}'.format(', '.join(missing_permissions))))
With this mixin you're not forced to write a REST framework permission for each rules permission.

testing Django REST Framework

I'm working on my first project which uses Django REST Framework, and I'm having issues testing the API. I'm getting 403 Forbidden errors instead of the expected 200 or 201. However, the API works as expected.
I have been going through DRF Testing docs, and it all seems straightforward, but I believe my client is not being logged in. Normally in my Django projects I use a mixture of factory boy and django webtest which I've had a lot of happy success with. I'm not finding that same happiness testing the DRF API after a couple days of fiddling around.
I'm not sure if this is a problem relating to something I'm doing wrong with DRF APITestCase/APIClient or a problem with the django test in general.
I'm just pasting the following code and not posting the serializers/viewsets because the API works in the browser, it seems I'm just having issues with the APIClient authentication in the APITestCase.
# settings.py
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
# tests.py
from django.test import TestCase
from rest_framework.test import APITestCase, APIClient
from accounts.models import User
from .factories import StaffUserFactory
class MainSetUp(TestCase):
def setUp(self):
self.user = StaffUserFactory
self.api_root = '/api/v0/'
self.client = APIClient()
class APITests(MainSetUp, APITestCase):
def test_create_feedback(self):
"""
Ensure we can create a new account object.
"""
self.client.login(username='staffuser', password='staffpassword')
url = '%sfeedback/' % self.api_root
data = {
'feedback': 'this is test feedback'
}
response = self.client.post(url, data, user=self.user)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.data, data)
# factories.py
from factory.django import DjangoModelFactory
from django.contrib.auth import get_user_model
User = get_user_model()
class UserFactory(DjangoModelFactory):
class Meta:
model = User
class StaffUserFactory(UserFactory):
username = 'staffuser'
password = 'staffpassword'
email = 'staff#email.com'
first_name = 'Staff'
last_name = 'User'
is_staff = True
I've never used DjangoModelFactory before, but it appears that you have to call create after setting your user to the StaffUserFactory. http://factoryboy.readthedocs.org/en/latest/_modules/factory/django.html#DjangoModelFactory
class MainSetUp(TestCase):
def setUp(self):
self.user = StaffUserFactory
self.user.create()
self.api_root = '/api/v0/'
self.client = APIClient()
I bet your User's password is not being set properly. You should use set_password. As a start, trying changing your setUp to this:
def setUp(self):
self.user = StaffUserFactory
self.user.set_password('staffpassword')
self.user.save() # You could probably omit this, but set_password does't call it
self.api_root = '/api/v0/'
self.client = APIClient()
If that works, you probably want to override _generate() in your factory to add that step.
Another thing to check would be that SessionAuthentication is in your DEFAULT_AUTHENTICATION_CLASSES setting.
I think you must instantiate the Factory to get real object, like this:
self.user = StaffUserFactory()
Hope that help.
Moreover, you don't need to create a seperate class for staff, just set is_staff=True is enough. Like this:
self.user = UseFactory(is_staff=True)

Rest Framework Ember and sideloading

I am using Rest Framework Ember along with Django Rest Framework as my JSON API backend for my Ember application.
https://github.com/ngenworks/rest_framework_ember
I have gotten sideloading to work correctly with the resource_name = False flag.
Here is my code below:
class DocumentViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows documents to be viewed or edited.
"""
queryset = Document.objects.all()
serializer_class = DocumentSerializer
# Side loading code for documents
resource_name = False
# renderer_classes = (JSONRenderer, BrowsableAPIRenderer)
def list(self, request, *args, **kwargs):
# import IPython
# IPython.embed()
data = {'document': []}
for doc in self.get_queryset():
data['document'].append(doc)
data['contacts'] = doc.contacts.all()
serializer = DocumentContactSerializer(data)
return Response(serializer.data)
This works as I'd like it to work.
The problem now is that since I've implemented this and overwritten the list() method on the ModelViewSet whenever a new object is created on a POST I am getting this error:
'NoneType' object has no attribute '__getitem__'
If I comment out the resource_name = False then POST works as expected again.
Would you know what could be causing this?
I just ran into the very same problem. Our set-up is also Ember + DRF. And I have found a solution.
You could override the create method like this:
def create(self, request):
self.resource_name = 'document'
data = request.DATA # returns the right querydict now
# do what you want
In this way, you're keeping the side load by using resource_name = false in cases other than create.

Custom authentication with django?

Because I didn't want to use Django's in-build authentication system (maybe I should do, please tell me if this is the case), I created a simple little auth class:
import random
import hashlib
from myapp import models
class CustomerAuth:
key = 'customer'
def __init__(self, session):
self.session = session
def attempt(self, email_address, password):
password_hash = hashlib.sha1(password).hexdigest()
try:
return models.Customer.objects.get(
email_address=email_address,
password_hash=password_hash)
except models.Customer.DoesNotExist:
return None
def login(self, customer):
self.session[self.key] = customer
def logout(self):
if self.session.has_key(self.key):
self.session[self.key] = None
def is_logged_in(self):
return self.session.has_key(self.key)
and self.session[self.key] != None
def get_active(self):
if self.is_logged_in():
return self.session[self.key]
else:
raise Exception('No user is logged in.')
def redirect_to_login(self):
return HttpResponseRedirect('/login/')
def redirect_from_login(self):
return HttpResponseRedirect('/account/')
The problem is, that when I want to use it to stop unauthorized access, I have to use this code snippet in every single view method:
def example(req):
auth = CustomerAuth(req.session)
if not auth.is_logged_in():
return auth.redirect_to_login()
As you can imagine, this yields fairly ugly and repetitive code. What is a better way of doing this? Should I be using Django's auth framework?
Firstly, yes you should use Django's authentication framework, and build your own custom auth backend.
Secondly, however you do it, you'll need to have something in the views that you want to restrict access to. The best way to do that is via a decorator on the view. Again, Django's built-in framework gives you access to the #login_required decorator, which does exactly what you want.