Python django.http() Examples

The following are 30 code examples of django.http(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django , or try the search function .
Example #1
Source File: views.py    From OpenBench with GNU General Public License v3.0 6 votes vote down vote up
def login(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  GET  : Return the HTML template used for logging in a User             #
    #                                                                         #
    #  POST : Attempt to login the User and authenticate their credentials.   #
    #         If their login is invalid, let them know. In all cases, return  #
    #         the User back to the main page                                  #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    if request.method == 'GET':
        return render(request, 'login.html')

    user = django.contrib.auth.authenticate(
        username=request.POST['username'],
        password=request.POST['password'])

    if user is None:
        return index(request, error='Unable to Authenticate User')

    django.contrib.auth.login(request, user)
    return django.http.HttpResponseRedirect('/index/') 
Example #2
Source File: test_admin_delete_record.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def test_post(self):
        """Tests POST requests to delete a record."""
        get_doc = self.to_doc(self.client.get(
            '/global/admin/delete_record/', secure=True))
        xsrf_token = get_doc.cssselect_one('input[name="xsrf_token"]').get(
            'value')
        post_resp = self.client.post('/haiti/admin/delete_record/', {
            'xsrf_token': xsrf_token,
            'id': self.person.record_id,
        }, secure=True)
        # Check that the user's redirected to the repo's main admin page.
        self.assertIsInstance(post_resp, django.http.HttpResponseRedirect)
        parse = urlparse.urlparse(post_resp.url)
        self.assertEqual('/haiti/delete', parse.path)
        query_params = dict(urlparse.parse_qsl(parse.query))
        self.assertEqual(query_params['id'], self.person.record_id)
        # Check that the signature param is present and not the empty string.
        self.assertTrue(len(query_params['signature']) > 1) 
Example #3
Source File: test_admin_review.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def test_flag_note(self):
        """Tests POST requests to flag a note."""
        note = self.data_generator.note(person_id=self.person.record_id)
        get_doc = self.to_doc(self.client.get(
            '/haiti/admin/review/', secure=True))
        xsrf_token = get_doc.cssselect_one('input[name="xsrf_token"]').get(
            'value')
        post_resp = self.client.post('/haiti/admin/review/', {
            'note.%s' % note.record_id: 'flag',
            'xsrf_token': xsrf_token,
        }, secure=True)
        # Check that the user's redirected to the repo's main admin page.
        self.assertIsInstance(post_resp, django.http.HttpResponseRedirect)
        self.assertEqual(post_resp.url, '/haiti/admin/review/')
        # Reload the Note from Datastore.
        note = model.Note.get('haiti', note.record_id)
        self.assertIs(note.reviewed, True)
        self.assertIs(note.hidden, True) 
Example #4
Source File: test_admin_review.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def test_accept_note(self):
        """Tests POST requests to accept a note."""
        note = self.data_generator.note(person_id=self.person.record_id)
        get_doc = self.to_doc(self.client.get(
            '/haiti/admin/review/', secure=True))
        xsrf_token = get_doc.cssselect_one('input[name="xsrf_token"]').get(
            'value')
        post_resp = self.client.post('/haiti/admin/review/', {
            'note.%s' % note.record_id: 'accept',
            'xsrf_token': xsrf_token,
        }, secure=True)
        # Check that the user's redirected to the repo's main admin page.
        self.assertIsInstance(post_resp, django.http.HttpResponseRedirect)
        self.assertEqual(post_resp.url, '/haiti/admin/review/')
        # Reload the Note from Datastore.
        note = model.Note.get('haiti', note.record_id)
        self.assertIs(note.reviewed, True)
        self.assertIs(note.hidden, False) 
Example #5
Source File: deletion.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        del request, args, kwargs  # unused
        q = self.get_query()
        cursor = self.params.get('cursor', '')
        if cursor:
            q.with_cursor(cursor)
        try:
            now = utils.get_utcnow()
            for item in q:
                next_cursor = q.cursor()
                associated_person = model.Person.get(
                    self.env.repo, self.get_person_record_id(item))
                if not associated_person:
                    if now - self.get_base_timestamp(item) > _STRAY_CLEANUP_TTL:
                        db.delete(item)
                cursor = next_cursor
        except runtime.DeadlineExceededError:
            self.schedule_task(self.env.repo, cursor=cursor)
        except datastore_errors.Timeout:
            self.schedule_task(self.env.repo, cursor=cursor)
        return django.http.HttpResponse('') 
Example #6
Source File: base.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        """See docs on django.views.View.dispatch."""
        # If the X-AppEngine-TaskQueue header is set, it means the request came
        # from App Engine, not an external user:
        # https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/creating-handlers#reading_request_headers
        # There are various reasons we'd prefer to prevent external users from
        # starting up tasks (e.g., because some tasks might be expensive
        # operations).
        # Django renames headers, so X-AppEngine-TaskName will be in the META
        # dictionary as HTTP_X_APPENGINE_TASKNAME:
        # https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META
        if not (request.META.get('HTTP_X_APPENGINE_TASKNAME') or
                utils.is_dev_app_server()):
            logging.warn('Non-taskqueue access of: %s' % self.request.path)
            return self.error(403)
        return super(TasksBaseView, self).dispatch(request, args, kwargs) 
Example #7
Source File: datachecks.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        query = model.Person.all(filter_expired=False).filter(
            'repo =', self.env.repo)
        cursor = self.params.cursor
        if cursor:
            query.with_cursor(cursor)
        try:
            for person in query:
                next_cursor = query.cursor()
                self._check_person(person)
                cursor = next_cursor
        except runtime.DeadlineExceededError:
            self.schedule_task(self.env.repo, cursor=cursor)
        except datastore_errors.Timeout:
            self.schedule_task(self.env.repo, cursor=cursor)
        return django.http.HttpResponse('') 
Example #8
Source File: datachecks.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        del request, args, kwargs  # unused
        query = model.Note.all(filter_expired=False).filter(
            'repo =', self.env.repo)
        cursor = self.params.cursor
        if cursor:
            query.with_cursor(cursor)
        try:
            for note in query:
                next_cursor = query.cursor()
                self._check_note(note)
                cursor = next_cursor
        except runtime.DeadlineExceededError:
            self.schedule_task(self.env.repo, cursor=cursor)
        except datastore_errors.Timeout:
            self.schedule_task(self.env.repo, cursor=cursor)
        return django.http.HttpResponse('') 
Example #9
Source File: datachecks.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        del request, args, kwargs  # unused
        query = model.Person.all(filter_expired=False).filter(
            'repo =', self.env.repo)
        cursor = self.params.cursor
        if cursor:
            query.with_cursor(cursor)
        try:
            for person in query:
                next_cursor = query.cursor()
                self._check_person(person)
                cursor = next_cursor
        except runtime.DeadlineExceededError:
            self.schedule_task(self.env.repo, cursor=cursor)
        except datastore_errors.Timeout:
            self.schedule_task(self.env.repo, cursor=cursor)
        return django.http.HttpResponse('') 
Example #10
Source File: base.py    From personfinder with Apache License 2.0 6 votes vote down vote up
def build_absolute_uri(self, path=None, repo=None, params=None):
        """Builds an absolute URI given a path.

        See build_absolute_path (above) for an explanation of why we implement
        this function ourselves.

        Args:
            path (str, optional): A path beginning with a slash (may include a
                query string), e.g., '/abc?x=y'. If the path argument is not
                specified or is None, the current request's path will be used.
            repo (str, optional): A repo ID. If specified, the path will be
                considered relative to the repo's route. If this is specified,
                path must also be specified.
            params (list, optional): A list of tuples of query param keys and
                values to add to the path.

        Returns:
            str: An absolute URI, including the sitewide OPTIONAL_PATH_PREFIX if
            it was used with the original request (e.g.,
            'http://localhost:8000/personfinder/abc?x=y'). Does not preserve
            query parameters from the original request.
        """
        return self.request.build_absolute_uri(
            self.build_absolute_path(path, repo, params)) 
Example #11
Source File: test_django_connector.py    From shadowd_python with GNU General Public License v2.0 6 votes vote down vote up
def test_defuse_input(self):
        r = django.http.HttpRequest()
        r.GET = django.http.QueryDict('foo=bar')
        r.POST = django.http.QueryDict('foo=bar')
        r.COOKIES = {'foo': 'bar'}
        r.META = {'HTTP_FOO': 'bar'}

        i = shadowd.django_connector.InputDjango(r)

        threats1 = ['GET|foo', 'POST|foo', 'COOKIE|foo', 'SERVER|HTTP_FOO']
        self.assertTrue(i.defuse_input(threats1))
        self.assertIn('foo', r.GET)
        self.assertEqual(r.GET['foo'], '')
        self.assertIn('foo', r.POST)
        self.assertEqual(r.POST['foo'], '')
        self.assertIn('foo', r.COOKIES)
        self.assertEqual(r.COOKIES['foo'], '')
        self.assertIn('HTTP_FOO', r.META)
        self.assertEqual(r.META['HTTP_FOO'], '')

        threats2 = ['FILES|foo']
        self.assertFalse(i.defuse_input(threats2)) 
Example #12
Source File: test_django_connector.py    From shadowd_python with GNU General Public License v2.0 6 votes vote down vote up
def test_get_input_array(self):
        r = django.http.HttpRequest()
        r.GET = django.http.QueryDict('foo=bar1&foo=bar2')
        r.POST = django.http.QueryDict('foo=bar1&foo=bar2')

        i = shadowd.django_connector.InputDjango(r)
        i.gather_input()

        input = i.get_input()
        self.assertIn('GET|foo|0', input)
        self.assertEqual(input['GET|foo|0'], 'bar1')
        self.assertIn('GET|foo|1', input)
        self.assertEqual(input['GET|foo|1'], 'bar2')
        self.assertIn('POST|foo|0', input)
        self.assertEqual(input['POST|foo|0'], 'bar1')
        self.assertIn('POST|foo|1', input)
        self.assertEqual(input['POST|foo|1'], 'bar2') 
Example #13
Source File: test_django_connector.py    From shadowd_python with GNU General Public License v2.0 6 votes vote down vote up
def test_get_input(self):
        r = django.http.HttpRequest()
        r.GET = django.http.QueryDict('foo=bar')
        r.POST = django.http.QueryDict('foo=bar')
        r.COOKIES = {'foo': 'bar'}
        r.META = {'HTTP_FOO': 'bar', 'foo': 'bar'}

        i = shadowd.django_connector.InputDjango(r)
        i.gather_input()

        input = i.get_input()
        self.assertIn('GET|foo', input)
        self.assertEqual(input['GET|foo'], 'bar')
        self.assertIn('POST|foo', input)
        self.assertEqual(input['POST|foo'], 'bar')
        self.assertIn('COOKIE|foo', input)
        self.assertEqual(input['COOKIE|foo'], 'bar')
        self.assertIn('SERVER|HTTP_FOO', input)
        self.assertEqual(input['SERVER|HTTP_FOO'], 'bar')
        self.assertNotIn('SERVER|foo', input) 
Example #14
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_update_notification(self, mock_reverse, mock_router):
        request = self._make_request('PUT', {'nickname': 'Fido', 'color': 'golden'})
        mock_reverse.return_value = '/dogs/1/'
        mock_router.registry = [('dogs', None, 'dummy')]

        response = self.view(request)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(request._messagings,
                         [('.dogs.changed', {
                             'url': 'http://0.0.0.0/dogs/1/',
                             'new_value': {
                                 'color': 'golden',
                                 'nickname': 'Fido'
                             },
                             'old_value': {
                                 'color': 'black',
                                 'nickname': 'Spot'
                             },
                         })])
        self.assertEqual(mock_reverse.call_args_list,
                         [mock.call('dummy-detail', args=[1])]) 
Example #15
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_create_notification(self, mock_reverse, mock_router):
        request = self._make_request('POST', {'nickname': 'Rover', 'color': 'brown'})
        mock_reverse.return_value = '/dogs/2/'
        mock_router.registry = [('dogs', None, 'dummy')]

        response = self.view(request)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(request._messagings,
                         [('.dogs.added', {
                             'url': 'http://0.0.0.0/dogs/2/',
                             'new_value': {
                                 'color': 'brown',
                                 'nickname': 'Rover'
                             },
                         })])
        self.assertEqual(mock_reverse.call_args_list,
                         [mock.call('dummy-detail', args=[2])]) 
Example #16
Source File: handlers.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def About(request):
  """About page."""
  overview = """These tests cover browers' implementations of 
  <a href="http://blog.whatwg.org/the-road-to-html-5-contenteditable">contenteditable</a>
  for basic rich text formatting commands. Most browser implementations do very
  well at editing the HTML which is generated by their own execCommands. But a
  big problem happens when developers try to make cross-browser web
  applications using contenteditable - most browsers are not able to correctly
  change formatting generated by other browsers. On top of that, most browsers
  allow users to to paste arbitrary HTML from other webpages into a
  contenteditable region, which is even harder for browsers to properly
  format. These tests check how well the execCommand, queryCommandState,
  and queryCommandValue functions work with different types of HTML. Please
  note that these are WYSIWYG editing tests, not semantic editing tests. Any
  HTML which produces a given visual style should be changeable via the
  execCommand for that style."""
  return util.About(request, CATEGORY, category_title='Rich Text',
                    overview=overview, show_hidden=False) 
Example #17
Source File: common.py    From django-oidc-provider with MIT License 6 votes vote down vote up
def default_idtoken_processing_hook(
        id_token, user, token, request, **kwargs):
    """
    Hook to perform some additional actions to `id_token` dictionary just before serialization.

    :param id_token: dictionary contains values that going to be serialized into `id_token`
    :type id_token: dict

    :param user: user for whom id_token is generated
    :type user: User

    :param token: the Token object created for the authentication request
    :type token: oidc_provider.models.Token

    :param request: the request initiating this ID token processing
    :type request: django.http.HttpRequest

    :return: custom modified dictionary of values for `id_token`
    :rtype: dict
    """
    return id_token 
Example #18
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def _make_request(self, method, data=None):
        request = django.http.HttpRequest()
        request.method = method
        request._messagings = []
        request.META = {'SERVER_NAME': '0.0.0.0', 'SERVER_PORT': 80}
        if data:
            data = json.dumps(data)
            request._read_started = False
            request.META.update({'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': 'application/json'})
            request._stream = BytesIO(data)
        return request 
Example #19
Source File: views.py    From OpenBench with GNU General Public License v3.0 5 votes vote down vote up
def register(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  GET  : Return the HTML template used for registering a new User        #
    #                                                                         #
    #  POST : Enforce matching alpha-numeric passwords, and then attempt to   #
    #         generate a new User and Profile. Return to the homepage after   #
    #         after logging the User in. Share any errors with the viewer     #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    if request.method == 'GET':
        return render(request, 'register.html')

    if request.POST['password1'] != request.POST['password2']:
        return index(request, error='Passwords Do Not Match')

    if not request.POST['username'].isalnum():
        return index(request, error='Alpha Numeric Usernames Only')

    if User.objects.filter(username=request.POST['username']):
        return index(request, error='That Username is taken')

    email    = request.POST['email']
    username = request.POST['username']
    password = request.POST['password1']

    user = User.objects.create_user(username, email, password)
    django.contrib.auth.login(request, user)
    Profile.objects.create(user=user)

    return django.http.HttpResponseRedirect('/index/') 
Example #20
Source File: views.py    From OpenBench with GNU General Public License v3.0 5 votes vote down vote up
def logout(request):

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                         #
    #  GET  : Logout the User if they are logged in. Return to the main page  #
    #                                                                         #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    django.contrib.auth.logout(request)
    return django.http.HttpResponseRedirect('/index/') 
Example #21
Source File: deletion.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        del request, args, kwargs  # unused
        q = model.Person.all(filter_expired=False).filter(
            'repo =', self.env.repo)
        cursor = self.params.get('cursor', '')
        if cursor:
            q.with_cursor(cursor)
        try:
            now = utils.get_utcnow()
            for person in q:
                next_cursor = q.cursor()
                was_expired = person.is_expired
                person.put_expiry_flags()
                if (now - person.get_effective_expiry_date() > _EXPIRED_TTL):
                    # Only original records should get to this point, since
                    # other records should have been deleted altogether as soon
                    # as they expired. Just in case the deletion task has failed
                    # for three days though, check that it's an original record
                    # to ensure we don't change the contents of a non-original
                    # record.
                    if person.is_original():
                        person.wipe_contents()
                    else:
                        person.delete_related_entities(delete_self=True)
                elif person.is_expired and not was_expired:
                    # Since we're not sending notices, handler isn't really
                    # needed.
                    # TODO(nworden): check with Product about whether we want to
                    # send notices for expirations. The current language
                    # indicates it was designed for cases where someone manually
                    # requested deletion of the record.
                    delete.delete_person(None, person, send_notices=False)
                cursor = next_cursor
        except runtime.DeadlineExceededError:
            self.schedule_task(self.env.repo, cursor=cursor)
        except datastore_errors.Timeout:
            self.schedule_task(self.env.repo, cursor=cursor)
        return django.http.HttpResponse('') 
Example #22
Source File: base.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        """Schedules tasks."""
        del request, args, kwargs  # unused
        if self.env.repo == 'global':
            for repo in model.Repo.list():
                self.schedule_task(repo)
        else:
            self.schedule_task(self.env.repo)
        return django.http.HttpResponse('') 
Example #23
Source File: handlers.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def About(request):
  """About page."""
  overview = """These tests cover browers' implementations of 
  <a href="http://blog.whatwg.org/the-road-to-html-5-contenteditable">contenteditable</a>
  for basic rich text formatting commands. Most browser implementations do very
  well at editing the HTML which is generated by their own execCommands. But a
  big problem happens when developers try to make cross-browser web
  applications using contenteditable - most browsers are not able to correctly
  change formatting generated by other browsers. On top of that, most browsers
  allow users to to paste arbitrary HTML from other webpages into a
  contenteditable region, which is even harder for browsers to properly
  format. These tests check how well the execCommand, queryCommandState,
  and queryCommandValue functions work with different types of HTML."""
  return util.About(request, common.CATEGORY, category_title='Rich Text',
                    overview=overview, show_hidden=False) 
Example #24
Source File: views.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        response = HttpResponseRedirect("/")

        redirect_url = request.META.get("HTTP_REFERER", request.build_absolute_uri())

        args = [redirect_url]
        kwargs = {"require_https": request.is_secure()}

        allowed_hosts = self.get_success_url_allowed_hosts()
        if __version__.startswith("2.0"):
            kwargs["allowed_hosts"] = allowed_hosts
        else:
            args.append(allowed_hosts)

        if __version__.startswith("2"):
            from django.utils.http import is_safe_url

            url_is_safe = is_safe_url(*args, **kwargs)
        else:
            from django.utils.http import url_has_allowed_host_and_scheme

            url_is_safe = url_has_allowed_host_and_scheme(*args, **kwargs)

        if url_is_safe:
            response = HttpResponseRedirect(redirect_url)

        form = ConsentForm(request.POST)
        if form.is_valid():
            set_consent(
                request,
                response,
                {key: str(value).lower() for key, value in form.cleaned_data.items()},
                explicit=True,
            )

        return response 
Example #25
Source File: common.py    From django-oidc-provider with MIT License 5 votes vote down vote up
def default_after_end_session_hook(
        request, id_token=None, post_logout_redirect_uri=None,
        state=None, client=None, next_page=None):
    """
    Default function for setting OIDC_AFTER_END_SESSION_HOOK.

    :param request: Django request object
    :type request: django.http.HttpRequest

    :param id_token: token passed by `id_token_hint` url query param.
                     Do NOT trust this param or validate token
    :type id_token: str

    :param post_logout_redirect_uri: redirect url from url query param.
                                     Do NOT trust this param
    :type post_logout_redirect_uri: str

    :param state: state param from url query params
    :type state: str

    :param client: If id_token has `aud` param and associated Client exists,
        this is an instance of it - do NOT trust this param
    :type client: oidc_provider.models.Client

    :param next_page: calculated next_page redirection target
    :type next_page: str
    :return:
    """
    return None 
Example #26
Source File: base.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        del request, args, kwargs  # Unused.
        self.log()
        root = ET.Element('feed', nsmap=ThirdPartyFeedBaseView._NAMESPACE_MAP)
        self.add_feed_elements(root)
        feed = ET.ElementTree(root)
        resp = django.http.HttpResponse()
        resp['Content-Type'] = 'application/xml; charset=utf-8'
        resp.write('<?xml version="1.0" encoding="UTF-8"?>')
        feed.write(resp)
        return resp 
Example #27
Source File: repo_feed.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def add_feed_elements(self, root):
        ET.SubElement(root, 'id').text = self.build_absolute_uri()
        ET.SubElement(root, 'title').text = RepoFeedView._TITLE
        if self.env.repo == 'global':
            repos = model.Repo.all().filter(
                'activation_status !=', model.Repo.ActivationStatus.STAGING)
        else:
            repo = model.Repo.get(self.env.repo)
            if repo.activation_status == model.Repo.ActivationStatus.ACTIVE:
                repos = [repo]
            else:
                raise django.http.Http404()
        repo_confs = {}
        for repo in repos:
            repo_id = repo.key().name()
            repo_conf = config.Configuration(repo_id, include_global=False)
            repo_confs[repo_id] = repo_conf
        updated_dates = [conf.updated_date for conf in repo_confs.values()]
        # If there's no non-staging repositories, it's not really clear what
        # updated_date should be; we just use the current time.
        latest_updated_date = (
            max(updated_dates) if updated_dates else utils.get_utcnow())
        ET.SubElement(root, 'updated').text = utils.format_utc_timestamp(
            latest_updated_date)
        for repo in repos:
            if repo.activation_status == model.Repo.ActivationStatus.ACTIVE:
                self._add_repo_entry(root, repo, repo_confs[repo.key().name()]) 
Example #28
Source File: frontendapi.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def _json_response(self, data):
        return django.http.HttpResponse(
            self._json_encoder.encode(data),
            content_type='application/json; charset=utf-8') 
Example #29
Source File: static_files.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        """Serves get requests with configurable static files."""
        del request, args  # unused
        filename = kwargs['filename']
        if filename not in CONFIGURABLE_STATIC_FILES:
            return self.error(404)
        fileinfo = CONFIGURABLE_STATIC_FILES[filename]
        return django.http.HttpResponse(
            resources.get_rendered(
                'static/configurable/%s' % filename, self.env.lang),
            content_type=fileinfo.content_type) 
Example #30
Source File: admin.py    From django-csv-exports with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def export_as_csv(admin_model, request, queryset):
    """
    Generic csv export admin action.
    based on http://djangosnippets.org/snippets/1697/
    """
    # everyone has perms to export as csv unless explicitly defined
    if getattr(settings, 'DJANGO_EXPORTS_REQUIRE_PERM', None):
        admin_opts = admin_model.opts
        codename = '%s_%s' % ('csv', admin_opts.object_name.lower())
        has_csv_permission = request.user.has_perm("%s.%s" % (admin_opts.app_label, codename))
    else:
        has_csv_permission = admin_model.has_csv_permission(request) \
            if (hasattr(admin_model, 'has_csv_permission') and callable(getattr(admin_model, 'has_csv_permission'))) \
            else True
    if has_csv_permission:
        opts = admin_model.model._meta
        if getattr(admin_model, 'csv_fields', None):
            field_names = admin_model.csv_fields
        else:
            field_names = [field.name for field in opts.fields]
            field_names.sort()

        if django.VERSION[0] == 1 and django.VERSION[1] <= 5:
            response = HttpResponse(mimetype='text/csv')
        else:
            response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % text(opts).replace('.', '_')

        queryset = queryset.values_list(*field_names)
        pandas.DataFrame(list(queryset), columns=field_names).to_csv(response, index=False, encoding='utf-8')
        return response
    return HttpResponseForbidden()