<commit_before>import logging
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http.response import HttpResponse, HttpResponseForbidden
from django.template import Context
from django.template.loader import get_template
from django.utils.translation import ugettext as _
from yapi.authentication import ApiKeyAuthentication, SessionAuthentication
from yapi.decorators import authentication_classes, permission_classes
from yapi.permissions import IsStaff
from yapi.resource import Resource
from yapi.response import HTTPStatus, Response
from yutils.email import EmailMessage

from serializers import PlaceSerializer, PhotoSerializer, ReviewSerializer
from yplaces.forms import PlaceForm, PhotoForm, ReviewForm
from yplaces.models import Place, Photo, Review

# Instantiate logger.
logger = logging.getLogger(__name__)


class PlacesHandler(Resource):
    """
    API endpoint handler.
    """
    # HTTP methods allowed.
    allowed_methods = ['POST', 'GET']
    
    @authentication_classes([SessionAuthentication, ApiKeyAuthentication])
    def post(self, request):
        """
        Process POST request.
        """
        # Add additional required info regarding the user that created this Place.
        request.data['created_by'] = request.auth['user'].pk
        
        # Populate form with provided data.
        form = PlaceForm(request.data)
        
        # Create new instance.
        try:
            new_instance = form.save()
            
            # If Place was added by a 'regular' user, notify admin that it is pending aproval.
            if not request.auth['user'].is_staff:
                try:
                    # Email variables.
                    d = Context({ 'place': new_instance, 'host_url': settings.HOST_URL })
                    
                    # Render plaintext email template.
                    plaintext = get_template('yplaces/email/place_added.txt')
                    text_content = plaintext.render(d)
                    
                    # Render HTML email template.
                    html = get_template('yplaces/email/place_added.html')
                    html_content = html.render(d)
                    
                    # Email options.
                    subject = _('Place Added')
                    from_email = settings.YPLACES['email_from']
                    to = settings.YPLACES['admin_emails']
                    
                    # Build message and send.
                    email = EmailMessage(sender=from_email,
                                        recipients=to,
                                        subject=subject,
                                        text_content=text_content,
                                        html_content=html_content,
                                        tags=['Place Added'])
                    result = email.send()
                    
                    # Check if email wasn't sent.
                    if not result['sent']:
                        logger.warning('Email Not Sent! Result: ' + str(result['result']))
                        raise
                except:
                    logger.warning('Unable to send email', exc_info=1)
            
            # Return.
            return Response(request=request,
                            data=new_instance,
                            serializer=PlaceSerializer,
                            status=HTTPStatus.SUCCESS_201_CREATED)
            
        # Form didn't validate!
        except ValueError:
            return Response(request=request,
                            data={ 'message': 'Invalid parameters', 'parameters': form.errors },
                            serializer=None,
                            status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
    
    def get(self, request):
        """
        Process GET request.
        """
        # Lets start with all.
        results = Place.objects.all()
        
        #
        # Filters
        #
        filters = {}
        
        # **************** IMPORTANT ***************
        # Only show full listing (i.e. inactive places) to staff users.
        # ******************************************
        if not request.user or not request.user.is_staff:
            results = results.filter(active=True)
        # If staff, can filter by active status.
        elif request.user and request.user.is_staff:
            try:
                active = request.GET['active']
                if active != '':
                    ['true', 'false'].index(active)
                    active = (active.lower() == 'true')
                    results = results.filter(active=active)
                    filters['active'] = active
            except KeyError:
                pass
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'active': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
        
        ###
        # Optionally, pagination can be disabled and results returned in single response.
        try:
            pagination = request.GET['pagination']
            ['true', 'false'].index(pagination)
            pagination = (pagination.lower() == 'true')
        except KeyError:
            pagination = True
        except ValueError:
            return Response(request=request,
                            data={ 'message': 'Invalid parameters', 'parameters': { 'pagination': ['Invalid value'] } },
                            serializer=None,
                            status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
        
        ###
        # Radius search.
        latLng = request.GET.get('latLng', None)
        
        # If coordinates are provided...
        if latLng:
            
            # Validate latitude/longitude pair.
            try:
                latLng = [float(i) for i in latLng.split(',')]
                if len(latLng) != 2:
                    raise ValueError
                latLng = (latLng[0], latLng[1])
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'latLng': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
            
            # If no radius is provided, default to 0.5
            radius = request.GET.get('radius', 0.5)
            
            # Validate radius.
            try:
                radius = float(radius)
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'radius': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
                
            # Filter results by radius search.
            filters['latLng'] = request.GET.get('latLng', None)
            filters['radius'] = radius
            results = Place.search_radius(latLng=latLng, radius=radius, querySet=results)

        ###
        # Name.
        try:
            name = request.GET['name']
            if name != '':
                results = results.filter(Q(name__icontains=name))
                filters['name'] = name
        except KeyError:
            pass
        
        ###
        # Location.
        try:
            location = request.GET['location']
            results = results.filter(Q(address__icontains=location) | Q(city__icontains=location) | Q(state__icontains=location) | Q(country__icontains=location))
        except KeyError:
            location = ''
        
        #
        # Return.
        #
        return Response(request=request,
                        data=results,
                        filters=filters,
                        serializer=PlaceSerializer,
                        pagination=pagination,
                        status=HTTPStatus.SUCCESS_200_OK)
        
        
class PlaceIdHandler(Resource):
    """
    API endpoint handler.
    """<commit_msg>Location is now returned in filters list when it is used.<commit_after>import logging
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http.response import HttpResponse, HttpResponseForbidden
from django.template import Context
from django.template.loader import get_template
from django.utils.translation import ugettext as _
from yapi.authentication import ApiKeyAuthentication, SessionAuthentication
from yapi.decorators import authentication_classes, permission_classes
from yapi.permissions import IsStaff
from yapi.resource import Resource
from yapi.response import HTTPStatus, Response
from yutils.email import EmailMessage

from serializers import PlaceSerializer, PhotoSerializer, ReviewSerializer
from yplaces.forms import PlaceForm, PhotoForm, ReviewForm
from yplaces.models import Place, Photo, Review

# Instantiate logger.
logger = logging.getLogger(__name__)


class PlacesHandler(Resource):
    """
    API endpoint handler.
    """
    # HTTP methods allowed.
    allowed_methods = ['POST', 'GET']
    
    @authentication_classes([SessionAuthentication, ApiKeyAuthentication])
    def post(self, request):
        """
        Process POST request.
        """
        # Add additional required info regarding the user that created this Place.
        request.data['created_by'] = request.auth['user'].pk
        
        # Populate form with provided data.
        form = PlaceForm(request.data)
        
        # Create new instance.
        try:
            new_instance = form.save()
            
            # If Place was added by a 'regular' user, notify admin that it is pending aproval.
            if not request.auth['user'].is_staff:
                try:
                    # Email variables.
                    d = Context({ 'place': new_instance, 'host_url': settings.HOST_URL })
                    
                    # Render plaintext email template.
                    plaintext = get_template('yplaces/email/place_added.txt')
                    text_content = plaintext.render(d)
                    
                    # Render HTML email template.
                    html = get_template('yplaces/email/place_added.html')
                    html_content = html.render(d)
                    
                    # Email options.
                    subject = _('Place Added')
                    from_email = settings.YPLACES['email_from']
                    to = settings.YPLACES['admin_emails']
                    
                    # Build message and send.
                    email = EmailMessage(sender=from_email,
                                        recipients=to,
                                        subject=subject,
                                        text_content=text_content,
                                        html_content=html_content,
                                        tags=['Place Added'])
                    result = email.send()
                    
                    # Check if email wasn't sent.
                    if not result['sent']:
                        logger.warning('Email Not Sent! Result: ' + str(result['result']))
                        raise
                except:
                    logger.warning('Unable to send email', exc_info=1)
            
            # Return.
            return Response(request=request,
                            data=new_instance,
                            serializer=PlaceSerializer,
                            status=HTTPStatus.SUCCESS_201_CREATED)
            
        # Form didn't validate!
        except ValueError:
            return Response(request=request,
                            data={ 'message': 'Invalid parameters', 'parameters': form.errors },
                            serializer=None,
                            status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
    
    def get(self, request):
        """
        Process GET request.
        """
        # Lets start with all.
        results = Place.objects.all()
        
        #
        # Filters
        #
        filters = {}
        
        # **************** IMPORTANT ***************
        # Only show full listing (i.e. inactive places) to staff users.
        # ******************************************
        if not request.user or not request.user.is_staff:
            results = results.filter(active=True)
        # If staff, can filter by active status.
        elif request.user and request.user.is_staff:
            try:
                active = request.GET['active']
                if active != '':
                    ['true', 'false'].index(active)
                    active = (active.lower() == 'true')
                    results = results.filter(active=active)
                    filters['active'] = active
            except KeyError:
                pass
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'active': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
        
        ###
        # Optionally, pagination can be disabled and results returned in single response.
        try:
            pagination = request.GET['pagination']
            ['true', 'false'].index(pagination)
            pagination = (pagination.lower() == 'true')
        except KeyError:
            pagination = True
        except ValueError:
            return Response(request=request,
                            data={ 'message': 'Invalid parameters', 'parameters': { 'pagination': ['Invalid value'] } },
                            serializer=None,
                            status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
        
        ###
        # Radius search.
        latLng = request.GET.get('latLng', None)
        
        # If coordinates are provided...
        if latLng:
            
            # Validate latitude/longitude pair.
            try:
                latLng = [float(i) for i in latLng.split(',')]
                if len(latLng) != 2:
                    raise ValueError
                latLng = (latLng[0], latLng[1])
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'latLng': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
            
            # If no radius is provided, default to 0.5
            radius = request.GET.get('radius', 0.5)
            
            # Validate radius.
            try:
                radius = float(radius)
            except ValueError:
                return Response(request=request,
                                data={ 'message': 'Invalid parameters', 'parameters': { 'radius': ['Invalid value'] } },
                                serializer=None,
                                status=HTTPStatus.CLIENT_ERROR_400_BAD_REQUEST)
                
            # Filter results by radius search.
            filters['latLng'] = request.GET.get('latLng', None)
            filters['radius'] = radius
            results = Place.search_radius(latLng=latLng, radius=radius, querySet=results)

        ###
        # Name.
        try:
            name = request.GET['name']
            if name != '':
                results = results.filter(Q(name__icontains=name))
                filters['name'] = name
        except KeyError:
            pass
        
        ###
        # Location.
        try:
            location = request.GET['location']
            if location != '':
                results = results.filter(Q(address__icontains=location) | Q(city__icontains=location) | Q(state__icontains=location) | Q(country__icontains=location))
                filters['location'] = location
        except KeyError:
            pass
        
        #
        # Return.
        #
        return Response(request=request,
                        data=results,
                        filters=filters,
                        serializer=PlaceSerializer,
                        pagination=pagination,
                        status=HTTPStatus.SUCCESS_200_OK)
        
        
class PlaceIdHandler(Resource):
    """
    API endpoint handler.
    """
{'fraction_non_alphanumeric': 0.09263756441390748, 'fraction_numerical': 0.0034354083989812235, 'mean_word_length': 1.4437689969604863, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5075261', 'n_tokens_mistral': 3960, 'n_tokens_neox': 3807, 'n_words': 954}