Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>
class FakeQueryset:
def __init__(self, objs):
self.objects = objs
def __len__(self):
return len(self.objects)
def __iter__(self):
return self.objects.__iter__()
def filter(self, pk__in):
return FakeQueryset([o for o in self.objects if o.pk in pk__in])
class BaseProjList(generic.ListView):
model = Proj
objects = None
template_name = "filtering_proj_list.html"
raise_exception = True
def __init__(self, *args, **kwargs):
if 'objects' in kwargs:
self.objects = FakeQueryset(kwargs['objects'])
def get_queryset(self):
return self.objects
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | class NormalProjList(PermissionRequiredMixin, BaseProjList): |
Given the following code snippet before the placeholder: <|code_start|># org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
pols = []
PolicyFactory.set_directory(str(datadir))
for i in range(1, 6):
<|code_end|>
, predict the next line using imports from the current file:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | user = UserFactory.create(username='user{}'.format(i)) |
Given snippet: <|code_start|># proj.detail (P=+proj.detail_private)
#
# org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
pols = []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
which might include code, classes, or functions. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Based on the snippet: <|code_start|># org1 X X X
# org2 X X X
#
# proj.detail (P=+proj.detail_private)
#
# org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | def setup(datadir, db): |
Given the code snippet: <|code_start|># org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
pols = []
PolicyFactory.set_directory(str(datadir))
for i in range(1, 6):
user = UserFactory.create(username='user{}'.format(i))
pol = PolicyFactory.create(name='pol{}'.format(i),
file='policy-{}.json'.format(i))
user.assign_policies(pol)
users.append(user)
pols.append(pol)
orgs = []
for i in range(1, 3):
<|code_end|>
, generate the next line using the imports in this file:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | orgs.append(Org(pk=i, name='org{}'.format(i))) |
Here is a snippet: <|code_start|>
class FakeQueryset:
def __init__(self, objs):
self.objects = objs
def __len__(self):
return len(self.objects)
def __iter__(self):
return self.objects.__iter__()
def filter(self, pk__in):
return FakeQueryset([o for o in self.objects if o.pk in pk__in])
class BaseProjList(generic.ListView):
<|code_end|>
. Write the next line using the current file imports:
from django.core.exceptions import PermissionDenied
from tutelary.mixins import PermissionRequiredMixin
from django.test import RequestFactory
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import django.views.generic as generic
import pytest
and context from other files:
# Path: tutelary/mixins.py
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin -- works just like the
# ``PermissionRequiredMixin`` in the default Django authentication
# system.
#
# """
# def has_permission(self):
# """Permission checking for "normal" Django."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# return True
# else:
# return check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# def handle_no_permission(self):
# msg = self.get_permission_denied_message()
# if hasattr(self, 'raise_exception') and self.raise_exception:
# raise PermissionDenied(*msg)
# return msg
#
# def dispatch(self, request, *args, **kwargs):
# if not self.has_permission():
# return self.handle_no_permission()
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
, which may include functions, classes, or code. Output only the next line. | model = Proj |
Using the snippet: <|code_start|> fields = ('name', 'org')
depth = 1
class FakeQueryset:
def __init__(self, objs):
self.objects = objs
def __len__(self):
return len(self.objects)
def __iter__(self):
return self.objects.__iter__()
def filter(self, pk__in):
return FakeQueryset([o for o in self.objects if o.pk in pk__in])
class BaseProjList(generics.ListAPIView):
objects = None
serializer_class = ProjSerializer
def __init__(self, *args, **kwargs):
if 'objects' in kwargs:
self.objects = FakeQueryset(kwargs['objects'])
def get_queryset(self):
return self.objects
<|code_end|>
, determine the next line of code. You have imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context (class names, function names, or code) available:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | class NormalProjList(APIPermissionRequiredMixin, BaseProjList): |
Based on the snippet: <|code_start|>class FakeQueryset:
def __init__(self, objs):
self.objects = objs
def __len__(self):
return len(self.objects)
def __iter__(self):
return self.objects.__iter__()
def filter(self, pk__in):
return FakeQueryset([o for o in self.objects if o.pk in pk__in])
class BaseProjList(generics.ListAPIView):
objects = None
serializer_class = ProjSerializer
def __init__(self, *args, **kwargs):
if 'objects' in kwargs:
self.objects = FakeQueryset(kwargs['objects'])
def get_queryset(self):
return self.objects
class NormalProjList(APIPermissionRequiredMixin, BaseProjList):
permission_required = 'proj.list'
<|code_end|>
, predict the immediate next line with the help of imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | class NormalPermissionsProjList(PermissionsFilterMixin, |
Continue the code snippet: <|code_start|># org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
pols = []
PolicyFactory.set_directory(str(datadir))
for i in range(1, 6):
<|code_end|>
. Use current file imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context (classes, functions, or code) from other files:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | user = UserFactory.create(username='user{}'.format(i)) |
Here is a snippet: <|code_start|># proj.detail (P=+proj.detail_private)
#
# org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
pols = []
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context from other files:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
, which may include functions, classes, or code. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Here is a snippet: <|code_start|># org1 X X X
# org2 X X X
#
# proj.detail (P=+proj.detail_private)
#
# org1/proj1 P X X
# org1/proj2 P X X
# org1/proj3 P X X
# org1/proj4 P X
# org1/proj5 P X
# org1/proj6 P
# org1/proj7 (P) P
# org2/proj8 X X X
# org2/proj9 (P) X P X
# org2/proj10 (P) X X X
#
# proj.delete
#
# org1/proj1 X X
# org1/proj2 X
# org1/proj3 X
# org1/proj4 X
# org1/proj5 X
# org1/proj6 X
# org1/proj7 X
# org2/proj8 X X
# org2/proj9 X X
# org2/proj10 X
@pytest.fixture(scope="function") # noqa
<|code_end|>
. Write the next line using the current file imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context from other files:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
, which may include functions, classes, or code. Output only the next line. | def setup(datadir, db): |
Continue the code snippet: <|code_start|>
class OrgSerializer(serializers.ModelSerializer):
class Meta:
model = Org
fields = ('name',)
class ProjSerializer(serializers.ModelSerializer):
class Meta:
<|code_end|>
. Use current file imports:
from rest_framework import serializers
from tutelary.mixins import APIPermissionRequiredMixin, PermissionsFilterMixin
from rest_framework.test import APIRequestFactory, force_authenticate
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .filter_models import Org, Proj
import rest_framework.generics as generics
import pytest
and context (classes, functions, or code) from other files:
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# class PermissionsFilterMixin:
# def dispatch(self, request, *args, **kwargs):
# permissions = request.GET.get('permissions', None)
# if permissions:
# actions = tuple(permissions.split(','))
#
# if (hasattr(self, 'permission_filter_queryset') and
# isinstance(self.permission_filter_queryset, Sequence)):
# actions += tuple(self.permission_filter_queryset)
#
# self.permission_filter_queryset = actions
#
# return super().dispatch(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/filter_models.py
# class Org(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'org'
# path_fields = ('name',)
# actions = [('org.list', {'permissions_object': None})]
#
# class Proj(models.Model):
# name = models.CharField(max_length=100)
# org = models.ForeignKey(Org)
# public = models.BooleanField(default=True)
#
# class TutelaryMeta:
# perm_type = 'proj'
# path_fields = ('org', 'name',)
# actions = [('proj.list', {'permissions_object': 'org'}),
# 'proj.detail',
# 'proj.detail_private',
# 'proj.delete']
. Output only the next line. | model = Proj |
Predict the next line after this snippet: <|code_start|> ('parcel.delete', {'description': "Delete parcels"})
]
def get_absolute_url(self):
return reverse('parcel-detail', kwargs={'pk': self.pk})
permissioned_model(
Policy, perm_type='policy', path_fields=['name'],
actions=[
('policy.list', {'description': "Can list existing policies",
'permissions_object': None}),
('policy.create', {'description': "Can create policies",
'permissions_object': None}),
('policy.detail', {'description': "Can view details of a policy"}),
('policy.edit', {'description': "Can update existing policies"}),
('policy.delete', {'description': "Can delete policies"})
]
)
permissioned_model(
User, perm_type='user', path_fields=['username'],
actions=[
('user.list', {'permissions_object': None}),
('user.create', {'permissions_object': None}),
'user.detail',
'user.edit',
'user.delete'
]
)
<|code_end|>
using the current file's imports:
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from tutelary.engine import Action
from tutelary.models import Policy
from tutelary.decorators import permissioned_model
and any relevant context from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# Path: tutelary/decorators.py
# def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
# """Function to set up a model for permissioning. Can either be called
# directly, passing a class and suitable values for ``perm_type``,
# ``path_fields`` and ``actions``, or can be used as a class
# decorator, taking values for ``perm_type``, ``path_fields`` and
# ``actions`` from the ``TutelaryMeta`` subclass of the decorated
# class.
#
# """
# if not issubclass(cls, models.Model):
# raise DecoratorException(
# 'permissioned_model',
# "class '" + cls.__name__ + "' is not a Django model"
# )
# added = False
# try:
# if not hasattr(cls, 'TutelaryMeta'):
# if perm_type is None or path_fields is None or actions is None:
# raise DecoratorException(
# 'permissioned_model',
# ("missing argument: all of perm_type, path_fields and " +
# "actions must be supplied")
# )
# added = True
# cls.TutelaryMeta = type('TutelaryMeta', (object,),
# dict(perm_type=perm_type,
# path_fields=path_fields,
# actions=actions))
# cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
# get_path_fields(cls))
# perms_objs = {}
# for a in cls.TutelaryMeta.actions:
# an = a
# ap = {}
# if isinstance(a, tuple):
# an = a[0]
# ap = a[1]
# Action.register(an)
# if isinstance(ap, dict) and 'permissions_object' in ap:
# po = ap['permissions_object']
# if po is not None:
# try:
# t = cls._meta.get_field(po).__class__
# if t not in [models.ForeignKey,
# models.OneToOneField]:
# raise PermissionObjectException(po)
# except:
# raise PermissionObjectException(po)
# perms_objs[an] = po
# if len(perms_objs) == 0:
# cls.get_permissions_object = get_perms_object
# else:
# cls.get_permissions_object = make_get_perms_object(perms_objs)
# return cls
# except:
# if added:
# del cls.TutelaryMeta
# raise
. Output only the next line. | Action.register('statistics') |
Predict the next line for this snippet: <|code_start|> def get_absolute_url(self):
return reverse('party-detail', kwargs={'pk': self.pk})
@permissioned_model
class Parcel(models.Model):
project = models.ForeignKey(Project)
address = models.CharField(max_length=200)
class Meta:
ordering = ('project', 'address')
class TutelaryMeta:
perm_type = 'parcel'
path_fields = ('project', 'pk')
actions = [
('parcel.list', {'description': "List existing parcels",
'permissions_object': 'project'}),
('parcel.create', {'description': "Create parcels",
'permissions_object': 'project'}),
('parcel.detail', {'description': "View details of a parcel"}),
('parcel.edit', {'description': "Update existing parcels"}),
('parcel.delete', {'description': "Delete parcels"})
]
def get_absolute_url(self):
return reverse('parcel-detail', kwargs={'pk': self.pk})
permissioned_model(
<|code_end|>
with the help of current file imports:
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from tutelary.engine import Action
from tutelary.models import Policy
from tutelary.decorators import permissioned_model
and context from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# Path: tutelary/decorators.py
# def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
# """Function to set up a model for permissioning. Can either be called
# directly, passing a class and suitable values for ``perm_type``,
# ``path_fields`` and ``actions``, or can be used as a class
# decorator, taking values for ``perm_type``, ``path_fields`` and
# ``actions`` from the ``TutelaryMeta`` subclass of the decorated
# class.
#
# """
# if not issubclass(cls, models.Model):
# raise DecoratorException(
# 'permissioned_model',
# "class '" + cls.__name__ + "' is not a Django model"
# )
# added = False
# try:
# if not hasattr(cls, 'TutelaryMeta'):
# if perm_type is None or path_fields is None or actions is None:
# raise DecoratorException(
# 'permissioned_model',
# ("missing argument: all of perm_type, path_fields and " +
# "actions must be supplied")
# )
# added = True
# cls.TutelaryMeta = type('TutelaryMeta', (object,),
# dict(perm_type=perm_type,
# path_fields=path_fields,
# actions=actions))
# cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
# get_path_fields(cls))
# perms_objs = {}
# for a in cls.TutelaryMeta.actions:
# an = a
# ap = {}
# if isinstance(a, tuple):
# an = a[0]
# ap = a[1]
# Action.register(an)
# if isinstance(ap, dict) and 'permissions_object' in ap:
# po = ap['permissions_object']
# if po is not None:
# try:
# t = cls._meta.get_field(po).__class__
# if t not in [models.ForeignKey,
# models.OneToOneField]:
# raise PermissionObjectException(po)
# except:
# raise PermissionObjectException(po)
# perms_objs[an] = po
# if len(perms_objs) == 0:
# cls.get_permissions_object = get_perms_object
# else:
# cls.get_permissions_object = make_get_perms_object(perms_objs)
# return cls
# except:
# if added:
# del cls.TutelaryMeta
# raise
, which may contain function names, class names, or code. Output only the next line. | Policy, perm_type='policy', path_fields=['name'], |
Using the snippet: <|code_start|> """
policy = models.ForeignKey('Policy', on_delete=models.PROTECT)
role = models.ForeignKey('Role', on_delete=models.CASCADE)
index = models.IntegerField()
"""Integer index used to order the sequence of policies composing a
role.
"""
class Meta:
ordering = ['index']
def __str__(self):
return "role={} policy={}".format(self.role.name, self.policy.name)
class RoleManager(models.Manager):
"""Custom manager for roles: ensures that role variable assignments
cover all the variables used in the role's policies.
"""
def create(self, name, policies=None, variables=None):
policies = policies or []
variables = variables or {}
role = super().create(name=name, variables=variables)
variable_names = set().union(*[p.variable_names() for p in policies])
if not variable_names.issubset(variables.keys()):
<|code_end|>
, determine the next line of code. You have imports:
import json
import re
import tutelary.engine as engine
from django.db import models
from django.conf import settings
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from audit_log.models.managers import AuditLog
from tutelary.exceptions import RoleVariableException
and context (class names, function names, or code) available:
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
. Output only the next line. | raise RoleVariableException("missing variable in role definition") |
Predict the next line after this snippet: <|code_start|>
class Backend:
"""Custom authentication backend: dispatches ``has_perm`` queries to
the user's permission set.
"""
@staticmethod
def _obj_ok(obj):
return obj is None or callable(obj) or isinstance(obj, Object)
def has_perm(self, user, perm, obj=None, *args, **kwargs):
"""Test user permissions for a single action and object.
:param user: The user to test.
:type user: ``User``
:param perm: The action to test.
:type perm: ``str``
:param obj: The object path to test.
:type obj: ``tutelary.engine.Object``
:returns: ``bool`` -- is the action permitted?
"""
try:
if not self._obj_ok(obj):
if hasattr(obj, 'get_permissions_object'):
obj = obj.get_permissions_object(perm)
else:
<|code_end|>
using the current file's imports:
from django.core.exceptions import ObjectDoesNotExist
from .exceptions import InvalidPermissionObjectException
from .engine import Action, Object
and any relevant context from other files:
# Path: tutelary/exceptions.py
# class InvalidPermissionObjectException(TutelaryException):
# """Exception raised by authentication backend if the object passed to
# backend methods is not either a ``tutelary.engine.Object`` or a
# Django model instance with a ``get_permissions_object`` method.
#
# """
# def __init__(self):
# super().__init__("invalid object passed to django-tutelary " +
# "backend method")
#
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
. Output only the next line. | raise InvalidPermissionObjectException |
Continue the code snippet: <|code_start|>
class Backend:
"""Custom authentication backend: dispatches ``has_perm`` queries to
the user's permission set.
"""
@staticmethod
def _obj_ok(obj):
return obj is None or callable(obj) or isinstance(obj, Object)
def has_perm(self, user, perm, obj=None, *args, **kwargs):
"""Test user permissions for a single action and object.
:param user: The user to test.
:type user: ``User``
:param perm: The action to test.
:type perm: ``str``
:param obj: The object path to test.
:type obj: ``tutelary.engine.Object``
:returns: ``bool`` -- is the action permitted?
"""
try:
if not self._obj_ok(obj):
if hasattr(obj, 'get_permissions_object'):
obj = obj.get_permissions_object(perm)
else:
raise InvalidPermissionObjectException
<|code_end|>
. Use current file imports:
from django.core.exceptions import ObjectDoesNotExist
from .exceptions import InvalidPermissionObjectException
from .engine import Action, Object
and context (classes, functions, or code) from other files:
# Path: tutelary/exceptions.py
# class InvalidPermissionObjectException(TutelaryException):
# """Exception raised by authentication backend if the object passed to
# backend methods is not either a ``tutelary.engine.Object`` or a
# Django model instance with a ``get_permissions_object`` method.
#
# """
# def __init__(self):
# super().__init__("invalid object passed to django-tutelary " +
# "backend method")
#
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
. Output only the next line. | return user.permset_tree.allow(Action(perm), obj) |
Using the snippet: <|code_start|>
class Backend:
"""Custom authentication backend: dispatches ``has_perm`` queries to
the user's permission set.
"""
@staticmethod
def _obj_ok(obj):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.exceptions import ObjectDoesNotExist
from .exceptions import InvalidPermissionObjectException
from .engine import Action, Object
and context (class names, function names, or code) available:
# Path: tutelary/exceptions.py
# class InvalidPermissionObjectException(TutelaryException):
# """Exception raised by authentication backend if the object passed to
# backend methods is not either a ``tutelary.engine.Object`` or a
# Django model instance with a ``get_permissions_object`` method.
#
# """
# def __init__(self):
# super().__init__("invalid object passed to django-tutelary " +
# "backend method")
#
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
. Output only the next line. | return obj is None or callable(obj) or isinstance(obj, Object) |
Predict the next line for this snippet: <|code_start|>
{'effect': 'allow',
'action': ['organisation.list']},
{'effect': 'allow',
'action': ['organisation.detail'],
'object': ['organisation/*']},
{'effect': 'allow',
'action': ['project.list'],
'object': ['organisation/*']},
{'effect': 'allow',
'action': ['project.detail'],
'object': ['project/*/*']},
{'effect': 'allow',
'action': ['user.list']},
{'effect': 'allow',
'action': ['user.detail'],
'object': ['user/*']},
{'effect': 'allow',
'action': ['policy.list']},
{'effect': 'allow',
'action': ['policy.detail'],
'object': ['policy/*']},
{'effect': 'deny',
'action': 'statistics'}
]
}
<|code_end|>
with the help of current file imports:
import json
import itertools
from django.contrib.auth.models import User
from tutelary.models import Policy, assign_user_policies
from exampleapp.models import (
Organisation, Project, Party, Parcel, UserPolicyAssignment
)
and context from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
, which may contain function names, class names, or code. Output only the next line. | default_p = Policy(name='default', body=json.dumps(default_p_body)) |
Given the code snippet: <|code_start|> u.assign_policies(*pols)
u.save()
for p, i in zip(pols, itertools.count()):
attrs = {}
if isinstance(p, tuple):
attrs = p[1]
p = p[0]
org = None
proj = None
if 'organisation' in attrs:
org = Organisation.objects.get(name=attrs['organisation'])
if 'project' in attrs:
proj = Project.objects.get(name=attrs['project'])
if org is not None and proj is not None:
ups = UserPolicyAssignment.objects.create(
user=u, policy=p, index=i,
organisation=org, project=proj
)
elif org is not None:
ups = UserPolicyAssignment.objects.create(
user=u, policy=p, index=i,
organisation=org
)
else:
ups = UserPolicyAssignment.objects.create(
user=u, policy=p, index=i
)
ups.save()
<|code_end|>
, generate the next line using the imports in this file:
import json
import itertools
from django.contrib.auth.models import User
from tutelary.models import Policy, assign_user_policies
from exampleapp.models import (
Organisation, Project, Party, Parcel, UserPolicyAssignment
)
and context (functions, classes, or occasionally code) from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
. Output only the next line. | assign_user_policies(None, default_p) |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
PolicyFactory.set_directory(str(datadir))
def_pol = PolicyFactory.create(name='def', file='default-policy.json')
org_pol = PolicyFactory.create(name='org', file='org-policy.json')
prj_pol = PolicyFactory.create(name='prj', file='project-policy.json')
deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json')
Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view',
'party.edit', 'parcel.edit'])
<|code_end|>
with the help of current file imports:
from tutelary.models import assign_user_policies
from tutelary.engine import Object, Action
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_backends
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
, which may contain function names, class names, or code. Output only the next line. | assign_user_policies(None, def_pol) |
Given snippet: <|code_start|> prj_pol = PolicyFactory.create(name='prj', file='project-policy.json')
deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json')
Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view',
'party.edit', 'parcel.edit'])
assign_user_policies(None, def_pol)
user1.assign_policies(def_pol)
user2.assign_policies(def_pol,
(org_pol, {'organisation': 'Cadasta'}))
user3.assign_policies(def_pol,
(org_pol, {'organisation': 'Cadasta'}),
(prj_pol, {'organisation': 'Cadasta',
'project': 'TestProj'}),
(deny_pol, {'organisation': 'Cadasta',
'project': 'Proj2'}))
user4.assign_policies(def_pol,
(org_pol, {'organisation': 'OtherOrg'}))
user5.assign_policies(def_pol,
(org_pol, {'organisation': 'Cadasta'}),
(prj_pol, {'organisation': 'Cadasta',
'project': 'TestProj2'}))
return (user1, user2, user3, user4, user5,
def_pol, org_pol, prj_pol, deny_pol)
def test_basic(datadir, setup): # noqa
u1, u2, u3, u4, u5, def_pol, org_pol, prj_pol, deny_pol = setup
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tutelary.models import assign_user_policies
from tutelary.engine import Object, Action
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_backends
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
which might include code, classes, or functions. Output only the next line. | obj1 = Object('parcel/Cadasta/TestProj/123') |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
PolicyFactory.set_directory(str(datadir))
def_pol = PolicyFactory.create(name='def', file='default-policy.json')
org_pol = PolicyFactory.create(name='org', file='org-policy.json')
prj_pol = PolicyFactory.create(name='prj', file='project-policy.json')
deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json')
<|code_end|>
with the help of current file imports:
from tutelary.models import assign_user_policies
from tutelary.engine import Object, Action
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_backends
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
, which may contain function names, class names, or code. Output only the next line. | Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view', |
Here is a snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
<|code_end|>
. Write the next line using the current file imports:
from tutelary.models import assign_user_policies
from tutelary.engine import Object, Action
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_backends
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
, which may include functions, classes, or code. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Given snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tutelary.models import (
PermissionSet, Policy, PolicyInstance
)
from tutelary.engine import Object
from django.contrib.auth.models import User
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context:
# Path: tutelary/models.py
# class PermissionSet(models.Model):
# """A permission set represents the complete set of permissions
# resulting from the composition of a sequence of policy instances.
# The sequence of policy instances is recorded using the
# ``PolicyInstance`` model and the permission tree is constructed
# lazily from this information when the permission set is read from
# the database.
#
# """
# # Ordered set of policies used to generate this permission set.
# policy_assign = models.ManyToManyField(Policy, through=PolicyInstance)
#
# # Users to which this permission set is attached: a user has only
# # one permission set, so this is really an 1:m relation, not an
# # n:m relation.
# users = models.ManyToManyField(settings.AUTH_USER_MODEL,
# related_name='permissionset')
# anonymous_user = models.BooleanField(default=False)
#
# # Custom manager to deal with folding together permission sets
# # generated from identical sequences of policies.
# objects = PermissionSetManager()
#
# def cache_key(self):
# return 'tutelary:ptree:' + str(self.pk)
#
# def tree(self):
# key = self.cache_key()
# cached = cache.get(key)
# if cached is None:
# ptree = engine.PermissionTree(
# policies=[engine.PolicyBody(json=pi.policy.body,
# variables=json.loads(pi.variables))
# for pi in (PolicyInstance.objects
# .select_related('policy')
# .filter(pset=self))]
# )
# cache.set(key, ptree)
# cached = ptree
# return cached
#
# def refresh(self):
# cache.set(self.cache_key(), None)
#
# def __str__(self):
# return str(self.pk)
#
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# class PolicyInstance(models.Model):
# """An instance of a policy provides fixed values for any variables
# used in the policy's body. An ordered sequence of policy
# instances defines a permission set.
#
# """
#
# policy = models.ForeignKey(Policy, on_delete=models.PROTECT)
#
# pset = models.ForeignKey('PermissionSet', on_delete=models.CASCADE)
#
# index = models.IntegerField()
# """Integer index used to order the sequence of policies composing a
# permission set.
#
# """
#
# role = models.ForeignKey(Role, null=True, on_delete=models.PROTECT)
# """The role that this policy instance is associated with, if any."""
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for policy
# instance.
#
# """
#
# class Meta:
# ordering = ['index']
#
# def __str__(self):
# return "policy={} pset={} index={} role={} variables={}".format(
# self.policy.name, self.pset.pk, self.index,
# self.role.name if self.role else "NULL",
# self.variables
# )
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
which might include code, classes, or functions. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Given snippet: <|code_start|>
def get_path_fields(cls, base=[]):
"""Get object fields used for calculation of django-tutelary object
paths.
"""
pfs = []
for pf in cls.TutelaryMeta.path_fields:
if pf == 'pk':
pfs.append(base + ['pk'])
else:
f = cls._meta.get_field(pf)
if isinstance(f, models.ForeignKey):
pfs += get_path_fields(f.target_field.model, base=base + [pf])
else:
pfs.append(base + [f.name])
return pfs
def get_perms_object(obj, action):
"""Get the django-tutelary path for an object, based on the fields
listed in ``TutelaryMeta.pfs``.
"""
def get_one(pf):
if isinstance(pf, str):
return pf
else:
return str(reduce(lambda o, f: getattr(o, f), pf, obj))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from functools import reduce, wraps
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.decorators import available_attrs
from .engine import Object, Action
from .models import check_perms
from .exceptions import DecoratorException, PermissionObjectException
and context:
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/exceptions.py
# class DecoratorException(TutelaryException):
# """Exception raised if the ``permissioned_model`` decorator is used
# without the required ``TutelaryMeta`` class member being included
# in the model.
#
# """
# def __init__(self, decorator, msg):
# super().__init__(
# "error expanding decorator '" + decorator + "': " + msg
# )
#
# class PermissionObjectException(TutelaryException):
# """Exception raised by the ``permissioned_model`` decorator if a
# ``permissions_object`` property in the ``actions`` list refers to
# a non-existent model field, or to a field that is not a foreign
# key or one-to-one relation field.
#
# """
# def __init__(self, prop):
# super().__init__(
# "invalid permissions_object property '" + prop +
# "' in permissioned_model"
# )
which might include code, classes, or functions. Output only the next line. | return Object([get_one(pf) for pf in obj.__class__.TutelaryMeta.pfs]) |
Given the code snippet: <|code_start|>
"""
if not issubclass(cls, models.Model):
raise DecoratorException(
'permissioned_model',
"class '" + cls.__name__ + "' is not a Django model"
)
added = False
try:
if not hasattr(cls, 'TutelaryMeta'):
if perm_type is None or path_fields is None or actions is None:
raise DecoratorException(
'permissioned_model',
("missing argument: all of perm_type, path_fields and " +
"actions must be supplied")
)
added = True
cls.TutelaryMeta = type('TutelaryMeta', (object,),
dict(perm_type=perm_type,
path_fields=path_fields,
actions=actions))
cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
get_path_fields(cls))
perms_objs = {}
for a in cls.TutelaryMeta.actions:
an = a
ap = {}
if isinstance(a, tuple):
an = a[0]
ap = a[1]
<|code_end|>
, generate the next line using the imports in this file:
from functools import reduce, wraps
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.decorators import available_attrs
from .engine import Object, Action
from .models import check_perms
from .exceptions import DecoratorException, PermissionObjectException
and context (functions, classes, or occasionally code) from other files:
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/exceptions.py
# class DecoratorException(TutelaryException):
# """Exception raised if the ``permissioned_model`` decorator is used
# without the required ``TutelaryMeta`` class member being included
# in the model.
#
# """
# def __init__(self, decorator, msg):
# super().__init__(
# "error expanding decorator '" + decorator + "': " + msg
# )
#
# class PermissionObjectException(TutelaryException):
# """Exception raised by the ``permissioned_model`` decorator if a
# ``permissions_object`` property in the ``actions`` list refers to
# a non-existent model field, or to a field that is not a foreign
# key or one-to-one relation field.
#
# """
# def __init__(self, prop):
# super().__init__(
# "invalid permissions_object property '" + prop +
# "' in permissioned_model"
# )
. Output only the next line. | Action.register(an) |
Given the following code snippet before the placeholder: <|code_start|>
def permission_required(*actions, obj=None, raise_exception=False):
"""Permission checking decorator -- works like the
``permission_required`` decorator in the default Django
authentication system, except that it takes a sequence of actions
to check, an object must be supplied, and the user must have
permission to perform all of the actions on the given object for
the permissions test to pass. *Not actually sure how useful this
is going to be: in any case where obj is not None, it's going to
be tricky to get the object into the decorator. Class-based views
are definitely best here...*
"""
def checker(user):
ok = False
<|code_end|>
, predict the next line using imports from the current file:
from functools import reduce, wraps
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.decorators import available_attrs
from .engine import Object, Action
from .models import check_perms
from .exceptions import DecoratorException, PermissionObjectException
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/exceptions.py
# class DecoratorException(TutelaryException):
# """Exception raised if the ``permissioned_model`` decorator is used
# without the required ``TutelaryMeta`` class member being included
# in the model.
#
# """
# def __init__(self, decorator, msg):
# super().__init__(
# "error expanding decorator '" + decorator + "': " + msg
# )
#
# class PermissionObjectException(TutelaryException):
# """Exception raised by the ``permissioned_model`` decorator if a
# ``permissions_object`` property in the ``actions`` list refers to
# a non-existent model field, or to a field that is not a foreign
# key or one-to-one relation field.
#
# """
# def __init__(self, prop):
# super().__init__(
# "invalid permissions_object property '" + prop +
# "' in permissioned_model"
# )
. Output only the next line. | if user.is_authenticated() and check_perms(user, actions, [obj]): |
Given the code snippet: <|code_start|> return Object([get_one(pf) for pf in obj.__class__.TutelaryMeta.pfs])
def make_get_perms_object(perms_objs):
"""Make a function to delegate permission object rendering to some
other (foreign key) field of an object.
"""
def retfn(obj, action):
if action in perms_objs:
if perms_objs[action] is None:
return None
else:
return get_perms_object(getattr(obj, perms_objs[action]),
action)
else:
return get_perms_object(obj, action)
return retfn
def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
"""Function to set up a model for permissioning. Can either be called
directly, passing a class and suitable values for ``perm_type``,
``path_fields`` and ``actions``, or can be used as a class
decorator, taking values for ``perm_type``, ``path_fields`` and
``actions`` from the ``TutelaryMeta`` subclass of the decorated
class.
"""
if not issubclass(cls, models.Model):
<|code_end|>
, generate the next line using the imports in this file:
from functools import reduce, wraps
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.decorators import available_attrs
from .engine import Object, Action
from .models import check_perms
from .exceptions import DecoratorException, PermissionObjectException
and context (functions, classes, or occasionally code) from other files:
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/exceptions.py
# class DecoratorException(TutelaryException):
# """Exception raised if the ``permissioned_model`` decorator is used
# without the required ``TutelaryMeta`` class member being included
# in the model.
#
# """
# def __init__(self, decorator, msg):
# super().__init__(
# "error expanding decorator '" + decorator + "': " + msg
# )
#
# class PermissionObjectException(TutelaryException):
# """Exception raised by the ``permissioned_model`` decorator if a
# ``permissions_object`` property in the ``actions`` list refers to
# a non-existent model field, or to a field that is not a foreign
# key or one-to-one relation field.
#
# """
# def __init__(self, prop):
# super().__init__(
# "invalid permissions_object property '" + prop +
# "' in permissioned_model"
# )
. Output only the next line. | raise DecoratorException( |
Continue the code snippet: <|code_start|> try:
if not hasattr(cls, 'TutelaryMeta'):
if perm_type is None or path_fields is None or actions is None:
raise DecoratorException(
'permissioned_model',
("missing argument: all of perm_type, path_fields and " +
"actions must be supplied")
)
added = True
cls.TutelaryMeta = type('TutelaryMeta', (object,),
dict(perm_type=perm_type,
path_fields=path_fields,
actions=actions))
cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
get_path_fields(cls))
perms_objs = {}
for a in cls.TutelaryMeta.actions:
an = a
ap = {}
if isinstance(a, tuple):
an = a[0]
ap = a[1]
Action.register(an)
if isinstance(ap, dict) and 'permissions_object' in ap:
po = ap['permissions_object']
if po is not None:
try:
t = cls._meta.get_field(po).__class__
if t not in [models.ForeignKey,
models.OneToOneField]:
<|code_end|>
. Use current file imports:
from functools import reduce, wraps
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.decorators import available_attrs
from .engine import Object, Action
from .models import check_perms
from .exceptions import DecoratorException, PermissionObjectException
and context (classes, functions, or code) from other files:
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/exceptions.py
# class DecoratorException(TutelaryException):
# """Exception raised if the ``permissioned_model`` decorator is used
# without the required ``TutelaryMeta`` class member being included
# in the model.
#
# """
# def __init__(self, decorator, msg):
# super().__init__(
# "error expanding decorator '" + decorator + "': " + msg
# )
#
# class PermissionObjectException(TutelaryException):
# """Exception raised by the ``permissioned_model`` decorator if a
# ``permissions_object`` property in the ``actions`` list refers to
# a non-existent model field, or to a field that is not a foreign
# key or one-to-one relation field.
#
# """
# def __init__(self, prop):
# super().__init__(
# "invalid permissions_object property '" + prop +
# "' in permissioned_model"
# )
. Output only the next line. | raise PermissionObjectException(po) |
Given snippet: <|code_start|>
return (user1, user2, user3, user4, user5,
def_pol, org_pol, prj_pol, deny_pol)
def test_roles_creation(datadir, setup): # noqa
u1, u2, u3, u4, u5, def_pol, org_pol, prj_pol, deny_pol = setup
cadasta_org_role = Role.objects.create(
name='cadasta_org', policies=[def_pol, org_pol],
variables={'organisation': 'Cadasta'}
)
cadasta_org_role.save()
assert str(cadasta_org_role) == 'cadasta_org'
testproj_proj_role = Role.objects.create(
name='testproj_proj', policies=[def_pol, org_pol, prj_pol],
variables={'organisation': 'Cadasta', 'project': 'TestProj'}
)
testproj_proj_role.save()
proj2_proj_role = Role.objects.create(
name='proj2_proj', policies=[def_pol, org_pol, prj_pol],
variables={'organisation': 'Cadasta', 'project': 'Proj2'}
)
proj2_proj_role.save()
other_org_role = Role.objects.create(
name='other_org', policies=[def_pol, org_pol],
variables={'organisation': 'OtherOrg'}
)
other_org_role.save()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
which might include code, classes, or functions. Output only the next line. | assign_user_policies(None, cadasta_org_role) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
PolicyFactory.set_directory(str(datadir))
def_pol = PolicyFactory.create(name='def', file='default-policy.json')
org_pol = PolicyFactory.create(name='org', file='org-policy.json')
prj_pol = PolicyFactory.create(name='prj', file='project-policy.json')
deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json')
Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view',
'party.edit', 'parcel.edit'])
return (user1, user2, user3, user4, user5,
def_pol, org_pol, prj_pol, deny_pol)
def test_roles_creation(datadir, setup): # noqa
u1, u2, u3, u4, u5, def_pol, org_pol, prj_pol, deny_pol = setup
<|code_end|>
using the current file's imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and any relevant context from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | cadasta_org_role = Role.objects.create( |
Given snippet: <|code_start|> name='cadasta_org', policies=[def_pol, org_pol],
variables={'organisation': 'Cadasta'}
)
cadasta_org_role.save()
assert str(cadasta_org_role) == 'cadasta_org'
testproj_proj_role = Role.objects.create(
name='testproj_proj', policies=[def_pol, org_pol, prj_pol],
variables={'organisation': 'Cadasta', 'project': 'TestProj'}
)
testproj_proj_role.save()
proj2_proj_role = Role.objects.create(
name='proj2_proj', policies=[def_pol, org_pol, prj_pol],
variables={'organisation': 'Cadasta', 'project': 'Proj2'}
)
proj2_proj_role.save()
other_org_role = Role.objects.create(
name='other_org', policies=[def_pol, org_pol],
variables={'organisation': 'OtherOrg'}
)
other_org_role.save()
assign_user_policies(None, cadasta_org_role)
u1.assign_policies(def_pol)
u2.assign_policies(cadasta_org_role)
u3.assign_policies(testproj_proj_role,
(deny_pol, {'organisation': 'Cadasta',
'project': 'Proj2'}))
u4.assign_policies(other_org_role)
u5.assign_policies(proj2_proj_role)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
which might include code, classes, or functions. Output only the next line. | obj1 = Object('parcel/Cadasta/TestProj/123') |
Based on the snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
PolicyFactory.set_directory(str(datadir))
def_pol = PolicyFactory.create(name='def', file='default-policy.json')
org_pol = PolicyFactory.create(name='org', file='org-policy.json')
prj_pol = PolicyFactory.create(name='prj', file='project-policy.json')
deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json')
<|code_end|>
, predict the immediate next line with the help of imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view', |
Using the snippet: <|code_start|> obj2 = Object('parcel/Cadasta/Proj2/114')
assert not u1.has_perm('parcel.view', obj2)
assert u2.has_perm('parcel.view', obj2)
assert u3.has_perm('parcel.view', obj2)
obj3 = Object('parcel/SkunkWorks/SR-71/Area51')
assert not u1.has_perm('parcel.view', obj3)
assert not u2.has_perm('parcel.view', obj3)
assert not u3.has_perm('parcel.view', obj3)
def test_roles_policies_variables(datadir, setup): # noqa
u1, u2, u3, u4, u5, def_pol, org_pol, prj_pol, deny_pol = setup
assert def_pol.variable_names() == set()
assert org_pol.variable_names() == {'organisation'}
assert prj_pol.variable_names() == {'organisation', 'project'}
org_role = Role.objects.create(
name='cadasta_org', policies=[def_pol, org_pol],
variables={'organisation': 'Cadasta'}
)
assert org_role.variable_names() == {'organisation'}
testproj_proj_role = Role.objects.create(
name='testproj_proj', policies=[def_pol, org_pol, prj_pol],
variables={'organisation': 'Cadasta', 'project': 'TestProj'}
)
testproj_proj_role.save()
assert testproj_proj_role.variable_names() == {'organisation', 'project'}
<|code_end|>
, determine the next line of code. You have imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context (class names, function names, or code) available:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | with pytest.raises(RoleVariableException): |
Here is a snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
user4 = UserFactory.create(username='user4')
user5 = UserFactory.create(username='user5')
<|code_end|>
. Write the next line using the current file imports:
from tutelary.models import (assign_user_policies, Role)
from tutelary.engine import Object, Action
from tutelary.exceptions import RoleVariableException
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
import pytest
and context from other files:
# Path: tutelary/models.py
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# Path: tutelary/engine.py
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/exceptions.py
# class RoleVariableException(TutelaryException):
# """Exception raised for missing or illegal variable substitutions for
# permissions roles.
#
# """
# def __init__(self, msg):
# super().__init__("illegal role variables: " + msg)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
, which may include functions, classes, or code. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Given snippet: <|code_start|> variables={'org': 'Org1', 'proj': 'Proj1'}
)
proj_mgr_2_r = RoleFactory.create(
name='proj-mgr', policies=[pols[2]],
variables={'org': 'Org2', 'proj': 'Proj2'}
)
roles = [sys_admin_r,
org_admin_1_r, org_admin_2_r,
proj_mgr_1_r, proj_mgr_2_r]
users[1].assign_policies(sys_admin_p)
users[2].assign_policies(sys_admin_r)
users[3].assign_policies(org_admin_1_r)
users[4].assign_policies(org_admin_2_r)
users[5].assign_policies(org_admin_1_r, org_admin_2_r)
users[6].assign_policies(org_admin_1_r, proj_mgr_2_r)
users[7].assign_policies(proj_mgr_1_r)
users[8].assign_policies((org_admin_p, {'org': 'Org3'}))
users[9].assign_policies((org_admin_p, {'org': 'Org3'}),
(proj_mgr_p, {'org': 'Org3', 'proj': 'Proj3'}))
return (users, pols, roles)
def test_role_lookup(datadir, setup): # noqa
users, pols, roles = setup
(sys_admin_r,
org_admin_1_r, org_admin_2_r,
proj_mgr_1_r, proj_mgr_2_r) = roles
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
which might include code, classes, or functions. Output only the next line. | assert list(Role.objects.filter(name='sys-admin')) == [sys_admin_r] |
Predict the next line for this snippet: <|code_start|> assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org1'})) ==
[org_admin_1_r])
assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org2'})) ==
[org_admin_2_r])
assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org3'})) == [])
assert (set(Role.objects.filter(name='proj-mgr')) ==
set([proj_mgr_1_r, proj_mgr_2_r]))
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org1',
'proj': 'Proj1'})) ==
[proj_mgr_1_r])
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org2',
'proj': 'Proj2'})) ==
[proj_mgr_2_r])
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org3',
'proj': 'Proj3'})) == [])
def test_lookup_user_policies_and_roles(datadir, setup): # noqa
users, pols, roles = setup
sys_admin_p, org_admin_p, proj_mgr_p = pols
(sys_admin_r,
org_admin_1_r, org_admin_2_r,
proj_mgr_1_r, proj_mgr_2_r) = roles
assert user_assigned_policies(None) == []
<|code_end|>
with the help of current file imports:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context from other files:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
, which may contain function names, class names, or code. Output only the next line. | assign_user_policies(None, (org_admin_p, {'org': 'Sandbox'})) |
Continue the code snippet: <|code_start|> set([org_admin_1_r, org_admin_2_r]))
assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org1'})) ==
[org_admin_1_r])
assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org2'})) ==
[org_admin_2_r])
assert (list(Role.objects.filter(name='org-admin',
variables={'org': 'Org3'})) == [])
assert (set(Role.objects.filter(name='proj-mgr')) ==
set([proj_mgr_1_r, proj_mgr_2_r]))
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org1',
'proj': 'Proj1'})) ==
[proj_mgr_1_r])
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org2',
'proj': 'Proj2'})) ==
[proj_mgr_2_r])
assert (list(Role.objects.filter(name='proj-mgr',
variables={'org': 'Org3',
'proj': 'Proj3'})) == [])
def test_lookup_user_policies_and_roles(datadir, setup): # noqa
users, pols, roles = setup
sys_admin_p, org_admin_p, proj_mgr_p = pols
(sys_admin_r,
org_admin_1_r, org_admin_2_r,
proj_mgr_1_r, proj_mgr_2_r) = roles
<|code_end|>
. Use current file imports:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context (classes, functions, or code) from other files:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
. Output only the next line. | assert user_assigned_policies(None) == [] |
Given the code snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
for i in range(1, 11):
<|code_end|>
, generate the next line using the imports in this file:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
. Output only the next line. | users.append(UserFactory.create(username='user{}'.format(i))) |
Using the snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
for i in range(1, 11):
users.append(UserFactory.create(username='user{}'.format(i)))
<|code_end|>
, determine the next line of code. You have imports:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context (class names, function names, or code) available:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Continue the code snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
users = []
for i in range(1, 11):
users.append(UserFactory.create(username='user{}'.format(i)))
PolicyFactory.set_directory(str(datadir))
sys_admin_p = PolicyFactory.create(name='sys-admin', file='sys-admin.json')
org_admin_p = PolicyFactory.create(name='org-admin', file='org-admin.json')
proj_mgr_p = PolicyFactory.create(name='proj-mgr', file='proj-mgr.json')
pols = [sys_admin_p, org_admin_p, proj_mgr_p]
<|code_end|>
. Use current file imports:
from tutelary.models import Role, assign_user_policies, user_assigned_policies
from .datadir import datadir # noqa
from .factories import UserFactory, PolicyFactory, RoleFactory
import pytest
and context (classes, functions, or code) from other files:
# Path: tutelary/models.py
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
#
# def assign_user_policies(user, *policies_roles):
# """Assign a sequence of policies to a user (or the anonymous user is
# ``user`` is ``None``). (Also installed as ``assign_policies``
# method on ``User`` model.
#
# """
# clear_user_policies(user)
# pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
# pset.refresh()
# if user is None:
# pset.anonymous_user = True
# else:
# pset.users.add(user)
# pset.save()
# cache.set(user_cache_key(user), None)
#
# def user_assigned_policies(user):
# """Return sequence of policies assigned to a user (or the anonymous
# user is ``user`` is ``None``). (Also installed as
# ``assigned_policies`` method on ``User`` model.
#
# """
# key = user_cache_key(user)
# cached = cache.get(key)
# if cached is not None:
# return cached
#
# if user is None:
# pset = PermissionSet.objects.filter(anonymous_user=True).first()
# else:
# pset = user.permissionset.first()
# if pset is None:
# return []
#
# res = []
# skip_role_policies = False
# skip_role = None
# skip_role_variables = None
# for pi in pset.policyinstance_set.select_related('policy', 'role'):
# if skip_role_policies:
# if pi.role == skip_role and pi.variables == skip_role_variables:
# continue
# else:
# skip_role_policies = False
# if pi.role:
# res.append(pi.role)
# skip_role = pi.role
# skip_role_variables = pi.variables
# skip_role_policies = True
# else:
# if pi.variables != '{}':
# res.append((pi.policy, json.loads(pi.variables)))
# else:
# res.append(pi.policy)
# cache.set(key, res)
# return res
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# class RoleFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Role
. Output only the next line. | sys_admin_r = RoleFactory.create( |
Here is a snippet: <|code_start|>
def test_sequence_creation_empty():
seq1 = SimpleSeparated(None)
assert len(seq1) == 0
assert seq1.components == []
def test_sequence_creation_components():
seq2 = SimpleSeparated(['parcel', 'list'])
assert len(seq2) == 2
assert seq2.components == ['parcel', 'list']
def test_sequence_creation_bad():
with pytest.raises(ValueError):
SimpleSeparated(123)
def test_action_creation():
<|code_end|>
. Write the next line using the current file imports:
import pytest
from tutelary.engine import Action, Object, SimpleSeparated
and context from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class SimpleSeparated(Sequence):
# """Simple sequences of strings delimited by a separator, with
# wildcarding.
#
# A wildcard component is represented by a ``*`` string and matches
# any single string component. Equality comparison between
# sequences is exact comparison of components; matching between
# wildcarded components can be tested using the ``match`` method.
#
# """
# def __init__(self, s):
# if s is None:
# self.components = []
# elif isinstance(s, str):
# self.components = self._split_components(s)
# elif isinstance(s, Sequence):
# self.components = s
# else:
# raise ValueError('invalid initialiser for separated sequence')
#
# def _split_components(self, s):
# return s.split(self.separator)
#
# def __len__(self):
# return len(self.components)
#
# def __getitem__(self, idx):
# return self.components[idx]
#
# def __str__(self):
# return self.separator.join(self.components)
#
# def __repr__(self):
# return '{}({!r})'.format(self.__class__.__name__, str(self))
#
# def __eq__(self, other):
# return self.components == other.components
#
# def __hash__(self):
# return hash(str(self))
#
# def match(self, other):
# # Two sequences match if they are the same length and
# # corresponding components are either equal, or at least one
# # is a wildcard.
# if len(self) != len(other):
# return False
# for cself, cother in zip(self.components, other.components):
# if not (cself == cother or cself == '*' or cother == '*'):
# return False
# return True
, which may include functions, classes, or code. Output only the next line. | act1 = Action('parcel.edit') |
Continue the code snippet: <|code_start|>
def test_sequence_creation_empty():
seq1 = SimpleSeparated(None)
assert len(seq1) == 0
assert seq1.components == []
def test_sequence_creation_components():
seq2 = SimpleSeparated(['parcel', 'list'])
assert len(seq2) == 2
assert seq2.components == ['parcel', 'list']
def test_sequence_creation_bad():
with pytest.raises(ValueError):
SimpleSeparated(123)
def test_action_creation():
act1 = Action('parcel.edit')
assert act1[0] == 'parcel'
assert act1[1] == 'edit'
assert str(act1) == 'parcel.edit'
def test_object_creation():
<|code_end|>
. Use current file imports:
import pytest
from tutelary.engine import Action, Object, SimpleSeparated
and context (classes, functions, or code) from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# class Object(EscapeSeparated):
# """Objects are represented by slash-separated sequences of elements
# (e.g. ``Cadasta/Batangas/parcel/123``, ``H4H/PaP/party/118``) with
# wildcard elements indicated by ``*``
# (e.g. ``Cadasta/*/parcel/*``). Slashes can be backslash-escaped,
# as can backslashes (e.g. ``Cadasta/Village-X\/Y/parcel/943``).
#
# """
# separator = '/'
#
# class SimpleSeparated(Sequence):
# """Simple sequences of strings delimited by a separator, with
# wildcarding.
#
# A wildcard component is represented by a ``*`` string and matches
# any single string component. Equality comparison between
# sequences is exact comparison of components; matching between
# wildcarded components can be tested using the ``match`` method.
#
# """
# def __init__(self, s):
# if s is None:
# self.components = []
# elif isinstance(s, str):
# self.components = self._split_components(s)
# elif isinstance(s, Sequence):
# self.components = s
# else:
# raise ValueError('invalid initialiser for separated sequence')
#
# def _split_components(self, s):
# return s.split(self.separator)
#
# def __len__(self):
# return len(self.components)
#
# def __getitem__(self, idx):
# return self.components[idx]
#
# def __str__(self):
# return self.separator.join(self.components)
#
# def __repr__(self):
# return '{}({!r})'.format(self.__class__.__name__, str(self))
#
# def __eq__(self, other):
# return self.components == other.components
#
# def __hash__(self):
# return hash(str(self))
#
# def match(self, other):
# # Two sequences match if they are the same length and
# # corresponding components are either equal, or at least one
# # is a wildcard.
# if len(self) != len(other):
# return False
# for cself, cother in zip(self.components, other.components):
# if not (cself == cother or cself == '*' or cother == '*'):
# return False
# return True
. Output only the next line. | obj1 = Object('Cadasta/Batangas/parcel/123') |
Given the following code snippet before the placeholder: <|code_start|> perms = perms(self, self.request)
if isinstance(perms, str):
perms = (perms, )
return perms
def get_permission_denied_message(self, default=None):
if hasattr(self, 'permission_denied_message'):
return (self.permission_denied_message,)
if hasattr(self, 'model') and hasattr(self.model, 'TutelaryMeta'):
return action_error_message(self.model.TutelaryMeta.actions,
self.get_permission_required(),
default)
def get_queryset(self):
if hasattr(self, 'filtered_queryset'):
return self.filtered_queryset
else:
return super().get_queryset()
def perms_filter_queryset(self, objs):
actions = self.get_permission_required()
if isinstance(self.permission_filter_queryset, Sequence):
actions += tuple(self.permission_filter_queryset)
def check_one(obj):
check_actions = actions
if callable(self.permission_filter_queryset):
check_actions += self.permission_filter_queryset(self, obj)
<|code_end|>
, predict the next line using imports from the current file:
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from collections.abc import Sequence
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import Http404
from .models import check_perms
from .decorators import action_error_message
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/decorators.py
# def action_error_message(actions, req_actions, default=None):
# for req in req_actions:
# for a in actions:
# if isinstance(a, tuple) and a[0] == req:
# if 'error_message' in a[1]:
# return (a[1]['error_message'],)
# if default is not None:
# return (default,)
# else:
# return ()
. Output only the next line. | return check_perms(self.request.user, check_actions, |
Predict the next line for this snippet: <|code_start|>
class BasePermissionRequiredMixin:
def get_permission_required(self):
if (not hasattr(self, 'permission_required') or
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__)
)
perms = self.permission_required
if isinstance(self.permission_required, dict):
perms = self.permission_required.get(self.request.method, ())
if callable(perms):
perms = perms(self, self.request)
if isinstance(perms, str):
perms = (perms, )
return perms
def get_permission_denied_message(self, default=None):
if hasattr(self, 'permission_denied_message'):
return (self.permission_denied_message,)
if hasattr(self, 'model') and hasattr(self.model, 'TutelaryMeta'):
<|code_end|>
with the help of current file imports:
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from collections.abc import Sequence
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import Http404
from .models import check_perms
from .decorators import action_error_message
and context from other files:
# Path: tutelary/models.py
# def check_perms(user, actions, objs, method=None):
# ensure_permission_set_tree_cached(user)
# if actions is False:
# return False
# if actions is not None:
# for a in actions:
# for o in objs:
# test_obj = None
# if o is not None:
# test_obj = o.get_permissions_object(a)
# if not user.has_perm(a, test_obj):
# return False
# return True
#
# Path: tutelary/decorators.py
# def action_error_message(actions, req_actions, default=None):
# for req in req_actions:
# for a in actions:
# if isinstance(a, tuple) and a[0] == req:
# if 'error_message' in a[1]:
# return (a[1]['error_message'],)
# if default is not None:
# return (default,)
# else:
# return ()
, which may contain function names, class names, or code. Output only the next line. | return action_error_message(self.model.TutelaryMeta.actions, |
Given the following code snippet before the placeholder: <|code_start|>
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
class PolicyFactory(factory.django.DjangoModelFactory):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import factory
from tutelary.models import Policy, Role
from django.contrib.auth.models import User
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
. Output only the next line. | model = Policy |
Given the following code snippet before the placeholder: <|code_start|>
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
class PolicyFactory(factory.django.DjangoModelFactory):
class Meta:
model = Policy
@classmethod
def set_directory(cls, dir):
cls.directory = dir
@classmethod
def _adjust_kwargs(cls, **kwargs):
body_file = os.path.join(cls.directory, kwargs.pop('file', None))
kwargs['body'] = open(body_file).read()
return kwargs
class RoleFactory(factory.django.DjangoModelFactory):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import factory
from tutelary.models import Policy, Role
from django.contrib.auth.models import User
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/models.py
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# class Role(models.Model):
# """A policy role has a name, a sequence of policies and a set of
# variable assignments. Changes to roles are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Role name field."""
#
# policies = models.ManyToManyField(Policy, through=RolePolicyAssign)
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for role.
#
# """
#
# audit_log = AuditLog()
#
# objects = RoleManager()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# return set().union(*[p.variable_names() for p in self.policies.all()])
#
# def delete(self, *args, **kwargs):
# RolePolicyAssign.objects.filter(role=self).delete()
# super().delete(*args, **kwargs)
. Output only the next line. | model = Role |
Here is a snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
<|code_end|>
. Write the next line using the current file imports:
from django.core.exceptions import ImproperlyConfigured
from django.http.response import Http404
from rest_framework.exceptions import PermissionDenied
from rest_framework.test import APIRequestFactory, force_authenticate
from tutelary.engine import Action
from tutelary.mixins import APIPermissionRequiredMixin
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .check_models import CheckModel1, CheckModel2, CheckModel4, CheckModel5
import rest_framework.generics as generic
import pytest
and context from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/mixins.py
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# """Permission checking mixin for Django Rest Framework -- works just
# like the ``PermissionRequiredMixin`` in the default Django
# authentication system.
#
# """
# def check_permissions(self, request):
# """Permission checking for DRF."""
# objs = [None]
# if hasattr(self, 'get_perms_objects'):
# objs = self.get_perms_objects()
# else:
# if hasattr(self, 'get_object'):
# try:
# objs = [self.get_object()]
# except Http404:
# raise
# except:
# pass
# if objs == [None]:
# objs = self.get_queryset()
# if len(objs) == 0:
# objs = [None]
#
# if (hasattr(self, 'permission_filter_queryset') and
# self.permission_filter_queryset is not False and
# self.request.method == 'GET'):
# if objs != [None]:
# self.perms_filter_queryset(objs)
# else:
# has_perm = check_perms(self.request.user,
# self.get_permission_required(),
# objs, self.request.method)
#
# if not has_perm:
# msg = self.get_permission_denied_message(
# default="Permission denied."
# )
# if isinstance(msg, Sequence):
# msg = msg[0]
# self.permission_denied(request, message=msg)
#
# def initial(self, request, *args, **kwargs):
# self.check_permissions(request)
# return super().initial(request, *args, **kwargs)
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
#
# Path: tests/check_models.py
# class CheckModel1(models.Model):
# name = models.CharField(max_length=100)
#
# class TutelaryMeta:
# perm_type = 'check'
# path_fields = ('name',)
# actions = [('check.list', {'permissions_object': None}),
# ('check.create', {'permissions_object': None}),
# ('check.detail',
# {'error_message': 'detail view not allowed'}),
# 'check.delete']
#
# def __str__(self):
# return self.name
#
# class CheckModel2(models.Model):
# name = models.CharField(max_length=100)
# container = models.ForeignKey(CheckModel1)
#
# def __str__(self):
# return self.name
#
# class CheckModel4(models.Model):
# name = models.CharField(max_length=100)
#
# def __str__(self):
# return self.name
#
# class TutelaryMeta:
# perm_type = 'check4'
# path_fields = ('name',)
# actions = [('check4.list', {'permissions_object': None}),
# ('check4.create', {'permissions_object': None}),
# 'check4.detail',
# 'check4.delete']
#
# class CheckModel5(models.Model):
# name = models.CharField(max_length=100)
#
# def __str__(self):
# return self.name
#
# class TutelaryMeta:
# perm_type = 'check5'
# path_fields = ('name',)
# actions = ['check5.detail', 'check5.delete']
, which may include functions, classes, or code. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture(scope="function") # noqa
def debug(db):
def fn(s):
print(s)
psets = PermissionSet.objects.all()
print('PSets:', list(map(
lambda pset: str(pset.pk) + ': ' + repr(pset.tree()),
psets)
))
pis = PolicyInstance.objects.all()
print('PolInsts:', list(map(lambda pi:
str(pi.pk) + ': ' + str(pi.pset.id) + ' ' +
pi.policy.name + ' ' +
str(pi.variables), pis)))
def nofn(s):
pass
if DEBUG:
return fn
else:
return nofn
def check(nuser=None, npol=None, npolin=None, npset=None):
if nuser is not None:
assert User.objects.count() == nuser
if npol is not None:
<|code_end|>
, predict the next line using imports from the current file:
from tutelary.models import (
PermissionSet, Policy, PolicyInstance
)
from django.contrib.auth.models import User
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .settings import DEBUG
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: tutelary/models.py
# class PermissionSet(models.Model):
# """A permission set represents the complete set of permissions
# resulting from the composition of a sequence of policy instances.
# The sequence of policy instances is recorded using the
# ``PolicyInstance`` model and the permission tree is constructed
# lazily from this information when the permission set is read from
# the database.
#
# """
# # Ordered set of policies used to generate this permission set.
# policy_assign = models.ManyToManyField(Policy, through=PolicyInstance)
#
# # Users to which this permission set is attached: a user has only
# # one permission set, so this is really an 1:m relation, not an
# # n:m relation.
# users = models.ManyToManyField(settings.AUTH_USER_MODEL,
# related_name='permissionset')
# anonymous_user = models.BooleanField(default=False)
#
# # Custom manager to deal with folding together permission sets
# # generated from identical sequences of policies.
# objects = PermissionSetManager()
#
# def cache_key(self):
# return 'tutelary:ptree:' + str(self.pk)
#
# def tree(self):
# key = self.cache_key()
# cached = cache.get(key)
# if cached is None:
# ptree = engine.PermissionTree(
# policies=[engine.PolicyBody(json=pi.policy.body,
# variables=json.loads(pi.variables))
# for pi in (PolicyInstance.objects
# .select_related('policy')
# .filter(pset=self))]
# )
# cache.set(key, ptree)
# cached = ptree
# return cached
#
# def refresh(self):
# cache.set(self.cache_key(), None)
#
# def __str__(self):
# return str(self.pk)
#
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# class PolicyInstance(models.Model):
# """An instance of a policy provides fixed values for any variables
# used in the policy's body. An ordered sequence of policy
# instances defines a permission set.
#
# """
#
# policy = models.ForeignKey(Policy, on_delete=models.PROTECT)
#
# pset = models.ForeignKey('PermissionSet', on_delete=models.CASCADE)
#
# index = models.IntegerField()
# """Integer index used to order the sequence of policies composing a
# permission set.
#
# """
#
# role = models.ForeignKey(Role, null=True, on_delete=models.PROTECT)
# """The role that this policy instance is associated with, if any."""
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for policy
# instance.
#
# """
#
# class Meta:
# ordering = ['index']
#
# def __str__(self):
# return "policy={} pset={} index={} role={} variables={}".format(
# self.policy.name, self.pset.pk, self.index,
# self.role.name if self.role else "NULL",
# self.variables
# )
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | assert Policy.objects.count() == npol |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
user3 = UserFactory.create(username='user3')
<|code_end|>
using the current file's imports:
from tutelary.models import (
PermissionSet, Policy, PolicyInstance
)
from django.contrib.auth.models import User
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
from .settings import DEBUG
import pytest
and any relevant context from other files:
# Path: tutelary/models.py
# class PermissionSet(models.Model):
# """A permission set represents the complete set of permissions
# resulting from the composition of a sequence of policy instances.
# The sequence of policy instances is recorded using the
# ``PolicyInstance`` model and the permission tree is constructed
# lazily from this information when the permission set is read from
# the database.
#
# """
# # Ordered set of policies used to generate this permission set.
# policy_assign = models.ManyToManyField(Policy, through=PolicyInstance)
#
# # Users to which this permission set is attached: a user has only
# # one permission set, so this is really an 1:m relation, not an
# # n:m relation.
# users = models.ManyToManyField(settings.AUTH_USER_MODEL,
# related_name='permissionset')
# anonymous_user = models.BooleanField(default=False)
#
# # Custom manager to deal with folding together permission sets
# # generated from identical sequences of policies.
# objects = PermissionSetManager()
#
# def cache_key(self):
# return 'tutelary:ptree:' + str(self.pk)
#
# def tree(self):
# key = self.cache_key()
# cached = cache.get(key)
# if cached is None:
# ptree = engine.PermissionTree(
# policies=[engine.PolicyBody(json=pi.policy.body,
# variables=json.loads(pi.variables))
# for pi in (PolicyInstance.objects
# .select_related('policy')
# .filter(pset=self))]
# )
# cache.set(key, ptree)
# cached = ptree
# return cached
#
# def refresh(self):
# cache.set(self.cache_key(), None)
#
# def __str__(self):
# return str(self.pk)
#
# class Policy(models.Model):
# """An individual policy has a name and a JSON policy body. Changes to
# policies are audited.
#
# """
#
# name = models.CharField(max_length=200)
# """Policy name field."""
#
# body = models.TextField()
# """Policy JSON body."""
#
# audit_log = AuditLog()
#
# def __str__(self):
# return self.name
#
# def variable_names(self):
# pat = re.compile(r'\$(?:([_a-z][_a-z0-9]*)|{([_a-z][_a-z0-9]*)})')
# return set([m[0] for m in re.findall(pat, self.body)])
#
# def save(self, *args, **kwargs):
# super().save(*args, **kwargs)
# self.refresh()
#
# def refresh(self):
# for pset in _policy_psets([self]):
# pset.refresh()
#
# class PolicyInstance(models.Model):
# """An instance of a policy provides fixed values for any variables
# used in the policy's body. An ordered sequence of policy
# instances defines a permission set.
#
# """
#
# policy = models.ForeignKey(Policy, on_delete=models.PROTECT)
#
# pset = models.ForeignKey('PermissionSet', on_delete=models.CASCADE)
#
# index = models.IntegerField()
# """Integer index used to order the sequence of policies composing a
# permission set.
#
# """
#
# role = models.ForeignKey(Role, null=True, on_delete=models.PROTECT)
# """The role that this policy instance is associated with, if any."""
#
# variables = models.TextField()
# """JSON dump of dictionary giving variable assignments for policy
# instance.
#
# """
#
# class Meta:
# ordering = ['index']
#
# def __str__(self):
# return "policy={} pset={} index={} role={} variables={}".format(
# self.policy.name, self.pset.pk, self.index,
# self.role.name if self.role else "NULL",
# self.variables
# )
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Continue the code snippet: <|code_start|>
@pytest.fixture(scope="function") # noqa
def setup(datadir, db):
user1 = UserFactory.create(username='user1')
user2 = UserFactory.create(username='user2')
<|code_end|>
. Use current file imports:
import pytest
import django.views.generic as generic
from tutelary.engine import Action
from tutelary.decorators import permissioned_model
from tutelary import mixins
from django.db import models
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.http.response import Http404
from django.core.exceptions import PermissionDenied
from .factories import UserFactory, PolicyFactory
from .datadir import datadir # noqa
and context (classes, functions, or code) from other files:
# Path: tutelary/engine.py
# class Action(SimpleSeparated):
# """Actions are represented by period-separated sequences of elements
# (e.g. ``parcel.edit``, ``admin.assign-role``) with wildcard
# elements indicated by ``*`` (e.g. ``party.*``). A list of
# *registered* actions is maintained to support permissions set
# queries to find the set of actions that are permitted on a
# specified object pattern.
#
# """
# separator = '.'
#
# registered = set()
#
# def register(action):
# """Action registration is used to support generating lists of
# permitted actions from a permission set and an object pattern.
# Only registered actions will be returned by such queries.
#
# """
# if isinstance(action, str):
# Action.register(Action(action))
# elif isinstance(action, Action):
# Action.registered.add(action)
# else:
# for a in action:
# Action.register(a)
#
# Path: tutelary/decorators.py
# def permissioned_model(cls, perm_type=None, path_fields=None, actions=None):
# """Function to set up a model for permissioning. Can either be called
# directly, passing a class and suitable values for ``perm_type``,
# ``path_fields`` and ``actions``, or can be used as a class
# decorator, taking values for ``perm_type``, ``path_fields`` and
# ``actions`` from the ``TutelaryMeta`` subclass of the decorated
# class.
#
# """
# if not issubclass(cls, models.Model):
# raise DecoratorException(
# 'permissioned_model',
# "class '" + cls.__name__ + "' is not a Django model"
# )
# added = False
# try:
# if not hasattr(cls, 'TutelaryMeta'):
# if perm_type is None or path_fields is None or actions is None:
# raise DecoratorException(
# 'permissioned_model',
# ("missing argument: all of perm_type, path_fields and " +
# "actions must be supplied")
# )
# added = True
# cls.TutelaryMeta = type('TutelaryMeta', (object,),
# dict(perm_type=perm_type,
# path_fields=path_fields,
# actions=actions))
# cls.TutelaryMeta.pfs = ([cls.TutelaryMeta.perm_type] +
# get_path_fields(cls))
# perms_objs = {}
# for a in cls.TutelaryMeta.actions:
# an = a
# ap = {}
# if isinstance(a, tuple):
# an = a[0]
# ap = a[1]
# Action.register(an)
# if isinstance(ap, dict) and 'permissions_object' in ap:
# po = ap['permissions_object']
# if po is not None:
# try:
# t = cls._meta.get_field(po).__class__
# if t not in [models.ForeignKey,
# models.OneToOneField]:
# raise PermissionObjectException(po)
# except:
# raise PermissionObjectException(po)
# perms_objs[an] = po
# if len(perms_objs) == 0:
# cls.get_permissions_object = get_perms_object
# else:
# cls.get_permissions_object = make_get_perms_object(perms_objs)
# return cls
# except:
# if added:
# del cls.TutelaryMeta
# raise
#
# Path: tutelary/mixins.py
# class BasePermissionRequiredMixin:
# class PermissionRequiredMixin(BasePermissionRequiredMixin):
# class LoginPermissionRequiredMixin(PermissionRequiredMixin,
# LoginRequiredMixin):
# class PermissionsFilterMixin:
# class APIPermissionRequiredMixin(BasePermissionRequiredMixin):
# def get_permission_required(self):
# def get_permission_denied_message(self, default=None):
# def get_queryset(self):
# def perms_filter_queryset(self, objs):
# def check_one(obj):
# def has_permission(self):
# def handle_no_permission(self):
# def dispatch(self, request, *args, **kwargs):
# def dispatch(self, request, *args, **kwargs):
# def dispatch(self, request, *args, **kwargs):
# def check_permissions(self, request):
# def initial(self, request, *args, **kwargs):
#
# Path: tests/factories.py
# class UserFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = User
#
# class PolicyFactory(factory.django.DjangoModelFactory):
# class Meta:
# model = Policy
#
# @classmethod
# def set_directory(cls, dir):
# cls.directory = dir
#
# @classmethod
# def _adjust_kwargs(cls, **kwargs):
# body_file = os.path.join(cls.directory, kwargs.pop('file', None))
# kwargs['body'] = open(body_file).read()
# return kwargs
#
# Path: tests/datadir.py
# @pytest.fixture(scope="function")
# def datadir(request, tmpdir):
# """
# Fixture responsible for searching a folder with the same name of test
# module and, if available, moving all contents to a temporary directory so
# tests can use them freely.
#
# Adapted from http://stackoverflow.com/questions/29627341
# """
# test_dir = py.path.local(request.module.__file__).new(ext='')
# try:
# for f in test_dir.listdir():
# f.copy(tmpdir)
# except:
# pass
# return tmpdir
. Output only the next line. | PolicyFactory.set_directory(str(datadir)) |
Given the code snippet: <|code_start|>
class Meta:
ordering = ['name']
class State(models.Model):
"""Top-level window into state data
Intended as a resource to track general state information and
as a skeleton for admin inlines such as election data and FOIA logs
"""
STATUS_OPTIONS = (
('not-started', 'Not Started'),
('partial', 'Partial'),
('up-to-date', 'Up-to-date'),
)
PAIN_CHOICES = (
('easy', 'Easy'),
('medium', 'Medium'),
('hard', 'Hard'),
('excruciating', 'Excruciating'),
)
postal = models.CharField(max_length=2, choices=US_STATES, primary_key=True)
name = models.CharField(max_length=25, help_text="Full state name")
metadata_status = models.CharField(max_length=20, choices=STATUS_OPTIONS, db_index=True, help_text="Status of metadata collection for state")
note = models.TextField("Overview", blank=True)
pain = models.CharField(max_length=15, blank=True, choices=PAIN_CHOICES, default='', help_text="Degree of difficulty for loading a state's results.")
results_description = models.TextField(blank=True, help_text="Quality and consistency of results over time. E.g., CSV files with consistent formats for all years except 2000 and 2002")
<|code_end|>
, generate the next line using the imports in this file:
import datetime
from django.contrib.auth.models import User
from localflavor.us.models import PhoneNumberField
from localflavor.us.us_states import US_STATES
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.db import models
from django.db.models import Q
from django.template.defaultfilters import slugify
from .managers import StateManager
and context (functions, classes, or occasionally code) from other files:
# Path: dashboard/apps/hub/managers.py
# class StateManager(models.Manager):
# def status_json(self):
# return json.dumps([s.status_entry() for s in self.all()])
. Output only the next line. | objects = StateManager() |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = ("Creates a json file of the project status of each state to be "
"consumed be the front-end website.")
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from dashboard.apps.hub.models import State
and context (class names, function names, or code) available:
# Path: dashboard/apps/hub/models.py
# class State(models.Model):
# """Top-level window into state data
#
# Intended as a resource to track general state information and
# as a skeleton for admin inlines such as election data and FOIA logs
#
# """
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# postal = models.CharField(max_length=2, choices=US_STATES, primary_key=True)
# name = models.CharField(max_length=25, help_text="Full state name")
# metadata_status = models.CharField(max_length=20, choices=STATUS_OPTIONS, db_index=True, help_text="Status of metadata collection for state")
# note = models.TextField("Overview", blank=True)
# pain = models.CharField(max_length=15, blank=True, choices=PAIN_CHOICES, default='', help_text="Degree of difficulty for loading a state's results.")
# results_description = models.TextField(blank=True, help_text="Quality and consistency of results over time. E.g., CSV files with consistent formats for all years except 2000 and 2002")
#
# objects = StateManager()
#
# class Meta:
# ordering = ['name']
#
# def __str__(self):
# return '%s' % self.name
#
# def status_entry(self):
# """
# Returns a dict, suitable for serialization that represents
# the state's completion status.
# """
# volunteers = [v.status_entry() for v in
# self.volunteer_set.all()]
# dev_volunteers = [v.status_entry() for v in
# self.volunteer_set.filter(roles__slug="dev")]
# metadata_volunteers = [v.status_entry() for v in
# self.volunteer_set.filter(roles__slug="metadata")]
#
# return {
# 'name': self.name,
# 'postal': self.postal,
# 'metadata_status': self.metadata_status,
# 'results_status': self.results_status,
# 'volunteers': volunteers,
# 'dev_volunteers': dev_volunteers,
# 'metadata_volunteers': metadata_volunteers,
# }
#
# @property
# def results_status(self):
# """
# The status of results for this state.
#
# The value can be one of these:
#
# None: Unknown status.
# "partial": A developer has been assigned to this state.
# "raw": Raw results available for at least some elections.
# "clean": Cleaned/transformed results available for at least some
# elections.
# """
# statuses = (
# {
# 'in': 'baked',
# 'out': 'clean',
# },
# {
# 'in': 'baked-raw',
# 'out': 'raw',
# },
# )
# final_status = None
# # Check if we have any clean or raw results
# for status in statuses:
# q = (Q(precinct_level_status=status['in']) | Q(county_level_status=status['in']) |
# Q(cong_dist_level_status=status['in']) | Q(state_leg_level_status=status['in']) |
# Q(state_level_status=status['in']))
#
# if self.election_set.filter(q).exists():
# final_status = status['out']
# break
#
# # No clean or raw results, see if a developer volunteer has been
# # assigned.
# if (final_status is None and
# self.volunteer_set.filter(roles__slug='dev').exists()):
# final_status = 'partial'
#
# return final_status
. Output only the next line. | self.stdout.write(State.objects.status_json()) |
Using the snippet: <|code_start|> gop_prez_primary.primary_type = "other"
self.assertRaises(ValidationError, gop_prez_primary.clean)
class LogTest(TestCase):
fixtures = [
'test_log_model',
]
def test_log_key(self):
"""Log key returns info on state, date and subject of conversation"""
kwargs = {
"follow_up": None,
"notes": "This is a test.",
"gdoc_link": "",
"state_id": "KS",
"contact": None,
"user_id": 9,
"formal_request": False,
"date": "2013-03-28",
"org_id": 15,
"subject": "Test subject line"
}
log = Log(**kwargs)
log.save()
self.assertEqual(log.log_key(), ('KS', '2013-03-28', 'Test subject line'))
self.assertEqual(log.log_key(as_string=True), 'KS - 2013-03-28 - Test subject line')
# Test with contact
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import mock
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.query import QuerySet
from django.test import TestCase
from ..models import Contact, Election, Log, State, Volunteer
and context (class names, function names, or code) available:
# Path: dashboard/apps/hub/models.py
# class ProxyUser(User):
# class Meta:
# class Office(models.Model):
# class Meta:
# class Organization(models.Model):
# class Meta:
# class DataFormat(models.Model):
# class Meta:
# class State(models.Model):
# class Meta:
# class Election(models.Model):
# class Meta:
# class BaseContact(models.Model):
# class Meta:
# class VolunteerRole(models.Model):
# class Volunteer(BaseContact):
# class BaseLog(models.Model):
# class Meta:
# class Log(BaseLog):
# class Meta:
# class VolunteerLog(BaseLog):
# def __str__(self):
# def __str__(self):
# def __repr__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# def status_entry(self):
# def results_status(self):
# def save(self, *args, **kwargs):
# def clean(self):
# def __str__(self):
# def __repr__(self):
# def _perform_unique_checks(self, unique_checks):
# def offices(self):
# def offices_for_api(self):
# def reporting_levels(self):
# def elec_key(self, as_string=False):
# def slug(self):
# def division(self):
# def __str__(self):
# def __str__(self):
# def full_name(self):
# def status_entry(self):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# GOV_LEVELS = (
# ('county', 'County'),
# ('state','State'),
# ('federal','Federal'),
# ('local', 'Local')
# )
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# RACE_CHOICES = (
# ('primary', 'Primary'),
# ('primary-recall', 'Primary Recall'),
# ('general', 'General'),
# ('general-recall', 'General Recall'),
# ('primary-runoff', 'Primary Runoff'),
# ('general-runoff', 'General Runoff'),
# )
# RESULT_CHOICES = (
# ('certified', 'Certified'),
# ('unofficial', 'Unofficial'),
# )
# PRIMARY_TYPE_CHOICES = (
# ('blanket', 'Blanket'),
# ('closed', 'Closed'),
# ('open', 'Open'),
# ('semi-closed', 'Semi-closed'),
# ('semi-open', 'Semi-open'),
# ('other', 'Other'),
# )
# LEVEL_STATUS_CHOICES = (
# ('yes', 'Yes - Will be included'),
# ('no', 'No - Will not be included'),
# ('unknown', 'Unsure if exists'),
# ('Unavailable', 'Not available'),
# ('baked-raw', 'Baked Raw'),
# ('baked', 'Baked'),
# )
. Output only the next line. | contact = Contact.objects.all()[0] |
Continue the code snippet: <|code_start|>
class ElectionTest(TestCase):
fixtures = [
'test_elecdata_model'
]
def test_offices(self):
"Election.offices should return tuple of offices up for election"
# Florida 2012 races
<|code_end|>
. Use current file imports:
import unittest
import mock
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.query import QuerySet
from django.test import TestCase
from ..models import Contact, Election, Log, State, Volunteer
and context (classes, functions, or code) from other files:
# Path: dashboard/apps/hub/models.py
# class ProxyUser(User):
# class Meta:
# class Office(models.Model):
# class Meta:
# class Organization(models.Model):
# class Meta:
# class DataFormat(models.Model):
# class Meta:
# class State(models.Model):
# class Meta:
# class Election(models.Model):
# class Meta:
# class BaseContact(models.Model):
# class Meta:
# class VolunteerRole(models.Model):
# class Volunteer(BaseContact):
# class BaseLog(models.Model):
# class Meta:
# class Log(BaseLog):
# class Meta:
# class VolunteerLog(BaseLog):
# def __str__(self):
# def __str__(self):
# def __repr__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# def status_entry(self):
# def results_status(self):
# def save(self, *args, **kwargs):
# def clean(self):
# def __str__(self):
# def __repr__(self):
# def _perform_unique_checks(self, unique_checks):
# def offices(self):
# def offices_for_api(self):
# def reporting_levels(self):
# def elec_key(self, as_string=False):
# def slug(self):
# def division(self):
# def __str__(self):
# def __str__(self):
# def full_name(self):
# def status_entry(self):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# GOV_LEVELS = (
# ('county', 'County'),
# ('state','State'),
# ('federal','Federal'),
# ('local', 'Local')
# )
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# RACE_CHOICES = (
# ('primary', 'Primary'),
# ('primary-recall', 'Primary Recall'),
# ('general', 'General'),
# ('general-recall', 'General Recall'),
# ('primary-runoff', 'Primary Runoff'),
# ('general-runoff', 'General Runoff'),
# )
# RESULT_CHOICES = (
# ('certified', 'Certified'),
# ('unofficial', 'Unofficial'),
# )
# PRIMARY_TYPE_CHOICES = (
# ('blanket', 'Blanket'),
# ('closed', 'Closed'),
# ('open', 'Open'),
# ('semi-closed', 'Semi-closed'),
# ('semi-open', 'Semi-open'),
# ('other', 'Other'),
# )
# LEVEL_STATUS_CHOICES = (
# ('yes', 'Yes - Will be included'),
# ('no', 'No - Will not be included'),
# ('unknown', 'Unsure if exists'),
# ('Unavailable', 'Not available'),
# ('baked-raw', 'Baked Raw'),
# ('baked', 'Baked'),
# )
. Output only the next line. | general = Election.objects.get(pk=4) |
Given the following code snippet before the placeholder: <|code_start|>
# Primary race_type must have a primary_type (e.g. closed, open, blanket)
gop_prez_primary.primary_type = ""
self.assertRaises(ValidationError, gop_prez_primary.clean)
# Primary race_type of other represents an edge case that requires explanation
gop_prez_primary.primary_type = "other"
self.assertRaises(ValidationError, gop_prez_primary.clean)
class LogTest(TestCase):
fixtures = [
'test_log_model',
]
def test_log_key(self):
"""Log key returns info on state, date and subject of conversation"""
kwargs = {
"follow_up": None,
"notes": "This is a test.",
"gdoc_link": "",
"state_id": "KS",
"contact": None,
"user_id": 9,
"formal_request": False,
"date": "2013-03-28",
"org_id": 15,
"subject": "Test subject line"
}
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import mock
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.query import QuerySet
from django.test import TestCase
from ..models import Contact, Election, Log, State, Volunteer
and context including class names, function names, and sometimes code from other files:
# Path: dashboard/apps/hub/models.py
# class ProxyUser(User):
# class Meta:
# class Office(models.Model):
# class Meta:
# class Organization(models.Model):
# class Meta:
# class DataFormat(models.Model):
# class Meta:
# class State(models.Model):
# class Meta:
# class Election(models.Model):
# class Meta:
# class BaseContact(models.Model):
# class Meta:
# class VolunteerRole(models.Model):
# class Volunteer(BaseContact):
# class BaseLog(models.Model):
# class Meta:
# class Log(BaseLog):
# class Meta:
# class VolunteerLog(BaseLog):
# def __str__(self):
# def __str__(self):
# def __repr__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# def status_entry(self):
# def results_status(self):
# def save(self, *args, **kwargs):
# def clean(self):
# def __str__(self):
# def __repr__(self):
# def _perform_unique_checks(self, unique_checks):
# def offices(self):
# def offices_for_api(self):
# def reporting_levels(self):
# def elec_key(self, as_string=False):
# def slug(self):
# def division(self):
# def __str__(self):
# def __str__(self):
# def full_name(self):
# def status_entry(self):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# GOV_LEVELS = (
# ('county', 'County'),
# ('state','State'),
# ('federal','Federal'),
# ('local', 'Local')
# )
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# RACE_CHOICES = (
# ('primary', 'Primary'),
# ('primary-recall', 'Primary Recall'),
# ('general', 'General'),
# ('general-recall', 'General Recall'),
# ('primary-runoff', 'Primary Runoff'),
# ('general-runoff', 'General Runoff'),
# )
# RESULT_CHOICES = (
# ('certified', 'Certified'),
# ('unofficial', 'Unofficial'),
# )
# PRIMARY_TYPE_CHOICES = (
# ('blanket', 'Blanket'),
# ('closed', 'Closed'),
# ('open', 'Open'),
# ('semi-closed', 'Semi-closed'),
# ('semi-open', 'Semi-open'),
# ('other', 'Other'),
# )
# LEVEL_STATUS_CHOICES = (
# ('yes', 'Yes - Will be included'),
# ('no', 'No - Will not be included'),
# ('unknown', 'Unsure if exists'),
# ('Unavailable', 'Not available'),
# ('baked-raw', 'Baked Raw'),
# ('baked', 'Baked'),
# )
. Output only the next line. | log = Log(**kwargs) |
Given the code snippet: <|code_start|> def filter_method(*args, **kwargs):
count_val = 0
try:
q_obj = args[0]
if isinstance(q_obj, Q):
filter_kwargs = {k:v for k, v in q_obj.children}
except IndexError:
filter_kwargs = kwargs
for kwarg, val in filter_kwargs.items():
try:
count_val = counts[kwarg][val]
break
except KeyError:
pass
mqs = mock.MagicMock(spec=QuerySet)
mqs.count.return_value = count_val
return mqs
return filter_method
# It would be great to use mock-django
# (https://github.com/dcramer/mock-django/) for more full-featured mocks
# of Django QuerySets and Managers. However, the version on pypi doesn't
# support Django 1.5.
@mock.patch('apps.hub.models.State.election_set', autospec=True)
def test_results_status(self, election_set):
election_set.filter = self.make_mock_filter_method()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import mock
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.query import QuerySet
from django.test import TestCase
from ..models import Contact, Election, Log, State, Volunteer
and context (functions, classes, or occasionally code) from other files:
# Path: dashboard/apps/hub/models.py
# class ProxyUser(User):
# class Meta:
# class Office(models.Model):
# class Meta:
# class Organization(models.Model):
# class Meta:
# class DataFormat(models.Model):
# class Meta:
# class State(models.Model):
# class Meta:
# class Election(models.Model):
# class Meta:
# class BaseContact(models.Model):
# class Meta:
# class VolunteerRole(models.Model):
# class Volunteer(BaseContact):
# class BaseLog(models.Model):
# class Meta:
# class Log(BaseLog):
# class Meta:
# class VolunteerLog(BaseLog):
# def __str__(self):
# def __str__(self):
# def __repr__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# def status_entry(self):
# def results_status(self):
# def save(self, *args, **kwargs):
# def clean(self):
# def __str__(self):
# def __repr__(self):
# def _perform_unique_checks(self, unique_checks):
# def offices(self):
# def offices_for_api(self):
# def reporting_levels(self):
# def elec_key(self, as_string=False):
# def slug(self):
# def division(self):
# def __str__(self):
# def __str__(self):
# def full_name(self):
# def status_entry(self):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# GOV_LEVELS = (
# ('county', 'County'),
# ('state','State'),
# ('federal','Federal'),
# ('local', 'Local')
# )
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# RACE_CHOICES = (
# ('primary', 'Primary'),
# ('primary-recall', 'Primary Recall'),
# ('general', 'General'),
# ('general-recall', 'General Recall'),
# ('primary-runoff', 'Primary Runoff'),
# ('general-runoff', 'General Runoff'),
# )
# RESULT_CHOICES = (
# ('certified', 'Certified'),
# ('unofficial', 'Unofficial'),
# )
# PRIMARY_TYPE_CHOICES = (
# ('blanket', 'Blanket'),
# ('closed', 'Closed'),
# ('open', 'Open'),
# ('semi-closed', 'Semi-closed'),
# ('semi-open', 'Semi-open'),
# ('other', 'Other'),
# )
# LEVEL_STATUS_CHOICES = (
# ('yes', 'Yes - Will be included'),
# ('no', 'No - Will not be included'),
# ('unknown', 'Unsure if exists'),
# ('Unavailable', 'Not available'),
# ('baked-raw', 'Baked Raw'),
# ('baked', 'Baked'),
# )
. Output only the next line. | s = State(postal="MD") |
Continue the code snippet: <|code_start|> "user_id": 9,
"formal_request": False,
"date": "2013-03-28",
"org_id": 15,
"subject": "Test subject line"
}
log = Log(**kwargs)
log.save()
self.assertEqual(log.log_key(), ('KS', '2013-03-28', 'Test subject line'))
self.assertEqual(log.log_key(as_string=True), 'KS - 2013-03-28 - Test subject line')
# Test with contact
contact = Contact.objects.all()[0]
log.contact = contact
log.save()
expected = (
'KS',
'2013-03-28',
u'Williams (Kansas Secretary of State elections division)',
'Test subject line',
)
self.assertEqual(expected, log.log_key())
class VolunteerTest(TestCase):
fixtures = [
'test_state_status',
]
def test_status_entry(self):
<|code_end|>
. Use current file imports:
import unittest
import mock
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.db.models.query import QuerySet
from django.test import TestCase
from ..models import Contact, Election, Log, State, Volunteer
and context (classes, functions, or code) from other files:
# Path: dashboard/apps/hub/models.py
# class ProxyUser(User):
# class Meta:
# class Office(models.Model):
# class Meta:
# class Organization(models.Model):
# class Meta:
# class DataFormat(models.Model):
# class Meta:
# class State(models.Model):
# class Meta:
# class Election(models.Model):
# class Meta:
# class BaseContact(models.Model):
# class Meta:
# class VolunteerRole(models.Model):
# class Volunteer(BaseContact):
# class BaseLog(models.Model):
# class Meta:
# class Log(BaseLog):
# class Meta:
# class VolunteerLog(BaseLog):
# def __str__(self):
# def __str__(self):
# def __repr__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def save(self, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# def status_entry(self):
# def results_status(self):
# def save(self, *args, **kwargs):
# def clean(self):
# def __str__(self):
# def __repr__(self):
# def _perform_unique_checks(self, unique_checks):
# def offices(self):
# def offices_for_api(self):
# def reporting_levels(self):
# def elec_key(self, as_string=False):
# def slug(self):
# def division(self):
# def __str__(self):
# def __str__(self):
# def full_name(self):
# def status_entry(self):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# def __str__(self):
# def __repr__(self):
# def log_key(self, as_string=False):
# GOV_LEVELS = (
# ('county', 'County'),
# ('state','State'),
# ('federal','Federal'),
# ('local', 'Local')
# )
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# RACE_CHOICES = (
# ('primary', 'Primary'),
# ('primary-recall', 'Primary Recall'),
# ('general', 'General'),
# ('general-recall', 'General Recall'),
# ('primary-runoff', 'Primary Runoff'),
# ('general-runoff', 'General Runoff'),
# )
# RESULT_CHOICES = (
# ('certified', 'Certified'),
# ('unofficial', 'Unofficial'),
# )
# PRIMARY_TYPE_CHOICES = (
# ('blanket', 'Blanket'),
# ('closed', 'Closed'),
# ('open', 'Open'),
# ('semi-closed', 'Semi-closed'),
# ('semi-open', 'Semi-open'),
# ('other', 'Other'),
# )
# LEVEL_STATUS_CHOICES = (
# ('yes', 'Yes - Will be included'),
# ('no', 'No - Will not be included'),
# ('unknown', 'Unsure if exists'),
# ('Unavailable', 'Not available'),
# ('baked-raw', 'Baked Raw'),
# ('baked', 'Baked'),
# )
. Output only the next line. | v = Volunteer.objects.get(user__username="testuser") |
Given the following code snippet before the placeholder: <|code_start|>
class TestStateManager(TestCase):
fixtures = [
'test_state_status',
]
def test_status_json(self):
<|code_end|>
, predict the next line using imports from the current file:
import json
from django.test import TestCase
from ..models import State
and context including class names, function names, and sometimes code from other files:
# Path: dashboard/apps/hub/models.py
# class State(models.Model):
# """Top-level window into state data
#
# Intended as a resource to track general state information and
# as a skeleton for admin inlines such as election data and FOIA logs
#
# """
# STATUS_OPTIONS = (
# ('not-started', 'Not Started'),
# ('partial', 'Partial'),
# ('up-to-date', 'Up-to-date'),
# )
# PAIN_CHOICES = (
# ('easy', 'Easy'),
# ('medium', 'Medium'),
# ('hard', 'Hard'),
# ('excruciating', 'Excruciating'),
# )
# postal = models.CharField(max_length=2, choices=US_STATES, primary_key=True)
# name = models.CharField(max_length=25, help_text="Full state name")
# metadata_status = models.CharField(max_length=20, choices=STATUS_OPTIONS, db_index=True, help_text="Status of metadata collection for state")
# note = models.TextField("Overview", blank=True)
# pain = models.CharField(max_length=15, blank=True, choices=PAIN_CHOICES, default='', help_text="Degree of difficulty for loading a state's results.")
# results_description = models.TextField(blank=True, help_text="Quality and consistency of results over time. E.g., CSV files with consistent formats for all years except 2000 and 2002")
#
# objects = StateManager()
#
# class Meta:
# ordering = ['name']
#
# def __str__(self):
# return '%s' % self.name
#
# def status_entry(self):
# """
# Returns a dict, suitable for serialization that represents
# the state's completion status.
# """
# volunteers = [v.status_entry() for v in
# self.volunteer_set.all()]
# dev_volunteers = [v.status_entry() for v in
# self.volunteer_set.filter(roles__slug="dev")]
# metadata_volunteers = [v.status_entry() for v in
# self.volunteer_set.filter(roles__slug="metadata")]
#
# return {
# 'name': self.name,
# 'postal': self.postal,
# 'metadata_status': self.metadata_status,
# 'results_status': self.results_status,
# 'volunteers': volunteers,
# 'dev_volunteers': dev_volunteers,
# 'metadata_volunteers': metadata_volunteers,
# }
#
# @property
# def results_status(self):
# """
# The status of results for this state.
#
# The value can be one of these:
#
# None: Unknown status.
# "partial": A developer has been assigned to this state.
# "raw": Raw results available for at least some elections.
# "clean": Cleaned/transformed results available for at least some
# elections.
# """
# statuses = (
# {
# 'in': 'baked',
# 'out': 'clean',
# },
# {
# 'in': 'baked-raw',
# 'out': 'raw',
# },
# )
# final_status = None
# # Check if we have any clean or raw results
# for status in statuses:
# q = (Q(precinct_level_status=status['in']) | Q(county_level_status=status['in']) |
# Q(cong_dist_level_status=status['in']) | Q(state_leg_level_status=status['in']) |
# Q(state_level_status=status['in']))
#
# if self.election_set.filter(q).exists():
# final_status = status['out']
# break
#
# # No clean or raw results, see if a developer volunteer has been
# # assigned.
# if (final_status is None and
# self.volunteer_set.filter(roles__slug='dev').exists()):
# final_status = 'partial'
#
# return final_status
. Output only the next line. | status_json = State.objects.status_json() |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = "Reset access log records older than given days."
def add_arguments(self, parser):
parser.add_argument(
"--age",
type=int,
default=30,
help="Maximum age for records to keep in days",
)
def handle(self, *args, **options):
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management.base import BaseCommand
from axes.handlers.proxy import AxesProxyHandler
and context (classes, functions, sometimes code) from other files:
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
. Output only the next line. | count = AxesProxyHandler.reset_logs(age_days=options["age"]) |
Here is a snippet: <|code_start|> """
Checks if the request or given credentials are blacklisted from access.
"""
if is_client_ip_address_blacklisted(request):
return True
return False
def is_whitelisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are whitelisted for access.
"""
if is_user_attempt_whitelisted(request, credentials):
return True
if is_client_ip_address_whitelisted(request):
return True
if is_client_method_whitelisted(request):
return True
return False
def is_locked(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are locked.
"""
<|code_end|>
. Write the next line using the current file imports:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
, which may include functions, classes, or code. Output only the next line. | if settings.AXES_LOCK_OUT_AT_FAILURE: |
Given the code snippet: <|code_start|> if is_client_ip_address_blacklisted(request):
return True
return False
def is_whitelisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are whitelisted for access.
"""
if is_user_attempt_whitelisted(request, credentials):
return True
if is_client_ip_address_whitelisted(request):
return True
if is_client_method_whitelisted(request):
return True
return False
def is_locked(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are locked.
"""
if settings.AXES_LOCK_OUT_AT_FAILURE:
# get_failures will have to be implemented by each specialized handler
return self.get_failures( # type: ignore
request, credentials
<|code_end|>
, generate the next line using the imports in this file:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context (functions, classes, or occasionally code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
. Output only the next line. | ) >= get_failure_limit(request, credentials) |
Based on the snippet: <|code_start|> This method is abstract and other backends can specialize it as needed, but the default implementation
checks if the user has attempted to authenticate into the site too many times through the
Django authentication backends and returns ``False`` if user exceeds the configured Axes thresholds.
This checker can implement arbitrary checks such as IP whitelisting or blacklisting,
request frequency checking, failed attempt monitoring or similar functions.
Please refer to the ``axes.handlers.database.AxesDatabaseHandler`` for the default implementation
and inspiration on some common checks and access restrictions before writing your own implementation.
"""
if self.is_admin_site(request):
return True
if self.is_blacklisted(request, credentials):
return False
if self.is_whitelisted(request, credentials):
return True
if self.is_locked(request, credentials):
return False
return True
def is_blacklisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are blacklisted from access.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context (classes, functions, sometimes code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
. Output only the next line. | if is_client_ip_address_blacklisted(request): |
Given the code snippet: <|code_start|>
if self.is_blacklisted(request, credentials):
return False
if self.is_whitelisted(request, credentials):
return True
if self.is_locked(request, credentials):
return False
return True
def is_blacklisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are blacklisted from access.
"""
if is_client_ip_address_blacklisted(request):
return True
return False
def is_whitelisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are whitelisted for access.
"""
if is_user_attempt_whitelisted(request, credentials):
return True
<|code_end|>
, generate the next line using the imports in this file:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context (functions, classes, or occasionally code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
. Output only the next line. | if is_client_ip_address_whitelisted(request): |
Predict the next line for this snippet: <|code_start|>
if self.is_whitelisted(request, credentials):
return True
if self.is_locked(request, credentials):
return False
return True
def is_blacklisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are blacklisted from access.
"""
if is_client_ip_address_blacklisted(request):
return True
return False
def is_whitelisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are whitelisted for access.
"""
if is_user_attempt_whitelisted(request, credentials):
return True
if is_client_ip_address_whitelisted(request):
return True
<|code_end|>
with the help of current file imports:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
, which may contain function names, class names, or code. Output only the next line. | if is_client_method_whitelisted(request): |
Continue the code snippet: <|code_start|>
if self.is_admin_site(request):
return True
if self.is_blacklisted(request, credentials):
return False
if self.is_whitelisted(request, credentials):
return True
if self.is_locked(request, credentials):
return False
return True
def is_blacklisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are blacklisted from access.
"""
if is_client_ip_address_blacklisted(request):
return True
return False
def is_whitelisted(self, request, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are whitelisted for access.
"""
<|code_end|>
. Use current file imports:
import re
from abc import ABC, abstractmethod
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from axes.conf import settings
from axes.helpers import (
get_failure_limit,
is_client_ip_address_blacklisted,
is_client_ip_address_whitelisted,
is_client_method_whitelisted,
is_user_attempt_whitelisted,
)
and context (classes, functions, or code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_failure_limit(request, credentials) -> int:
# if callable(settings.AXES_FAILURE_LIMIT):
# return settings.AXES_FAILURE_LIMIT( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_FAILURE_LIMIT, str):
# return import_string(settings.AXES_FAILURE_LIMIT)(request, credentials)
# if isinstance(settings.AXES_FAILURE_LIMIT, int):
# return settings.AXES_FAILURE_LIMIT
# raise TypeError("settings.AXES_FAILURE_LIMIT needs to be a callable or an integer")
#
# def is_client_ip_address_blacklisted(request) -> bool:
# """
# Check if the given request refers to a blacklisted IP.
# """
#
# if is_ip_address_in_blacklist(request.axes_ip_address):
# return True
#
# if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_ip_address_whitelisted(request):
# """
# Check if the given request refers to a whitelisted IP.
# """
#
# if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(
# request.axes_ip_address
# ):
# return True
#
# return False
#
# def is_client_method_whitelisted(request) -> bool:
# """
# Check if the given request uses a whitelisted method.
# """
#
# if settings.AXES_NEVER_LOCKOUT_GET and request.method == "GET":
# return True
#
# return False
#
# def is_user_attempt_whitelisted(request, credentials: dict = None) -> bool:
# """
# Check if the given request or credentials refer to a whitelisted username.
#
# This method invokes the ``settings.AXES_WHITELIST`` callable
# with ``request`` and ``credentials`` arguments.
#
# This function could use the following implementation for checking
# the lockout flags from a specific property in the user object:
#
# .. code-block: python
#
# username_value = get_client_username(request, credentials)
# username_field = getattr(
# get_user_model(),
# "USERNAME_FIELD",
# "username"
# )
# kwargs = {username_field: username_value}
#
# user_model = get_user_model()
# user = user_model.objects.get(**kwargs)
# return user.nolockout
# """
#
# whitelist_callable = settings.AXES_WHITELIST_CALLABLE
# if whitelist_callable is None:
# return False
# if callable(whitelist_callable):
# return whitelist_callable(request, credentials) # pylint: disable=not-callable
# if isinstance(whitelist_callable, str):
# return import_string(whitelist_callable)(request, credentials)
#
# raise TypeError(
# "settings.AXES_WHITELIST_CALLABLE needs to be a string, callable, or None."
# )
. Output only the next line. | if is_user_attempt_whitelisted(request, credentials): |
Continue the code snippet: <|code_start|> "username",
"user_agent",
"path_info",
)
list_filter = ["attempt_time", "logout_time", "path_info"]
search_fields = ["ip_address", "user_agent", "username", "path_info"]
date_hierarchy = "attempt_time"
fieldsets = (
(None, {"fields": ("path_info",)}),
(_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}),
)
readonly_fields = [
"user_agent",
"ip_address",
"username",
"http_accept",
"path_info",
"attempt_time",
"logout_time",
]
def has_add_permission(self, request):
return False
<|code_end|>
. Use current file imports:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from axes.conf import settings
from axes.models import AccessAttempt, AccessLog
and context (classes, functions, or code) from other files:
# Path: axes/conf.py
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
#
# class AccessLog(AccessBase):
# logout_time = models.DateTimeField(_("Logout Time"), null=True, blank=True)
#
# def __str__(self):
# return f"Access Log for {self.username} @ {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access log")
# verbose_name_plural = _("access logs")
. Output only the next line. | if settings.AXES_ENABLE_ADMIN: |
Given snippet: <|code_start|> "user_agent",
"path_info",
)
list_filter = ["attempt_time", "logout_time", "path_info"]
search_fields = ["ip_address", "user_agent", "username", "path_info"]
date_hierarchy = "attempt_time"
fieldsets = (
(None, {"fields": ("path_info",)}),
(_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}),
)
readonly_fields = [
"user_agent",
"ip_address",
"username",
"http_accept",
"path_info",
"attempt_time",
"logout_time",
]
def has_add_permission(self, request):
return False
if settings.AXES_ENABLE_ADMIN:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from axes.conf import settings
from axes.models import AccessAttempt, AccessLog
and context:
# Path: axes/conf.py
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
#
# class AccessLog(AccessBase):
# logout_time = models.DateTimeField(_("Logout Time"), null=True, blank=True)
#
# def __str__(self):
# return f"Access Log for {self.username} @ {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access log")
# verbose_name_plural = _("access logs")
which might include code, classes, or functions. Output only the next line. | admin.site.register(AccessAttempt, AccessAttemptAdmin) |
Here is a snippet: <|code_start|> "path_info",
)
list_filter = ["attempt_time", "logout_time", "path_info"]
search_fields = ["ip_address", "user_agent", "username", "path_info"]
date_hierarchy = "attempt_time"
fieldsets = (
(None, {"fields": ("path_info",)}),
(_("Meta Data"), {"fields": ("user_agent", "ip_address", "http_accept")}),
)
readonly_fields = [
"user_agent",
"ip_address",
"username",
"http_accept",
"path_info",
"attempt_time",
"logout_time",
]
def has_add_permission(self, request):
return False
if settings.AXES_ENABLE_ADMIN:
admin.site.register(AccessAttempt, AccessAttemptAdmin)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from axes.conf import settings
from axes.models import AccessAttempt, AccessLog
and context from other files:
# Path: axes/conf.py
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
#
# class AccessLog(AccessBase):
# logout_time = models.DateTimeField(_("Logout Time"), null=True, blank=True)
#
# def __str__(self):
# return f"Access Log for {self.username} @ {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access log")
# verbose_name_plural = _("access logs")
, which may include functions, classes, or code. Output only the next line. | admin.site.register(AccessLog, AccessLogAdmin) |
Next line prediction: <|code_start|>
log = getLogger(__name__)
def get_cache() -> BaseCache:
"""
Get the cache instance Axes is configured to use with ``settings.AXES_CACHE`` and use ``'default'`` if not set.
"""
<|code_end|>
. Use current file imports:
(from datetime import timedelta
from hashlib import md5
from logging import getLogger
from string import Template
from typing import Callable, Optional, Type, Union
from urllib.parse import urlencode
from django.core.cache import caches, BaseCache
from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict
from django.shortcuts import render, redirect
from django.utils.module_loading import import_string
from axes.conf import settings
from axes.models import AccessBase
import ipware.ip)
and context including class names, function names, or small code snippets from other files:
# Path: axes/conf.py
#
# Path: axes/models.py
# class AccessBase(models.Model):
# user_agent = models.CharField(_("User Agent"), max_length=255, db_index=True)
#
# ip_address = models.GenericIPAddressField(_("IP Address"), null=True, db_index=True)
#
# username = models.CharField(_("Username"), max_length=255, null=True, db_index=True)
#
# http_accept = models.CharField(_("HTTP Accept"), max_length=1025)
#
# path_info = models.CharField(_("Path"), max_length=255)
#
# attempt_time = models.DateTimeField(_("Attempt Time"), auto_now_add=True)
#
# class Meta:
# app_label = "axes"
# abstract = True
# ordering = ["-attempt_time"]
. Output only the next line. | return caches[getattr(settings, "AXES_CACHE", "default")] |
Given the code snippet: <|code_start|> else:
if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# One of `username` or `IP address` is used
filter_query = [{"username": username}, {"ip_address": ip_address}]
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# 2. A combination of username and IP address can be used as well
filter_query = [{"username": username, "ip_address": ip_address}]
else:
# 3. Default case is to track the IP address only, which is the most secure option
filter_query = [{"ip_address": ip_address}]
if settings.AXES_USE_USER_AGENT:
# 4. The HTTP User-Agent can be used to track e.g. one browser
filter_query.append({"user_agent": user_agent})
return filter_query
def make_cache_key_list(filter_kwargs_list):
cache_keys = []
for filter_kwargs in filter_kwargs_list:
cache_key_components = "".join(
value for value in filter_kwargs.values() if value
)
cache_key_digest = md5(cache_key_components.encode()).hexdigest()
cache_keys.append(f"axes-{cache_key_digest}")
return cache_keys
def get_client_cache_key(
<|code_end|>
, generate the next line using the imports in this file:
from datetime import timedelta
from hashlib import md5
from logging import getLogger
from string import Template
from typing import Callable, Optional, Type, Union
from urllib.parse import urlencode
from django.core.cache import caches, BaseCache
from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict
from django.shortcuts import render, redirect
from django.utils.module_loading import import_string
from axes.conf import settings
from axes.models import AccessBase
import ipware.ip
and context (functions, classes, or occasionally code) from other files:
# Path: axes/conf.py
#
# Path: axes/models.py
# class AccessBase(models.Model):
# user_agent = models.CharField(_("User Agent"), max_length=255, db_index=True)
#
# ip_address = models.GenericIPAddressField(_("IP Address"), null=True, db_index=True)
#
# username = models.CharField(_("Username"), max_length=255, null=True, db_index=True)
#
# http_accept = models.CharField(_("HTTP Accept"), max_length=1025)
#
# path_info = models.CharField(_("Path"), max_length=255)
#
# attempt_time = models.DateTimeField(_("Attempt Time"), auto_now_add=True)
#
# class Meta:
# app_label = "axes"
# abstract = True
# ordering = ["-attempt_time"]
. Output only the next line. | request_or_attempt: Union[HttpRequest, AccessBase], credentials: dict = None |
Given the following code snippet before the placeholder: <|code_start|>
class Command(BaseCommand):
help = "Reset all access attempts and lockouts for given IP addresses"
def add_arguments(self, parser):
parser.add_argument("ip", nargs="+", type=str)
def handle(self, *args, **options):
count = 0
for ip in options["ip"]:
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management.base import BaseCommand
from axes.utils import reset
and context including class names, function names, and sometimes code from other files:
# Path: axes/utils.py
# def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
# """
# Reset records that match IP or username, and return the count of removed attempts.
#
# This utility method is meant to be used from the CLI or via Python API.
# """
#
# return AxesProxyHandler.reset_attempts(
# ip_address=ip, username=username, ip_or_username=ip_or_username
# )
. Output only the next line. | count += reset(ip=ip) |
Given snippet: <|code_start|>
if attempt_time is None:
return now() - cool_off
return attempt_time - cool_off
def filter_user_attempts(request, credentials: dict = None) -> List[QuerySet]:
"""
Return a list querysets of AccessAttempts that match the given request and credentials.
"""
username = get_client_username(request, credentials)
filter_kwargs_list = get_client_parameters(
username, request.axes_ip_address, request.axes_user_agent
)
attempts_list = [
AccessAttempt.objects.filter(**filter_kwargs)
for filter_kwargs in filter_kwargs_list
]
return attempts_list
def get_user_attempts(request, credentials: dict = None) -> List[QuerySet]:
"""
Get list of querysets with valid user attempts that match the given request and credentials.
"""
attempts_list = filter_user_attempts(request, credentials)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from logging import getLogger
from typing import List
from django.db.models import QuerySet
from django.utils.timezone import datetime, now
from axes.conf import settings
from axes.helpers import get_client_username, get_client_parameters, get_cool_off
from axes.models import AccessAttempt
and context:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_client_username(request, credentials: dict = None) -> str:
# """
# Resolve client username from the given request or credentials if supplied.
#
# The order of preference for fetching the username is as follows:
#
# 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments
# 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
# 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
#
# :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source
# :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
# """
#
# if settings.AXES_USERNAME_CALLABLE:
# log.debug("Using settings.AXES_USERNAME_CALLABLE to get username")
#
# if callable(settings.AXES_USERNAME_CALLABLE):
# return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_USERNAME_CALLABLE, str):
# return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None."
# )
#
# if credentials:
# log.debug(
# "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
# return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# log.debug(
# "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
#
# request_data = getattr(request, "data", request.POST)
# return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# def get_client_parameters(username: str, ip_address: str, user_agent: str) -> list:
# """
# Get query parameters for filtering AccessAttempt queryset.
#
# This method returns a dict that guarantees iteration order for keys and values,
# and can so be used in e.g. the generation of hash keys or other deterministic functions.
#
# Returns list of dict, every item of list are separate parameters
# """
#
# if settings.AXES_ONLY_USER_FAILURES:
# # 1. Only individual usernames can be tracked with parametrization
# filter_query = [{"username": username}]
# else:
# if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# # One of `username` or `IP address` is used
# filter_query = [{"username": username}, {"ip_address": ip_address}]
# elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# # 2. A combination of username and IP address can be used as well
# filter_query = [{"username": username, "ip_address": ip_address}]
# else:
# # 3. Default case is to track the IP address only, which is the most secure option
# filter_query = [{"ip_address": ip_address}]
#
# if settings.AXES_USE_USER_AGENT:
# # 4. The HTTP User-Agent can be used to track e.g. one browser
# filter_query.append({"user_agent": user_agent})
#
# return filter_query
#
# def get_cool_off() -> Optional[timedelta]:
# """
# Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.
#
# The return value is either None or timedelta.
#
# Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,
# and this function offers a unified _timedelta or None_ representation of that configuration
# for use with the Axes internal implementations.
#
# :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
# """
#
# cool_off = settings.AXES_COOLOFF_TIME
#
# if isinstance(cool_off, int):
# return timedelta(hours=cool_off)
# if isinstance(cool_off, str):
# return import_string(cool_off)()
# if callable(cool_off):
# return cool_off() # pylint: disable=not-callable
#
# return cool_off
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
which might include code, classes, or functions. Output only the next line. | if settings.AXES_COOLOFF_TIME is None: |
Continue the code snippet: <|code_start|>
log = getLogger(__name__)
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime:
"""
Get threshold for fetching access attempts from the database.
"""
cool_off = get_cool_off()
if cool_off is None:
raise TypeError(
"Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None"
)
if attempt_time is None:
return now() - cool_off
return attempt_time - cool_off
def filter_user_attempts(request, credentials: dict = None) -> List[QuerySet]:
"""
Return a list querysets of AccessAttempts that match the given request and credentials.
"""
<|code_end|>
. Use current file imports:
from logging import getLogger
from typing import List
from django.db.models import QuerySet
from django.utils.timezone import datetime, now
from axes.conf import settings
from axes.helpers import get_client_username, get_client_parameters, get_cool_off
from axes.models import AccessAttempt
and context (classes, functions, or code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_client_username(request, credentials: dict = None) -> str:
# """
# Resolve client username from the given request or credentials if supplied.
#
# The order of preference for fetching the username is as follows:
#
# 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments
# 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
# 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
#
# :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source
# :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
# """
#
# if settings.AXES_USERNAME_CALLABLE:
# log.debug("Using settings.AXES_USERNAME_CALLABLE to get username")
#
# if callable(settings.AXES_USERNAME_CALLABLE):
# return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_USERNAME_CALLABLE, str):
# return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None."
# )
#
# if credentials:
# log.debug(
# "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
# return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# log.debug(
# "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
#
# request_data = getattr(request, "data", request.POST)
# return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# def get_client_parameters(username: str, ip_address: str, user_agent: str) -> list:
# """
# Get query parameters for filtering AccessAttempt queryset.
#
# This method returns a dict that guarantees iteration order for keys and values,
# and can so be used in e.g. the generation of hash keys or other deterministic functions.
#
# Returns list of dict, every item of list are separate parameters
# """
#
# if settings.AXES_ONLY_USER_FAILURES:
# # 1. Only individual usernames can be tracked with parametrization
# filter_query = [{"username": username}]
# else:
# if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# # One of `username` or `IP address` is used
# filter_query = [{"username": username}, {"ip_address": ip_address}]
# elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# # 2. A combination of username and IP address can be used as well
# filter_query = [{"username": username, "ip_address": ip_address}]
# else:
# # 3. Default case is to track the IP address only, which is the most secure option
# filter_query = [{"ip_address": ip_address}]
#
# if settings.AXES_USE_USER_AGENT:
# # 4. The HTTP User-Agent can be used to track e.g. one browser
# filter_query.append({"user_agent": user_agent})
#
# return filter_query
#
# def get_cool_off() -> Optional[timedelta]:
# """
# Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.
#
# The return value is either None or timedelta.
#
# Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,
# and this function offers a unified _timedelta or None_ representation of that configuration
# for use with the Axes internal implementations.
#
# :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
# """
#
# cool_off = settings.AXES_COOLOFF_TIME
#
# if isinstance(cool_off, int):
# return timedelta(hours=cool_off)
# if isinstance(cool_off, str):
# return import_string(cool_off)()
# if callable(cool_off):
# return cool_off() # pylint: disable=not-callable
#
# return cool_off
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | username = get_client_username(request, credentials) |
Continue the code snippet: <|code_start|>
log = getLogger(__name__)
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime:
"""
Get threshold for fetching access attempts from the database.
"""
cool_off = get_cool_off()
if cool_off is None:
raise TypeError(
"Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None"
)
if attempt_time is None:
return now() - cool_off
return attempt_time - cool_off
def filter_user_attempts(request, credentials: dict = None) -> List[QuerySet]:
"""
Return a list querysets of AccessAttempts that match the given request and credentials.
"""
username = get_client_username(request, credentials)
<|code_end|>
. Use current file imports:
from logging import getLogger
from typing import List
from django.db.models import QuerySet
from django.utils.timezone import datetime, now
from axes.conf import settings
from axes.helpers import get_client_username, get_client_parameters, get_cool_off
from axes.models import AccessAttempt
and context (classes, functions, or code) from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_client_username(request, credentials: dict = None) -> str:
# """
# Resolve client username from the given request or credentials if supplied.
#
# The order of preference for fetching the username is as follows:
#
# 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments
# 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
# 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
#
# :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source
# :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
# """
#
# if settings.AXES_USERNAME_CALLABLE:
# log.debug("Using settings.AXES_USERNAME_CALLABLE to get username")
#
# if callable(settings.AXES_USERNAME_CALLABLE):
# return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_USERNAME_CALLABLE, str):
# return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None."
# )
#
# if credentials:
# log.debug(
# "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
# return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# log.debug(
# "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
#
# request_data = getattr(request, "data", request.POST)
# return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# def get_client_parameters(username: str, ip_address: str, user_agent: str) -> list:
# """
# Get query parameters for filtering AccessAttempt queryset.
#
# This method returns a dict that guarantees iteration order for keys and values,
# and can so be used in e.g. the generation of hash keys or other deterministic functions.
#
# Returns list of dict, every item of list are separate parameters
# """
#
# if settings.AXES_ONLY_USER_FAILURES:
# # 1. Only individual usernames can be tracked with parametrization
# filter_query = [{"username": username}]
# else:
# if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# # One of `username` or `IP address` is used
# filter_query = [{"username": username}, {"ip_address": ip_address}]
# elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# # 2. A combination of username and IP address can be used as well
# filter_query = [{"username": username, "ip_address": ip_address}]
# else:
# # 3. Default case is to track the IP address only, which is the most secure option
# filter_query = [{"ip_address": ip_address}]
#
# if settings.AXES_USE_USER_AGENT:
# # 4. The HTTP User-Agent can be used to track e.g. one browser
# filter_query.append({"user_agent": user_agent})
#
# return filter_query
#
# def get_cool_off() -> Optional[timedelta]:
# """
# Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.
#
# The return value is either None or timedelta.
#
# Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,
# and this function offers a unified _timedelta or None_ representation of that configuration
# for use with the Axes internal implementations.
#
# :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
# """
#
# cool_off = settings.AXES_COOLOFF_TIME
#
# if isinstance(cool_off, int):
# return timedelta(hours=cool_off)
# if isinstance(cool_off, str):
# return import_string(cool_off)()
# if callable(cool_off):
# return cool_off() # pylint: disable=not-callable
#
# return cool_off
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | filter_kwargs_list = get_client_parameters( |
Using the snippet: <|code_start|>
log = getLogger(__name__)
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime:
"""
Get threshold for fetching access attempts from the database.
"""
<|code_end|>
, determine the next line of code. You have imports:
from logging import getLogger
from typing import List
from django.db.models import QuerySet
from django.utils.timezone import datetime, now
from axes.conf import settings
from axes.helpers import get_client_username, get_client_parameters, get_cool_off
from axes.models import AccessAttempt
and context (class names, function names, or code) available:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_client_username(request, credentials: dict = None) -> str:
# """
# Resolve client username from the given request or credentials if supplied.
#
# The order of preference for fetching the username is as follows:
#
# 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments
# 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
# 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
#
# :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source
# :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
# """
#
# if settings.AXES_USERNAME_CALLABLE:
# log.debug("Using settings.AXES_USERNAME_CALLABLE to get username")
#
# if callable(settings.AXES_USERNAME_CALLABLE):
# return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_USERNAME_CALLABLE, str):
# return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None."
# )
#
# if credentials:
# log.debug(
# "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
# return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# log.debug(
# "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
#
# request_data = getattr(request, "data", request.POST)
# return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# def get_client_parameters(username: str, ip_address: str, user_agent: str) -> list:
# """
# Get query parameters for filtering AccessAttempt queryset.
#
# This method returns a dict that guarantees iteration order for keys and values,
# and can so be used in e.g. the generation of hash keys or other deterministic functions.
#
# Returns list of dict, every item of list are separate parameters
# """
#
# if settings.AXES_ONLY_USER_FAILURES:
# # 1. Only individual usernames can be tracked with parametrization
# filter_query = [{"username": username}]
# else:
# if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# # One of `username` or `IP address` is used
# filter_query = [{"username": username}, {"ip_address": ip_address}]
# elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# # 2. A combination of username and IP address can be used as well
# filter_query = [{"username": username, "ip_address": ip_address}]
# else:
# # 3. Default case is to track the IP address only, which is the most secure option
# filter_query = [{"ip_address": ip_address}]
#
# if settings.AXES_USE_USER_AGENT:
# # 4. The HTTP User-Agent can be used to track e.g. one browser
# filter_query.append({"user_agent": user_agent})
#
# return filter_query
#
# def get_cool_off() -> Optional[timedelta]:
# """
# Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.
#
# The return value is either None or timedelta.
#
# Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,
# and this function offers a unified _timedelta or None_ representation of that configuration
# for use with the Axes internal implementations.
#
# :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
# """
#
# cool_off = settings.AXES_COOLOFF_TIME
#
# if isinstance(cool_off, int):
# return timedelta(hours=cool_off)
# if isinstance(cool_off, str):
# return import_string(cool_off)()
# if callable(cool_off):
# return cool_off() # pylint: disable=not-callable
#
# return cool_off
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | cool_off = get_cool_off() |
Predict the next line for this snippet: <|code_start|>log = getLogger(__name__)
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime:
"""
Get threshold for fetching access attempts from the database.
"""
cool_off = get_cool_off()
if cool_off is None:
raise TypeError(
"Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None"
)
if attempt_time is None:
return now() - cool_off
return attempt_time - cool_off
def filter_user_attempts(request, credentials: dict = None) -> List[QuerySet]:
"""
Return a list querysets of AccessAttempts that match the given request and credentials.
"""
username = get_client_username(request, credentials)
filter_kwargs_list = get_client_parameters(
username, request.axes_ip_address, request.axes_user_agent
)
attempts_list = [
<|code_end|>
with the help of current file imports:
from logging import getLogger
from typing import List
from django.db.models import QuerySet
from django.utils.timezone import datetime, now
from axes.conf import settings
from axes.helpers import get_client_username, get_client_parameters, get_cool_off
from axes.models import AccessAttempt
and context from other files:
# Path: axes/conf.py
#
# Path: axes/helpers.py
# def get_client_username(request, credentials: dict = None) -> str:
# """
# Resolve client username from the given request or credentials if supplied.
#
# The order of preference for fetching the username is as follows:
#
# 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as arguments
# 2. If given, use ``credentials`` and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
# 3. Use request.POST and fetch username from ``AXES_USERNAME_FORM_FIELD`` (defaults to ``username``)
#
# :param request: incoming Django ``HttpRequest`` or similar object from authentication backend or other source
# :param credentials: incoming credentials ``dict`` or similar object from authentication backend or other source
# """
#
# if settings.AXES_USERNAME_CALLABLE:
# log.debug("Using settings.AXES_USERNAME_CALLABLE to get username")
#
# if callable(settings.AXES_USERNAME_CALLABLE):
# return settings.AXES_USERNAME_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_USERNAME_CALLABLE, str):
# return import_string(settings.AXES_USERNAME_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_USERNAME_CALLABLE needs to be a string, callable, or None."
# )
#
# if credentials:
# log.debug(
# "Using parameter credentials to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
# return credentials.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# log.debug(
# "Using parameter request.POST to get username with key settings.AXES_USERNAME_FORM_FIELD"
# )
#
# request_data = getattr(request, "data", request.POST)
# return request_data.get(settings.AXES_USERNAME_FORM_FIELD, None)
#
# def get_client_parameters(username: str, ip_address: str, user_agent: str) -> list:
# """
# Get query parameters for filtering AccessAttempt queryset.
#
# This method returns a dict that guarantees iteration order for keys and values,
# and can so be used in e.g. the generation of hash keys or other deterministic functions.
#
# Returns list of dict, every item of list are separate parameters
# """
#
# if settings.AXES_ONLY_USER_FAILURES:
# # 1. Only individual usernames can be tracked with parametrization
# filter_query = [{"username": username}]
# else:
# if settings.AXES_LOCK_OUT_BY_USER_OR_IP:
# # One of `username` or `IP address` is used
# filter_query = [{"username": username}, {"ip_address": ip_address}]
# elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
# # 2. A combination of username and IP address can be used as well
# filter_query = [{"username": username, "ip_address": ip_address}]
# else:
# # 3. Default case is to track the IP address only, which is the most secure option
# filter_query = [{"ip_address": ip_address}]
#
# if settings.AXES_USE_USER_AGENT:
# # 4. The HTTP User-Agent can be used to track e.g. one browser
# filter_query.append({"user_agent": user_agent})
#
# return filter_query
#
# def get_cool_off() -> Optional[timedelta]:
# """
# Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME.
#
# The return value is either None or timedelta.
#
# Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours,
# and this function offers a unified _timedelta or None_ representation of that configuration
# for use with the Axes internal implementations.
#
# :exception TypeError: if settings.AXES_COOLOFF_TIME is of wrong type.
# """
#
# cool_off = settings.AXES_COOLOFF_TIME
#
# if isinstance(cool_off, int):
# return timedelta(hours=cool_off)
# if isinstance(cool_off, str):
# return import_string(cool_off)()
# if callable(cool_off):
# return cool_off() # pylint: disable=not-callable
#
# return cool_off
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
, which may contain function names, class names, or code. Output only the next line. | AccessAttempt.objects.filter(**filter_kwargs) |
Using the snippet: <|code_start|>
class Command(BaseCommand):
help = "Reset all access attempts and lockouts"
def handle(self, *args, **options):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from axes.utils import reset
and context (class names, function names, or code) available:
# Path: axes/utils.py
# def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
# """
# Reset records that match IP or username, and return the count of removed attempts.
#
# This utility method is meant to be used from the CLI or via Python API.
# """
#
# return AxesProxyHandler.reset_attempts(
# ip_address=ip, username=username, ip_or_username=ip_or_username
# )
. Output only the next line. | count = reset() |
Next line prediction: <|code_start|> and maps lockout signals into readable HTTP 403 Forbidden responses.
If a project uses ``django rest framework`` then the middleware updates the
request and checks whether the limit has been exceeded. It's needed only
for integration with DRF because it uses its own request object.
This middleware recognizes a logout monitoring flag in the request and
and uses the ``axes.helpers.get_lockout_response`` handler for returning
customizable and context aware lockout message to the end user if necessary.
To customize the lockout handling behaviour further, you can subclass this middleware
and change the ``__call__`` method to your own liking.
Please see the following configuration flags before customizing this handler:
- ``AXES_LOCKOUT_TEMPLATE``,
- ``AXES_LOCKOUT_URL``,
- ``AXES_COOLOFF_MESSAGE``, and
- ``AXES_PERMALOCK_MESSAGE``.
"""
def __init__(self, get_response: Callable):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if settings.AXES_ENABLED:
if getattr(request, "axes_locked_out", None):
credentials = getattr(request, "axes_credentials", None)
<|code_end|>
. Use current file imports:
(from typing import Callable
from django.conf import settings
from axes.helpers import get_lockout_response)
and context including class names, function names, or small code snippets from other files:
# Path: axes/helpers.py
# def get_lockout_response(request, credentials: dict = None) -> HttpResponse:
# if settings.AXES_LOCKOUT_CALLABLE:
# if callable(settings.AXES_LOCKOUT_CALLABLE):
# return settings.AXES_LOCKOUT_CALLABLE( # pylint: disable=not-callable
# request, credentials
# )
# if isinstance(settings.AXES_LOCKOUT_CALLABLE, str):
# return import_string(settings.AXES_LOCKOUT_CALLABLE)(request, credentials)
# raise TypeError(
# "settings.AXES_LOCKOUT_CALLABLE needs to be a string, callable, or None."
# )
#
# status = settings.AXES_HTTP_RESPONSE_CODE
# context = {
# "failure_limit": get_failure_limit(request, credentials),
# "username": get_client_username(request, credentials) or "",
# }
#
# cool_off = get_cool_off()
# if cool_off:
# context.update(
# {
# "cooloff_time": get_cool_off_iso8601(
# cool_off
# ), # differing old name is kept for backwards compatibility
# "cooloff_timedelta": cool_off,
# }
# )
#
# if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest":
# json_response = JsonResponse(context, status=status)
# json_response[
# "Access-Control-Allow-Origin"
# ] = settings.AXES_ALLOWED_CORS_ORIGINS
# json_response["Access-Control-Allow-Methods"] = "POST, OPTIONS"
# json_response[
# "Access-Control-Allow-Headers"
# ] = "Origin, Content-Type, Accept, Authorization, x-requested-with"
# return json_response
#
# if settings.AXES_LOCKOUT_TEMPLATE:
# return render(request, settings.AXES_LOCKOUT_TEMPLATE, context, status=status)
#
# if settings.AXES_LOCKOUT_URL:
# lockout_url = settings.AXES_LOCKOUT_URL
# query_string = urlencode({"username": context["username"]})
# url = f"{lockout_url}?{query_string}"
# return redirect(url)
#
# return HttpResponse(get_lockout_message(), status=status)
. Output only the next line. | response = get_lockout_response(request, credentials) # type: ignore |
Given snippet: <|code_start|>"""
log = getLogger(__name__)
def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
return AxesProxyHandler.reset_attempts(
ip_address=ip, username=username, ip_or_username=ip_or_username
)
def reset_request(request: HttpRequest) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
ip: Optional[str] = get_client_ip_address(request)
username = request.GET.get("username", None)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from logging import getLogger
from typing import Optional
from django.http import HttpRequest
from axes.conf import settings
from axes.handlers.proxy import AxesProxyHandler
from axes.helpers import get_client_ip_address
and context:
# Path: axes/conf.py
#
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
#
# Path: axes/helpers.py
# def get_client_ip_address(request) -> str:
# """
# Get client IP address as configured by the user.
#
# The django-ipware package is used for address resolution
# and parameters can be configured in the Axes package.
# """
#
# client_ip_address, _ = ipware.ip.get_client_ip(
# request,
# proxy_order=settings.AXES_PROXY_ORDER,
# proxy_count=settings.AXES_PROXY_COUNT,
# proxy_trusted_ips=settings.AXES_PROXY_TRUSTED_IPS,
# request_header_order=settings.AXES_META_PRECEDENCE_ORDER,
# )
#
# return client_ip_address
which might include code, classes, or functions. Output only the next line. | ip_or_username = settings.AXES_LOCK_OUT_BY_USER_OR_IP |
Using the snippet: <|code_start|>"""
Axes utility functions that are publicly available.
This module is separate for historical reasons
and offers a backwards compatible import path.
"""
log = getLogger(__name__)
def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
<|code_end|>
, determine the next line of code. You have imports:
from logging import getLogger
from typing import Optional
from django.http import HttpRequest
from axes.conf import settings
from axes.handlers.proxy import AxesProxyHandler
from axes.helpers import get_client_ip_address
and context (class names, function names, or code) available:
# Path: axes/conf.py
#
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
#
# Path: axes/helpers.py
# def get_client_ip_address(request) -> str:
# """
# Get client IP address as configured by the user.
#
# The django-ipware package is used for address resolution
# and parameters can be configured in the Axes package.
# """
#
# client_ip_address, _ = ipware.ip.get_client_ip(
# request,
# proxy_order=settings.AXES_PROXY_ORDER,
# proxy_count=settings.AXES_PROXY_COUNT,
# proxy_trusted_ips=settings.AXES_PROXY_TRUSTED_IPS,
# request_header_order=settings.AXES_META_PRECEDENCE_ORDER,
# )
#
# return client_ip_address
. Output only the next line. | return AxesProxyHandler.reset_attempts( |
Based on the snippet: <|code_start|>
This module is separate for historical reasons
and offers a backwards compatible import path.
"""
log = getLogger(__name__)
def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
return AxesProxyHandler.reset_attempts(
ip_address=ip, username=username, ip_or_username=ip_or_username
)
def reset_request(request: HttpRequest) -> int:
"""
Reset records that match IP or username, and return the count of removed attempts.
This utility method is meant to be used from the CLI or via Python API.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from logging import getLogger
from typing import Optional
from django.http import HttpRequest
from axes.conf import settings
from axes.handlers.proxy import AxesProxyHandler
from axes.helpers import get_client_ip_address
and context (classes, functions, sometimes code) from other files:
# Path: axes/conf.py
#
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
#
# Path: axes/helpers.py
# def get_client_ip_address(request) -> str:
# """
# Get client IP address as configured by the user.
#
# The django-ipware package is used for address resolution
# and parameters can be configured in the Axes package.
# """
#
# client_ip_address, _ = ipware.ip.get_client_ip(
# request,
# proxy_order=settings.AXES_PROXY_ORDER,
# proxy_count=settings.AXES_PROXY_COUNT,
# proxy_trusted_ips=settings.AXES_PROXY_TRUSTED_IPS,
# request_header_order=settings.AXES_META_PRECEDENCE_ORDER,
# )
#
# return client_ip_address
. Output only the next line. | ip: Optional[str] = get_client_ip_address(request) |
Next line prediction: <|code_start|>
class Command(BaseCommand):
help = "List access attempts"
def handle(self, *args, **options):
<|code_end|>
. Use current file imports:
(from django.core.management.base import BaseCommand
from axes.models import AccessAttempt)
and context including class names, function names, or small code snippets from other files:
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | for obj in AccessAttempt.objects.all(): |
Based on the snippet: <|code_start|>
if "axes.middleware.AxesMiddleware" not in settings.MIDDLEWARE:
warnings.append(
Warning(
msg=Messages.MIDDLEWARE_INVALID,
hint=Hints.MIDDLEWARE_INVALID,
id=Codes.MIDDLEWARE_INVALID,
)
)
return warnings
@register(Tags.security, Tags.compatibility)
def axes_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument
warnings = []
found = False
for name in settings.AUTHENTICATION_BACKENDS:
try:
backend = import_string(name)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
"Can not find module path defined in settings.AUTHENTICATION_BACKENDS"
) from e
except ImportError as e:
raise ImportError(
"Can not import backend class defined in settings.AUTHENTICATION_BACKENDS"
) from e
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.checks import ( # pylint: disable=redefined-builtin
Tags,
Warning,
register,
)
from django.utils.module_loading import import_string
from axes.backends import AxesBackend
from axes.conf import settings
and context (classes, functions, sometimes code) from other files:
# Path: axes/backends.py
# class AxesBackend(ModelBackend):
# """
# Authentication backend class that forbids login attempts for locked out users.
#
# Use this class as the first item of ``AUTHENTICATION_BACKENDS`` to
# prevent locked out users from being logged in by the Django authentication flow.
#
# .. note:: This backend does not log your user in. It monitors login attempts.
# Authentication is handled by the following backends that are configured in ``AUTHENTICATION_BACKENDS``.
# """
#
# @toggleable
# def authenticate(
# self, request, username: str = None, password: str = None, **kwargs: dict
# ):
# """
# Checks user lockout status and raises an exception if user is not allowed to log in.
#
# This method interrupts the login flow and inserts error message directly to the
# ``response_context`` attribute that is supplied as a keyword argument.
#
# :keyword response_context: kwarg that will be have its ``error`` attribute updated with context.
# :raises AxesBackendRequestParameterRequired: if request parameter is not passed.
# :raises AxesBackendPermissionDenied: if user is already locked out.
# """
#
# if request is None:
# raise AxesBackendRequestParameterRequired(
# "AxesBackend requires a request as an argument to authenticate"
# )
#
# credentials = get_credentials(username=username, password=password, **kwargs)
#
# if AxesProxyHandler.is_allowed(request, credentials):
# return
#
# # Locked out, don't try to authenticate, just update response_context and return.
# # Its a bit weird to pass a context and expect a response value but its nice to get a "why" back.
#
# error_msg = get_lockout_message()
# response_context = kwargs.get("response_context", {})
# response_context["error"] = error_msg
#
# # Raise an error that stops the authentication flows at django.contrib.auth.authenticate.
# # This error stops bubbling up at the authenticate call which catches backend PermissionDenied errors.
# # After this error is caught by authenticate it emits a signal indicating user login failed,
# # which is processed by axes.signals.log_user_login_failed which logs and flags the failed request.
# # The axes.middleware.AxesMiddleware further processes the flagged request into a readable response.
#
# raise AxesBackendPermissionDenied(
# "AxesBackend detected that the given user is locked out"
# )
#
# Path: axes/conf.py
. Output only the next line. | if issubclass(backend, AxesBackend): |
Predict the next line after this snippet: <|code_start|> "You are using the django-axes cache handler for login attempt tracking."
" Your cache configuration is however invalid and will not work correctly with django-axes."
" This can leave security holes in your login systems as attempts are not tracked correctly."
" Reconfigure settings.AXES_CACHE and settings.CACHES per django-axes configuration documentation."
)
MIDDLEWARE_INVALID = (
"You do not have 'axes.middleware.AxesMiddleware' in your settings.MIDDLEWARE."
)
BACKEND_INVALID = "You do not have 'axes.backends.AxesBackend' or a subclass in your settings.AUTHENTICATION_BACKENDS."
SETTING_DEPRECATED = "You have a deprecated setting {deprecated_setting} configured in your project settings"
class Hints:
CACHE_INVALID = None
MIDDLEWARE_INVALID = None
BACKEND_INVALID = (
"AxesModelBackend was renamed to AxesBackend in django-axes version 5.0."
)
SETTING_DEPRECATED = None
class Codes:
CACHE_INVALID = "axes.W001"
MIDDLEWARE_INVALID = "axes.W002"
BACKEND_INVALID = "axes.W003"
SETTING_DEPRECATED = "axes.W004"
@register(Tags.security, Tags.caches, Tags.compatibility)
def axes_cache_check(app_configs, **kwargs): # pylint: disable=unused-argument
<|code_end|>
using the current file's imports:
from django.core.checks import ( # pylint: disable=redefined-builtin
Tags,
Warning,
register,
)
from django.utils.module_loading import import_string
from axes.backends import AxesBackend
from axes.conf import settings
and any relevant context from other files:
# Path: axes/backends.py
# class AxesBackend(ModelBackend):
# """
# Authentication backend class that forbids login attempts for locked out users.
#
# Use this class as the first item of ``AUTHENTICATION_BACKENDS`` to
# prevent locked out users from being logged in by the Django authentication flow.
#
# .. note:: This backend does not log your user in. It monitors login attempts.
# Authentication is handled by the following backends that are configured in ``AUTHENTICATION_BACKENDS``.
# """
#
# @toggleable
# def authenticate(
# self, request, username: str = None, password: str = None, **kwargs: dict
# ):
# """
# Checks user lockout status and raises an exception if user is not allowed to log in.
#
# This method interrupts the login flow and inserts error message directly to the
# ``response_context`` attribute that is supplied as a keyword argument.
#
# :keyword response_context: kwarg that will be have its ``error`` attribute updated with context.
# :raises AxesBackendRequestParameterRequired: if request parameter is not passed.
# :raises AxesBackendPermissionDenied: if user is already locked out.
# """
#
# if request is None:
# raise AxesBackendRequestParameterRequired(
# "AxesBackend requires a request as an argument to authenticate"
# )
#
# credentials = get_credentials(username=username, password=password, **kwargs)
#
# if AxesProxyHandler.is_allowed(request, credentials):
# return
#
# # Locked out, don't try to authenticate, just update response_context and return.
# # Its a bit weird to pass a context and expect a response value but its nice to get a "why" back.
#
# error_msg = get_lockout_message()
# response_context = kwargs.get("response_context", {})
# response_context["error"] = error_msg
#
# # Raise an error that stops the authentication flows at django.contrib.auth.authenticate.
# # This error stops bubbling up at the authenticate call which catches backend PermissionDenied errors.
# # After this error is caught by authenticate it emits a signal indicating user login failed,
# # which is processed by axes.signals.log_user_login_failed which logs and flags the failed request.
# # The axes.middleware.AxesMiddleware further processes the flagged request into a readable response.
#
# raise AxesBackendPermissionDenied(
# "AxesBackend detected that the given user is locked out"
# )
#
# Path: axes/conf.py
. Output only the next line. | axes_handler = getattr(settings, "AXES_HANDLER", "") |
Predict the next line for this snippet: <|code_start|>
class Command(BaseCommand):
help = "Reset all access attempts and lockouts for given usernames"
def add_arguments(self, parser):
parser.add_argument("username", nargs="+", type=str)
def handle(self, *args, **options):
count = 0
for username in options["username"]:
<|code_end|>
with the help of current file imports:
from django.core.management.base import BaseCommand
from axes.utils import reset
and context from other files:
# Path: axes/utils.py
# def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
# """
# Reset records that match IP or username, and return the count of removed attempts.
#
# This utility method is meant to be used from the CLI or via Python API.
# """
#
# return AxesProxyHandler.reset_attempts(
# ip_address=ip, username=username, ip_or_username=ip_or_username
# )
, which may contain function names, class names, or code. Output only the next line. | count += reset(username=username) |
Using the snippet: <|code_start|>
log = getLogger(__name__)
# This signal provides the following arguments to any listeners:
# request - The current Request object.
# username - The username of the User who has been locked out.
# ip_address - The IP of the user who has been locked out.
user_locked_out = Signal()
@receiver(user_login_failed)
def handle_user_login_failed(*args, **kwargs):
<|code_end|>
, determine the next line of code. You have imports:
from logging import getLogger
from django.contrib.auth.signals import (
user_logged_in,
user_logged_out,
user_login_failed,
)
from django.core.signals import setting_changed
from django.db.models.signals import post_save, post_delete
from django.dispatch import Signal
from django.dispatch import receiver
from axes.handlers.proxy import AxesProxyHandler
from axes.models import AccessAttempt
and context (class names, function names, or code) available:
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | AxesProxyHandler.user_login_failed(*args, **kwargs) |
Using the snippet: <|code_start|>
log = getLogger(__name__)
# This signal provides the following arguments to any listeners:
# request - The current Request object.
# username - The username of the User who has been locked out.
# ip_address - The IP of the user who has been locked out.
user_locked_out = Signal()
@receiver(user_login_failed)
def handle_user_login_failed(*args, **kwargs):
AxesProxyHandler.user_login_failed(*args, **kwargs)
@receiver(user_logged_in)
def handle_user_logged_in(*args, **kwargs):
AxesProxyHandler.user_logged_in(*args, **kwargs)
@receiver(user_logged_out)
def handle_user_logged_out(*args, **kwargs):
AxesProxyHandler.user_logged_out(*args, **kwargs)
<|code_end|>
, determine the next line of code. You have imports:
from logging import getLogger
from django.contrib.auth.signals import (
user_logged_in,
user_logged_out,
user_login_failed,
)
from django.core.signals import setting_changed
from django.db.models.signals import post_save, post_delete
from django.dispatch import Signal
from django.dispatch import receiver
from axes.handlers.proxy import AxesProxyHandler
from axes.models import AccessAttempt
and context (class names, function names, or code) available:
# Path: axes/handlers/proxy.py
# class AxesProxyHandler(AbstractAxesHandler, AxesBaseHandler):
# """
# Proxy interface for configurable Axes signal handler class.
#
# If you wish to implement a custom version of this handler,
# you can override the settings.AXES_HANDLER configuration string
# with a class that implements a compatible interface and methods.
#
# Defaults to using axes.handlers.proxy.AxesProxyHandler if not overridden.
# Refer to axes.handlers.proxy.AxesProxyHandler for default implementation.
# """
#
# implementation = None # type: AxesHandler
#
# @classmethod
# def get_implementation(cls, force: bool = False) -> AxesHandler:
# """
# Fetch and initialize configured handler implementation and memoize it to avoid reinitialization.
#
# This method is re-entrant and can be called multiple times from e.g. Django application loader.
# """
#
# if force or not cls.implementation:
# cls.implementation = import_string(settings.AXES_HANDLER)()
# return cls.implementation
#
# @classmethod
# def reset_attempts(
# cls,
# *,
# ip_address: str = None,
# username: str = None,
# ip_or_username: bool = False,
# ) -> int:
# return cls.get_implementation().reset_attempts(
# ip_address=ip_address, username=username, ip_or_username=ip_or_username
# )
#
# @classmethod
# def reset_logs(cls, *, age_days: int = None) -> int:
# return cls.get_implementation().reset_logs(age_days=age_days)
#
# @staticmethod
# def update_request(request):
# """
# Update request attributes before passing them into the selected handler class.
# """
#
# if request is None:
# log.error(
# "AXES: AxesProxyHandler.update_request can not set request attributes to a None request"
# )
# return
# if not hasattr(request, "axes_updated"):
# request.axes_locked_out = False
# request.axes_attempt_time = now()
# request.axes_ip_address = get_client_ip_address(request)
# request.axes_user_agent = get_client_user_agent(request)
# request.axes_path_info = get_client_path_info(request)
# request.axes_http_accept = get_client_http_accept(request)
# request.axes_failures_since_start = None
# request.axes_updated = True
# request.axes_credentials = None
#
# @classmethod
# def is_locked(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_locked(request, credentials)
#
# @classmethod
# def is_allowed(cls, request, credentials: dict = None) -> bool:
# cls.update_request(request)
# return cls.get_implementation().is_allowed(request, credentials)
#
# @classmethod
# def get_failures(cls, request, credentials: dict = None) -> int:
# cls.update_request(request)
# return cls.get_implementation().get_failures(request, credentials)
#
# @classmethod
# @toggleable
# def user_login_failed(cls, sender, credentials: dict, request=None, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_login_failed(
# sender, credentials, request, **kwargs
# )
#
# @classmethod
# @toggleable
# def user_logged_in(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_in(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def user_logged_out(cls, sender, request, user, **kwargs):
# cls.update_request(request)
# return cls.get_implementation().user_logged_out(sender, request, user, **kwargs)
#
# @classmethod
# @toggleable
# def post_save_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_save_access_attempt(instance, **kwargs)
#
# @classmethod
# @toggleable
# def post_delete_access_attempt(cls, instance, **kwargs):
# return cls.get_implementation().post_delete_access_attempt(instance, **kwargs)
#
# Path: axes/models.py
# class AccessAttempt(AccessBase):
# get_data = models.TextField(_("GET Data"))
#
# post_data = models.TextField(_("POST Data"))
#
# failures_since_start = models.PositiveIntegerField(_("Failed Logins"))
#
# def __str__(self):
# return f"Attempted Access: {self.attempt_time}"
#
# class Meta:
# verbose_name = _("access attempt")
# verbose_name_plural = _("access attempts")
# unique_together = [["username", "ip_address", "user_agent"]]
. Output only the next line. | @receiver(post_save, sender=AccessAttempt) |
Predict the next line after this snippet: <|code_start|>
def cover_task():
######################
IMAGE_SCALE = 0.4
screen, spots = initialize_kelpy(dimensions=(1920,1200), bg=(255, 255, 255))
#game.init()
#screen = game.display.set_mode([500, 500])
gameon = True
background_color = pygame.color.Color("black")
#while gameon:
BLICKET_DETECTOR_POSITION = (spots.c1[0], spots.c1[1] + 100)
blicketd_image_path = (kstimulus("shapes/triangle_yellow.png"))
BLICKET_DETECTOR_POSITION_2 = (spots.c2[0], spots.c2[1] + 100)
blicketd_image_path_2 = (kstimulus("shapes/star_pink.png"))
BLICKET_DETECTOR_POSITION_3 = (spots.c3[0], spots.c3[0], 100)
blicketd_image_path_3 = (kstimulus("shapes/circle_red.png"))
pygame.display.flip() # tells game to refresh the display,
# all code involving the display of things must go ABOVE this line
event = pygame.event.poll() # ask game to examine all things happening in the game now
# code that responds to keyboard of mouse events goes after pool line
# need to pool all current events before dealing wtih them
def present_trial(imagepath):
<|code_end|>
using the current file's imports:
import os, sys
import pygame
import glob
import numpy
from random import randint, choice, sample, shuffle
from time import time,sleep
from kelpy.GIFImage import *
from kelpy.CommandableImageSprite import *
from kelpy.Miscellaneous import *
from kelpy.DisplayQueue import *
from kelpy.OrderedUpdates import *
from kelpy.EventHandler import *
from kelpy.DragDrop import DragSprite, DropSprite
from kelpy.DragDrop import *
from kelpy.tobii.TobiiSimController import *
from kelpy.tobii.TobiiSprite import *
and any relevant context from other files:
# Path: kelpy/DragDrop.py
# class DragSprite(CommandableImageSprite, Dragable):
# """
# The DragSprite is used to create a dragable sprite. It is written so that you feed it similar parameters that you would feed a regualar CommandableImageSprite.
# The only difference is that this sprite is able to be dragged around, once the drag and drop function is run in the main event loop (object.process_dragndrop(event))
# """
# def __init__(self, canvas, initial_position, imgpath, rotation=0, scale=.20):
# CommandableImageSprite.__init__(self, canvas, initial_position, imgpath, rotation, scale)
# Dragable.__init__(self)
# self.set_x(initial_position[0])
# self.set_y(initial_position[1])
# self.set_height(self.display_image.get_height())
# self.set_width(self.display_image.get_width())
#
# class DropSprite(CommandableImageSprite, Arrangeable):
# """
# The DropSprite class is used to create a sprite with a drop zone on top of it. You then register the drop zone via the DragSprite.register_drop_zone(DropSprite) line.
#
# """
# def __init__(self, canvas, initial_position, imgpath, rotation=0, scale=.20):
# CommandableImageSprite.__init__(self, canvas, initial_position, imgpath, rotation, scale)
# Arrangeable.__init__(self)
# self.set_x(initial_position[0])
# self.set_y(initial_position[1])
# self.set_height(self.display_image.get_height())
# self.set_width(self.display_image.get_width())
. Output only the next line. | thing = DragSprite(screen, spots.cu, imagepath, scale=IMAGE_SCALE) |
Next line prediction: <|code_start|>
def cover_task():
######################
IMAGE_SCALE = 0.4
screen, spots = initialize_kelpy(dimensions=(1920,1200), bg=(255, 255, 255))
#game.init()
#screen = game.display.set_mode([500, 500])
gameon = True
background_color = pygame.color.Color("black")
#while gameon:
BLICKET_DETECTOR_POSITION = (spots.c1[0], spots.c1[1] + 100)
blicketd_image_path = (kstimulus("shapes/triangle_yellow.png"))
BLICKET_DETECTOR_POSITION_2 = (spots.c2[0], spots.c2[1] + 100)
blicketd_image_path_2 = (kstimulus("shapes/star_pink.png"))
BLICKET_DETECTOR_POSITION_3 = (spots.c3[0], spots.c3[0], 100)
blicketd_image_path_3 = (kstimulus("shapes/circle_red.png"))
pygame.display.flip() # tells game to refresh the display,
# all code involving the display of things must go ABOVE this line
event = pygame.event.poll() # ask game to examine all things happening in the game now
# code that responds to keyboard of mouse events goes after pool line
# need to pool all current events before dealing wtih them
def present_trial(imagepath):
thing = DragSprite(screen, spots.cu, imagepath, scale=IMAGE_SCALE)
<|code_end|>
. Use current file imports:
(import os, sys
import pygame
import glob
import numpy
from random import randint, choice, sample, shuffle
from time import time,sleep
from kelpy.GIFImage import *
from kelpy.CommandableImageSprite import *
from kelpy.Miscellaneous import *
from kelpy.DisplayQueue import *
from kelpy.OrderedUpdates import *
from kelpy.EventHandler import *
from kelpy.DragDrop import DragSprite, DropSprite
from kelpy.DragDrop import *
from kelpy.tobii.TobiiSimController import *
from kelpy.tobii.TobiiSprite import *)
and context including class names, function names, or small code snippets from other files:
# Path: kelpy/DragDrop.py
# class DragSprite(CommandableImageSprite, Dragable):
# """
# The DragSprite is used to create a dragable sprite. It is written so that you feed it similar parameters that you would feed a regualar CommandableImageSprite.
# The only difference is that this sprite is able to be dragged around, once the drag and drop function is run in the main event loop (object.process_dragndrop(event))
# """
# def __init__(self, canvas, initial_position, imgpath, rotation=0, scale=.20):
# CommandableImageSprite.__init__(self, canvas, initial_position, imgpath, rotation, scale)
# Dragable.__init__(self)
# self.set_x(initial_position[0])
# self.set_y(initial_position[1])
# self.set_height(self.display_image.get_height())
# self.set_width(self.display_image.get_width())
#
# class DropSprite(CommandableImageSprite, Arrangeable):
# """
# The DropSprite class is used to create a sprite with a drop zone on top of it. You then register the drop zone via the DragSprite.register_drop_zone(DropSprite) line.
#
# """
# def __init__(self, canvas, initial_position, imgpath, rotation=0, scale=.20):
# CommandableImageSprite.__init__(self, canvas, initial_position, imgpath, rotation, scale)
# Arrangeable.__init__(self)
# self.set_x(initial_position[0])
# self.set_y(initial_position[1])
# self.set_height(self.display_image.get_height())
# self.set_width(self.display_image.get_width())
. Output only the next line. | blicket_detector = DropSprite(screen, BLICKET_DETECTOR_POSITION, blicketd_image_path, scale=.3) |
Based on the snippet: <|code_start|>
python runkelpy.py <yourscriptname>.py <<< exactly like this. removing the < > and replacing yourscriptname with your script name (of course).
"""
run_script = None
print "Attempting to run your kelpy script!"
if len(sys.argv)==1:
##You didn't input the filename!
print "ERROR: no filename passed as an argument."
print " please input the filename of the script you wish to run."
print " example syntax: python runkelpy.py <yourscriptname>.py "
sys.exit()
else:
print "Checking for your kelpy script's name..."
for i in range(len(sys.argv)):
## Check the arguments. right now we only handle one, the filename, but this could be improved later to handle more stuff.
##print argv[i] , i
if argv[i].rsplit('.', 1)[1]=='py' and argv[i].rsplit('.', 1)[0] !="runkelpy":
run_script = argv[i]
print "Found " + run_script
##print run_script
if run_script is not None:
print "Attemting to run " + run_script
os.system("python " + run_script)
print "Run (should have) finished. Proceeding to render video."
<|code_end|>
, predict the immediate next line with the help of imports:
import sys,os
import datetime
from sys import *
from kelpy.ScreenVideoRecorder import lastdir
and context (classes, functions, sometimes code) from other files:
# Path: kelpy/ScreenVideoRecorder.py
# def lastdir():
# """The latest timestamp-based directory"""
# dirs = [d for d in os.listdir(".") if d.startswith("vidcap-")]
# return max(dirs) if dirs else None
. Output only the next line. | video_directory = lastdir() |
Continue the code snippet: <|code_start|>
# Additional TFDS metadata
VERSION = tfds.core.Version('1.0.0')
RELEASE_NOTES = {
'1.0.0': 'Initial version',
}
CONFIGS = [
tfds.core.BuilderConfig(name=scene_name) for scene_name in SCENE_NAMES
]
DATASET_INFO_KWARGS = dict(
description="""Nerf synthetic dataset.""",
homepage='https://github.com/bmild/nerf',
citation="""
@inproceedings{mildenhall2020nerf,
title={NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis},
author={Mildenhall, Ben and Srinivasan, Pratul P and Tancik, Matthew and Barron, Jonathan T and Ramamoorthi, Ravi and Ng, Ren},
booktitle={European Conference on Computer Vision},
pages={405--421},
year={2020},
organization={Springer}
}
""",
)
DL_URL = 'https://drive.google.com/uc?id=18JxhpWD-4ZmuFKLzKlAw-w5PpzZxXOcG&export=download'
IMG_SHAPE = (800, 800)
CAMERA_NAME = 'default_camera'
<|code_end|>
. Use current file imports:
from typing import Optional
from sunds.typing import Json
import numpy as np
import sunds
import tensorflow_datasets as tfds
and context (classes, functions, or code) from other files:
# Path: sunds/typing.py
. Output only the next line. | def camera_intrinsics(scene_data: Json) -> sunds.specs_utils.CameraIntrinsics: |
Here is a snippet: <|code_start|>
class DatasetBuilder:
"""Wrapper around `tfds.core.DatasetBuilder`."""
def __init__(
self,
*,
scene_builder: LazyBuilder,
frame_builder: LazyBuilder,
):
"""Constructor.
Args:
scene_builder: Dataset builder containing the scenes.
frame_builder: Dataset builder containing the frames.
"""
self._scene_builder = scene_builder
self._frame_builder = frame_builder
self._validate()
def download_and_prepare(self, **kwargs):
"""Download and prepare the dataset."""
# Is a no-op if the dataset has already been generated
self.scene_builder.download_and_prepare(**kwargs)
self.frame_builder.download_and_prepare(**kwargs)
def as_dataset(
self,
*,
split: Tree[Split],
<|code_end|>
. Write the next line using the current file imports:
import typing
import tensorflow as tf
import tensorflow_datasets as tfds
import sunds # pylint: disable=g-import-not-at-top
from typing import Callable, Optional, Union
from etils import epath
from sunds.core import tasks as tasks_lib
from sunds.typing import Split, Tree # pylint: disable=g-multiple-import
and context from other files:
# Path: sunds/core/tasks.py
# class Task(abc.ABC):
# class FrameTask(Task):
# def initialize(
# self,
# *,
# scene_builder: tfds.core.DatasetBuilder,
# frame_builder: tfds.core.DatasetBuilder,
# ) -> 'Task':
# def as_dataset(self, **kwargs) -> tf.data.Dataset:
# def full_scene_specs(self) -> tfds.features.FeaturesDict:
# def full_frame_specs(self) -> tfds.features.FeaturesDict:
# def as_dataset(
# self,
# *,
# split: Tree[Split],
# decoders: Optional[TreeDict[tfds.decode.Decoder]] = None,
# pipeline_kwargs: Optional[Dict[str, Any]] = None,
# **kwargs,
# ) -> tf.data.Dataset:
# def frame_specs(self) -> Optional[FeatureSpecsHint]:
# def pipeline(self, ds: tf.data.Dataset) -> tf.data.Dataset:
#
# Path: sunds/typing.py
, which may include functions, classes, or code. Output only the next line. | task: Optional[tasks_lib.Task] = None, |
Continue the code snippet: <|code_start|>
class DatasetBuilder:
"""Wrapper around `tfds.core.DatasetBuilder`."""
def __init__(
self,
*,
scene_builder: LazyBuilder,
frame_builder: LazyBuilder,
):
"""Constructor.
Args:
scene_builder: Dataset builder containing the scenes.
frame_builder: Dataset builder containing the frames.
"""
self._scene_builder = scene_builder
self._frame_builder = frame_builder
self._validate()
def download_and_prepare(self, **kwargs):
"""Download and prepare the dataset."""
# Is a no-op if the dataset has already been generated
self.scene_builder.download_and_prepare(**kwargs)
self.frame_builder.download_and_prepare(**kwargs)
def as_dataset(
self,
*,
<|code_end|>
. Use current file imports:
import typing
import tensorflow as tf
import tensorflow_datasets as tfds
import sunds # pylint: disable=g-import-not-at-top
from typing import Callable, Optional, Union
from etils import epath
from sunds.core import tasks as tasks_lib
from sunds.typing import Split, Tree # pylint: disable=g-multiple-import
and context (classes, functions, or code) from other files:
# Path: sunds/core/tasks.py
# class Task(abc.ABC):
# class FrameTask(Task):
# def initialize(
# self,
# *,
# scene_builder: tfds.core.DatasetBuilder,
# frame_builder: tfds.core.DatasetBuilder,
# ) -> 'Task':
# def as_dataset(self, **kwargs) -> tf.data.Dataset:
# def full_scene_specs(self) -> tfds.features.FeaturesDict:
# def full_frame_specs(self) -> tfds.features.FeaturesDict:
# def as_dataset(
# self,
# *,
# split: Tree[Split],
# decoders: Optional[TreeDict[tfds.decode.Decoder]] = None,
# pipeline_kwargs: Optional[Dict[str, Any]] = None,
# **kwargs,
# ) -> tf.data.Dataset:
# def frame_specs(self) -> Optional[FeatureSpecsHint]:
# def pipeline(self, ds: tf.data.Dataset) -> tf.data.Dataset:
#
# Path: sunds/typing.py
. Output only the next line. | split: Tree[Split], |
Given the following code snippet before the placeholder: <|code_start|>
class DatasetBuilder:
"""Wrapper around `tfds.core.DatasetBuilder`."""
def __init__(
self,
*,
scene_builder: LazyBuilder,
frame_builder: LazyBuilder,
):
"""Constructor.
Args:
scene_builder: Dataset builder containing the scenes.
frame_builder: Dataset builder containing the frames.
"""
self._scene_builder = scene_builder
self._frame_builder = frame_builder
self._validate()
def download_and_prepare(self, **kwargs):
"""Download and prepare the dataset."""
# Is a no-op if the dataset has already been generated
self.scene_builder.download_and_prepare(**kwargs)
self.frame_builder.download_and_prepare(**kwargs)
def as_dataset(
self,
*,
<|code_end|>
, predict the next line using imports from the current file:
import typing
import tensorflow as tf
import tensorflow_datasets as tfds
import sunds # pylint: disable=g-import-not-at-top
from typing import Callable, Optional, Union
from etils import epath
from sunds.core import tasks as tasks_lib
from sunds.typing import Split, Tree # pylint: disable=g-multiple-import
and context including class names, function names, and sometimes code from other files:
# Path: sunds/core/tasks.py
# class Task(abc.ABC):
# class FrameTask(Task):
# def initialize(
# self,
# *,
# scene_builder: tfds.core.DatasetBuilder,
# frame_builder: tfds.core.DatasetBuilder,
# ) -> 'Task':
# def as_dataset(self, **kwargs) -> tf.data.Dataset:
# def full_scene_specs(self) -> tfds.features.FeaturesDict:
# def full_frame_specs(self) -> tfds.features.FeaturesDict:
# def as_dataset(
# self,
# *,
# split: Tree[Split],
# decoders: Optional[TreeDict[tfds.decode.Decoder]] = None,
# pipeline_kwargs: Optional[Dict[str, Any]] = None,
# **kwargs,
# ) -> tf.data.Dataset:
# def frame_specs(self) -> Optional[FeatureSpecsHint]:
# def pipeline(self, ds: tf.data.Dataset) -> tf.data.Dataset:
#
# Path: sunds/typing.py
. Output only the next line. | split: Tree[Split], |
Next line prediction: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for normal."""
def _get_encoded_img(image_array: np.ndarray) -> bytes:
if image_array.ndim == 2: # Expand 2d array
image_array = image_array[..., None]
return tf.image.encode_png(image_array).numpy()
class ImageFeaturesTest(tfds.testing.FeatureExpectationsTestCase):
def testNormalImage(self):
img = np.random.rand(24, 24, 3).astype(np.float32)
img_discrete = ((img + 1.0) * 32767.5).astype(np.uint16)
img2 = np.array([
[[1., 0., 0.]],
[[1e-6, 0.4, -1.]],
[[0.9999999999999999999999999999, 0.4, -1.]],
])
atol = 1e-04
self.assertFeatureEagerOnly(
<|code_end|>
. Use current file imports:
(import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from sunds.features import normal)
and context including class names, function names, or small code snippets from other files:
# Path: sunds/features/normal.py
# class NormalImage(tfds.features.Image):
# def __init__(
# self,
# shape: Tuple[tfds.typing.Dim, tfds.typing.Dim] = (None, None),
# ):
# def get_tensor_info(self) -> tfds.features.TensorInfo:
# def encode_example(self, normal_np: np.ndarray) -> bytes:
# def decode_example(self, example: tf.Tensor) -> tf.Tensor:
# def from_json_content(cls, value: tfds.typing.Json) -> 'NormalImage':
# def to_json_content(self) -> tfds.typing.Json:
# def repr_html(self, ex: np.ndarray) -> str:
. Output only the next line. | feature=normal.NormalImage(), |
Predict the next line after this snippet: <|code_start|># Copyright 2022 The sunds Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for isun.geometry.rays."""
def simple_pinhole_camera():
image_width, image_height = 320, 240
fx, fy, cx, cy = 400.0, 400.0, image_width / 2, image_height / 2
<|code_end|>
using the current file's imports:
from absl.testing import parameterized
from sunds.core.tf_geometry import cameras
from sunds.core.tf_geometry import isometry
from sunds.core.tf_geometry import rays
import numpy as np
import tensorflow as tf
and any relevant context from other files:
# Path: sunds/core/tf_geometry/cameras.py
# class AbstractCamera(abc.ABC):
# class PinholeCamera(AbstractCamera):
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# def __post_init__(self):
# def from_fov(
# cls,
# *,
# image_width: int,
# image_height: int,
# horizontal_fov_in_degrees: float,
# vertical_fov_in_degrees: Optional[float] = None) -> 'PinholeCamera':
# def focal_length_from_fov(image_size, fov_in_degrees):
# def from_intrinsics(
# cls,
# *,
# image_size_in_pixels: Tuple[int, int],
# focal_length_in_pixels: Tuple[float, float],
# principal_point_in_pixels: Optional[Tuple[float, float]] = None,
# skew: float = 0.0,
# ) -> 'PinholeCamera':
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# K: TensorLike # pylint: disable=invalid-name
#
# Path: sunds/core/tf_geometry/isometry.py
# class Isometry:
# R: TensorLike # pylint: disable=invalid-name
# def __post_init__(self):
# def from_matrix(cls, matrix: TensorLike) -> 'Isometry':
# def matrix3x4(self) -> tf.Tensor:
# def matrix4x4(self) -> tf.Tensor:
# def inverse(self) -> 'Isometry':
# def compose(self, other: 'Isometry') -> 'Isometry':
# def transform_points(self, points: TensorLike) -> tf.Tensor:
# def __mul__(
# self, other: Union['Isometry',
# TensorLike]) -> Union['Isometry', tf.Tensor]:
#
# Path: sunds/core/tf_geometry/rays.py
# def rays_from_image_points(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry,
# points_image: TensorLike):
# def rays_from_image_grid(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry):
# def _rays_from_directions(ray_directions: TensorLike,
# world_from_camera: isometry.Isometry):
# def depth_samples_along_rays(near_depth: TensorLike,
# far_depth: TensorLike,
# num_samples_per_ray: int,
# method: str = 'linspace_depth') -> tf.Tensor:
# def jitter_depth_samples_along_rays(point_depths: TensorLike) -> tf.Tensor:
# def point_samples_along_rays(ray_origins: TensorLike,
# ray_directions: TensorLike,
# point_depths: TensorLike) -> tf.Tensor:
. Output only the next line. | return cameras.PinholeCamera( |
Predict the next line for this snippet: <|code_start|># Copyright 2022 The sunds Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for isun.geometry.rays."""
def simple_pinhole_camera():
image_width, image_height = 320, 240
fx, fy, cx, cy = 400.0, 400.0, image_width / 2, image_height / 2
return cameras.PinholeCamera(
K=[[fx, 0., cx], [0., fy, cy], [0., 0., 1.]],
image_width=image_width,
image_height=image_height)
def random_pose():
"""Use QR decomposition of random (normal) matrix to get random rotation."""
random_rotation, _ = tf.linalg.qr(tf.random.normal(shape=[3, 3]))
<|code_end|>
with the help of current file imports:
from absl.testing import parameterized
from sunds.core.tf_geometry import cameras
from sunds.core.tf_geometry import isometry
from sunds.core.tf_geometry import rays
import numpy as np
import tensorflow as tf
and context from other files:
# Path: sunds/core/tf_geometry/cameras.py
# class AbstractCamera(abc.ABC):
# class PinholeCamera(AbstractCamera):
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# def __post_init__(self):
# def from_fov(
# cls,
# *,
# image_width: int,
# image_height: int,
# horizontal_fov_in_degrees: float,
# vertical_fov_in_degrees: Optional[float] = None) -> 'PinholeCamera':
# def focal_length_from_fov(image_size, fov_in_degrees):
# def from_intrinsics(
# cls,
# *,
# image_size_in_pixels: Tuple[int, int],
# focal_length_in_pixels: Tuple[float, float],
# principal_point_in_pixels: Optional[Tuple[float, float]] = None,
# skew: float = 0.0,
# ) -> 'PinholeCamera':
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# K: TensorLike # pylint: disable=invalid-name
#
# Path: sunds/core/tf_geometry/isometry.py
# class Isometry:
# R: TensorLike # pylint: disable=invalid-name
# def __post_init__(self):
# def from_matrix(cls, matrix: TensorLike) -> 'Isometry':
# def matrix3x4(self) -> tf.Tensor:
# def matrix4x4(self) -> tf.Tensor:
# def inverse(self) -> 'Isometry':
# def compose(self, other: 'Isometry') -> 'Isometry':
# def transform_points(self, points: TensorLike) -> tf.Tensor:
# def __mul__(
# self, other: Union['Isometry',
# TensorLike]) -> Union['Isometry', tf.Tensor]:
#
# Path: sunds/core/tf_geometry/rays.py
# def rays_from_image_points(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry,
# points_image: TensorLike):
# def rays_from_image_grid(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry):
# def _rays_from_directions(ray_directions: TensorLike,
# world_from_camera: isometry.Isometry):
# def depth_samples_along_rays(near_depth: TensorLike,
# far_depth: TensorLike,
# num_samples_per_ray: int,
# method: str = 'linspace_depth') -> tf.Tensor:
# def jitter_depth_samples_along_rays(point_depths: TensorLike) -> tf.Tensor:
# def point_samples_along_rays(ray_origins: TensorLike,
# ray_directions: TensorLike,
# point_depths: TensorLike) -> tf.Tensor:
, which may contain function names, class names, or code. Output only the next line. | return isometry.Isometry(R=random_rotation, t=tf.random.uniform(shape=[3])) |
Based on the snippet: <|code_start|> """Use QR decomposition of random (normal) matrix to get random rotation."""
random_rotation, _ = tf.linalg.qr(tf.random.normal(shape=[3, 3]))
return isometry.Isometry(R=random_rotation, t=tf.random.uniform(shape=[3]))
def pinhole_camera_with_random_pose():
return {
'testcase_name': 'pinhole_camera_with_random_pose',
'camera': simple_pinhole_camera(),
'world_from_camera': random_pose(),
}
def pinhole_camera_with_non_square_pixels():
camera = cameras.PinholeCamera.from_intrinsics(
image_size_in_pixels=(1024, 768), focal_length_in_pixels=(500.0, 600.0))
world_from_camera = isometry.Isometry(R=tf.eye(3), t=tf.ones(3))
return {
'testcase_name': 'pinhole_camera_with_non_square_pixels',
'camera': camera,
'world_from_camera': world_from_camera,
}
class RaysFromImageGridTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.named_parameters(pinhole_camera_with_random_pose(),
pinhole_camera_with_non_square_pixels())
def test_rays_shape(self, camera, world_from_camera):
"""Test that the output tensor shapes are correct."""
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import parameterized
from sunds.core.tf_geometry import cameras
from sunds.core.tf_geometry import isometry
from sunds.core.tf_geometry import rays
import numpy as np
import tensorflow as tf
and context (classes, functions, sometimes code) from other files:
# Path: sunds/core/tf_geometry/cameras.py
# class AbstractCamera(abc.ABC):
# class PinholeCamera(AbstractCamera):
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# def __post_init__(self):
# def from_fov(
# cls,
# *,
# image_width: int,
# image_height: int,
# horizontal_fov_in_degrees: float,
# vertical_fov_in_degrees: Optional[float] = None) -> 'PinholeCamera':
# def focal_length_from_fov(image_size, fov_in_degrees):
# def from_intrinsics(
# cls,
# *,
# image_size_in_pixels: Tuple[int, int],
# focal_length_in_pixels: Tuple[float, float],
# principal_point_in_pixels: Optional[Tuple[float, float]] = None,
# skew: float = 0.0,
# ) -> 'PinholeCamera':
# def project(self, points: TensorLike) -> tf.Tensor:
# def unproject(self,
# points: Optional[TensorLike] = None,
# to_rays: bool = True) -> tf.Tensor:
# def pixel_centers(self) -> tf.Tensor:
# K: TensorLike # pylint: disable=invalid-name
#
# Path: sunds/core/tf_geometry/isometry.py
# class Isometry:
# R: TensorLike # pylint: disable=invalid-name
# def __post_init__(self):
# def from_matrix(cls, matrix: TensorLike) -> 'Isometry':
# def matrix3x4(self) -> tf.Tensor:
# def matrix4x4(self) -> tf.Tensor:
# def inverse(self) -> 'Isometry':
# def compose(self, other: 'Isometry') -> 'Isometry':
# def transform_points(self, points: TensorLike) -> tf.Tensor:
# def __mul__(
# self, other: Union['Isometry',
# TensorLike]) -> Union['Isometry', tf.Tensor]:
#
# Path: sunds/core/tf_geometry/rays.py
# def rays_from_image_points(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry,
# points_image: TensorLike):
# def rays_from_image_grid(camera: cameras.CameraType,
# world_from_camera: isometry.Isometry):
# def _rays_from_directions(ray_directions: TensorLike,
# world_from_camera: isometry.Isometry):
# def depth_samples_along_rays(near_depth: TensorLike,
# far_depth: TensorLike,
# num_samples_per_ray: int,
# method: str = 'linspace_depth') -> tf.Tensor:
# def jitter_depth_samples_along_rays(point_depths: TensorLike) -> tf.Tensor:
# def point_samples_along_rays(ray_origins: TensorLike,
# ray_directions: TensorLike,
# point_depths: TensorLike) -> tf.Tensor:
. Output only the next line. | ray_origins, ray_directions = rays.rays_from_image_grid( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.