mirror of
https://github.com/jazzband/django-downloadview.git
synced 2026-03-17 06:50:24 +00:00
Compare commits
No commits in common. "master" and "2.2" have entirely different histories.
88 changed files with 486 additions and 786 deletions
8
.github/dependabot.yml
vendored
8
.github/dependabot.yml
vendored
|
|
@ -1,8 +0,0 @@
|
|||
version: 2
|
||||
|
||||
updates:
|
||||
# Maintain dependencies for GitHub Actions
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
40
.github/workflows/release.yml
vendored
40
.github/workflows/release.yml
vendored
|
|
@ -1,40 +0,0 @@
|
|||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: github.repository == 'jazzband/django-downloadview'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: 3.8
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install -U pip
|
||||
python -m pip install -U setuptools twine wheel
|
||||
|
||||
- name: Build package
|
||||
run: |
|
||||
python setup.py --version
|
||||
python setup.py sdist --format=gztar bdist_wheel
|
||||
twine check dist/*
|
||||
|
||||
- name: Upload packages to Jazzband
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
|
||||
uses: pypa/gh-action-pypi-publish@master
|
||||
with:
|
||||
user: jazzband
|
||||
password: ${{ secrets.JAZZBAND_RELEASE_KEY }}
|
||||
repository_url: https://jazzband.co/projects/django-downloadview/upload
|
||||
61
.github/workflows/test.yml
vendored
61
.github/workflows/test.yml
vendored
|
|
@ -1,61 +0,0 @@
|
|||
name: Test
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: build (Python ${{ matrix.python-version }}, Django ${{ matrix.django-version }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13', '3.14']
|
||||
django-version: ['4.2', '5.0', '5.1', '5.2', 'main']
|
||||
exclude:
|
||||
# Django 5.0 dropped support for Python <3.10
|
||||
- django-version: '5.0'
|
||||
python-version: '3.8'
|
||||
- django-version: '5.0'
|
||||
python-version: '3.9'
|
||||
- django-version: 'main'
|
||||
python-version: '3.8'
|
||||
- django-version: 'main'
|
||||
python-version: '3.9'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Get pip cache dir
|
||||
id: pip-cache
|
||||
run: |
|
||||
echo "::set-output name=dir::$(pip cache dir)"
|
||||
|
||||
- name: Cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pip-cache.outputs.dir }}
|
||||
key:
|
||||
${{ matrix.python-version }}-v1-${{ hashFiles('**/setup.py') }}
|
||||
restore-keys: |
|
||||
${{ matrix.python-version }}-v1-
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install --upgrade tox tox-gh-actions
|
||||
|
||||
- name: Tox tests
|
||||
run: |
|
||||
tox -v
|
||||
env:
|
||||
DJANGO: ${{ matrix.django-version }}
|
||||
|
||||
- name: Upload coverage
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
name: Python ${{ matrix.python-version }}
|
||||
8
.gitignore
vendored
8
.gitignore
vendored
|
|
@ -6,8 +6,6 @@
|
|||
|
||||
# Data files.
|
||||
/var/
|
||||
coverage.xml
|
||||
.coverage/
|
||||
|
||||
# Python files.
|
||||
*.pyc
|
||||
|
|
@ -16,17 +14,11 @@ coverage.xml
|
|||
|
||||
# Tox files.
|
||||
/.tox/
|
||||
.eggs
|
||||
*.egg-info
|
||||
|
||||
# Virtualenv files (created by tox).
|
||||
/build/
|
||||
/dist/
|
||||
|
||||
# Virtual environments (created by user).
|
||||
/venv/
|
||||
|
||||
# Editors' temporary buffers.
|
||||
.*.swp
|
||||
*~
|
||||
.idea
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ force_grid_wrap=0
|
|||
line_length=88
|
||||
combine_as_imports=True
|
||||
|
||||
# List sections with django and
|
||||
# List sections with django and
|
||||
known_django=django
|
||||
known_downloadview=django_downloadview
|
||||
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v6.0.0
|
||||
hooks:
|
||||
- id: check-toml
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- id: mixed-line-ending
|
||||
- id: file-contents-sorter
|
||||
files: docs/spelling_wordlist.txt
|
||||
- repo: https://github.com/pycqa/doc8
|
||||
rev: v2.0.0
|
||||
hooks:
|
||||
- id: doc8
|
||||
- repo: https://github.com/adamchainz/django-upgrade
|
||||
rev: 1.29.1
|
||||
hooks:
|
||||
- id: django-upgrade
|
||||
args: [--target-version, "4.2"]
|
||||
- repo: https://github.com/pre-commit/pygrep-hooks
|
||||
rev: v1.10.0
|
||||
hooks:
|
||||
- id: rst-backticks
|
||||
- id: rst-directive-colons
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v4.0.0-alpha.8
|
||||
hooks:
|
||||
- id: prettier
|
||||
entry: env PRETTIER_LEGACY_CLI=1 prettier
|
||||
types_or: [javascript, css]
|
||||
args:
|
||||
- --trailing-comma=es5
|
||||
- repo: https://github.com/pre-commit/mirrors-eslint
|
||||
rev: v9.39.1
|
||||
hooks:
|
||||
- id: eslint
|
||||
additional_dependencies:
|
||||
- "eslint@v9.0.0-beta.1"
|
||||
- "@eslint/js@v9.0.0-beta.1"
|
||||
- "globals"
|
||||
files: \.js?$
|
||||
types: [file]
|
||||
args:
|
||||
- --fix
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: 'v0.14.5'
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
- id: ruff-format
|
||||
- repo: https://github.com/tox-dev/pyproject-fmt
|
||||
rev: v2.11.1
|
||||
hooks:
|
||||
- id: pyproject-fmt
|
||||
- repo: https://github.com/abravalheri/validate-pyproject
|
||||
rev: v0.24.1
|
||||
hooks:
|
||||
- id: validate-pyproject
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
# .readthedocs.yaml
|
||||
# Read the Docs configuration file
|
||||
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
|
||||
|
||||
version: 2
|
||||
|
||||
build:
|
||||
os: ubuntu-22.04
|
||||
tools:
|
||||
python: "3.10"
|
||||
|
||||
sphinx:
|
||||
configuration: docs/conf.py
|
||||
|
||||
python:
|
||||
install:
|
||||
- method: pip
|
||||
path: .
|
||||
34
.travis.yml
Normal file
34
.travis.yml
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
language: python
|
||||
dist: bionic
|
||||
python:
|
||||
- 3.6
|
||||
- 3.7
|
||||
- 3.8
|
||||
- 3.9-dev
|
||||
install:
|
||||
- pip install tox tox-travis
|
||||
script:
|
||||
- tox -v
|
||||
jobs:
|
||||
fast_finish: true
|
||||
include:
|
||||
- stage: deploy
|
||||
env:
|
||||
python: 3.7
|
||||
script: skip
|
||||
deploy:
|
||||
provider: pypi
|
||||
user: jazzband
|
||||
server: https://jazzband.co/projects/django-downloadview/upload
|
||||
distributions: sdist bdist_wheel
|
||||
password:
|
||||
secure: TYFfz5OkSH0YwTKh0lc0PbddcuZh5oL2H1AVIXHs2dODQ46PNgLYgDRe9k9PItAenxm7QCnGRONJo2o1GNuiCcAOWK84jbrmufHZ5EeKTOVtssyrffSA/Oxfs5mFJ/Kgy3o8FC1hGRKXrXFN3bvedmVHERGQimQESPxHQ9sPWhc=
|
||||
skip_existing: true
|
||||
skip_cleanup: true
|
||||
on:
|
||||
tags: true
|
||||
repo: jazzband/django-downloadview
|
||||
python: 3.7
|
||||
after_success:
|
||||
- pip install coveralls
|
||||
- coveralls
|
||||
28
AUTHORS
28
AUTHORS
|
|
@ -4,25 +4,13 @@ Authors & contributors
|
|||
|
||||
Maintainer: Benoît Bryon <benoit@marmelune.net>
|
||||
|
||||
Original code by `PeopleDoc <https://www.people-doc.com/>`_ team:
|
||||
Original code by `Novapost <http://www.novapost.fr>`_ team:
|
||||
|
||||
* Adam Chainz <adam@adamj.eu>
|
||||
* Aleksi Häkli <aleksi.hakli@iki.fi>
|
||||
* Nicolas Tobo <https://github.com/nicolastobo>
|
||||
* Lauréline Guérin <https://github.com/zebuline>
|
||||
* Gregory Tappero <https://github.com/coulix>
|
||||
* Rémy Hubscher <remy.hubscher@novapost.fr>
|
||||
* Benoît Bryon <benoit@marmelune.net>
|
||||
* CJ <cjdreiss@users.noreply.github.com>
|
||||
* David Wolf <68775926+devidw@users.noreply.github.com>
|
||||
* Davide Setti <setti.davide89@gmail.com>
|
||||
* Erik Dykema <dykema@gmail.com>
|
||||
* Fabre Florian <ffabre@hybird.org>
|
||||
* Hasan Ramezani <hasan.r67@gmail.com>
|
||||
* Jannis Leidel <jannis@leidel.info>
|
||||
* John Hagen <johnthagen@gmail.com>
|
||||
* Mariusz Felisiak <felisiak.mariusz@gmail.com>
|
||||
* Martin Bächtold <martin@baechtold.me>
|
||||
* Nikhil Benesch <nikhil.benesch@gmail.com>
|
||||
* Omer Katz <omer.drow@gmail.com>
|
||||
* Peter Marheine <peter@taricorp.net>
|
||||
* René Leonhardt <rene.leonhardt@gmail.com>
|
||||
* Rémy HUBSCHER <hubscher.remy@gmail.com>
|
||||
* Tim Gates <tim.gates@iress.com>
|
||||
* zero13cool <zero13cool@yandex.ru>
|
||||
* Aleksi Häkli <https://github.com/aleksihakli>
|
||||
|
||||
Developers: https://github.com/jazzband/django-downloadview/graphs/contributors
|
||||
|
|
|
|||
27
CHANGELOG
27
CHANGELOG
|
|
@ -4,33 +4,10 @@ Changelog
|
|||
This document describes changes between past releases. For information about
|
||||
future releases, check `milestones`_ and :doc:`/about/vision`.
|
||||
|
||||
2.6.0 (unreleased)
|
||||
|
||||
2.2 (unreleased)
|
||||
----------------
|
||||
|
||||
- No changes yet
|
||||
|
||||
|
||||
2.5.0 (2025-10-28)
|
||||
----------------
|
||||
|
||||
- Upgrade to Django 5.2 and Python 3.14
|
||||
|
||||
|
||||
2.4.0 (2024-08-05)
|
||||
------------------
|
||||
|
||||
- Drop support for Python 3.6
|
||||
- Escape malicious filenames
|
||||
- Handle headers in XAccel responses
|
||||
|
||||
|
||||
2.3.0 (2022-01-11)
|
||||
------------------
|
||||
|
||||
- Drop Django 3.0 support
|
||||
- Add Django 3.2 support
|
||||
- Add support for Python 3.10
|
||||
- Add support for Django 4.0
|
||||
- Remove support for Python 3.5 and Django 1.11
|
||||
- Add support for Python 3.9 and Django 3.1
|
||||
- Remove old urls syntax and adopt the new one
|
||||
|
|
|
|||
|
|
@ -1,46 +0,0 @@
|
|||
# Code of Conduct
|
||||
|
||||
As contributors and maintainers of the Jazzband projects, and in the interest of
|
||||
fostering an open and welcoming community, we pledge to respect all people who
|
||||
contribute through reporting issues, posting feature requests, updating documentation,
|
||||
submitting pull requests or patches, and other activities.
|
||||
|
||||
We are committed to making participation in the Jazzband a harassment-free experience
|
||||
for everyone, regardless of the level of experience, gender, gender identity and
|
||||
expression, sexual orientation, disability, personal appearance, body size, race,
|
||||
ethnicity, age, religion, or nationality.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
- The use of sexualized language or imagery
|
||||
- Personal attacks
|
||||
- Trolling or insulting/derogatory comments
|
||||
- Public or private harassment
|
||||
- Publishing other's private information, such as physical or electronic addresses,
|
||||
without explicit permission
|
||||
- Other unethical or unprofessional conduct
|
||||
|
||||
The Jazzband roadies have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are not
|
||||
aligned to this Code of Conduct, or to ban temporarily or permanently any contributor
|
||||
for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
By adopting this Code of Conduct, the roadies commit themselves to fairly and
|
||||
consistently applying these principles to every aspect of managing the jazzband
|
||||
projects. Roadies who do not follow or enforce the Code of Conduct may be permanently
|
||||
removed from the Jazzband roadies.
|
||||
|
||||
This code of conduct applies both within project spaces and in public spaces when an
|
||||
individual is representing the project or its community.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
|
||||
contacting the roadies at `roadies@jazzband.co`. All complaints will be reviewed and
|
||||
investigated and will result in a response that is deemed necessary and appropriate to
|
||||
the circumstances. Roadies are obligated to maintain confidentiality with regard to the
|
||||
reporter of an incident.
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version
|
||||
1.3.0, available at [https://contributor-covenant.org/version/1/3/0/][version]
|
||||
|
||||
[homepage]: https://contributor-covenant.org
|
||||
[version]: https://contributor-covenant.org/version/1/3/0/
|
||||
|
|
@ -11,7 +11,7 @@ This is a `Jazzband <https://jazzband.co>`_ project. By contributing you agree t
|
|||
|
||||
|
||||
This document provides guidelines for people who want to contribute to
|
||||
``django-downloadview``.
|
||||
`django-downloadview`.
|
||||
|
||||
|
||||
**************
|
||||
|
|
@ -50,7 +50,7 @@ Use topic branches
|
|||
Fork, clone
|
||||
***********
|
||||
|
||||
Clone ``django-downloadview`` repository (adapt to use your own fork):
|
||||
Clone `django-downloadview` repository (adapt to use your own fork):
|
||||
|
||||
.. code:: sh
|
||||
|
||||
|
|
@ -62,7 +62,7 @@ Clone ``django-downloadview`` repository (adapt to use your own fork):
|
|||
Usual actions
|
||||
*************
|
||||
|
||||
The ``Makefile`` is the reference card for usual actions in development
|
||||
The `Makefile` is the reference card for usual actions in development
|
||||
environment:
|
||||
|
||||
* Install development toolkit with `pip`_: ``make develop``.
|
||||
|
|
@ -70,7 +70,7 @@ environment:
|
|||
* Run tests with `tox`_: ``make test``.
|
||||
|
||||
* Build documentation: ``make documentation``. It builds `Sphinx`_
|
||||
documentation in ``var/docs/html/index.html``.
|
||||
documentation in `var/docs/html/index.html`.
|
||||
|
||||
* Release project with `zest.releaser`_: ``make release``.
|
||||
|
||||
|
|
@ -84,7 +84,7 @@ See also ``make help``.
|
|||
Demo project included
|
||||
*********************
|
||||
|
||||
The ``demo`` included in project's repository is part of the tests and
|
||||
The `demo` included in project's repository is part of the tests and
|
||||
documentation. Maintain it along with code and documentation.
|
||||
|
||||
|
||||
|
|
@ -92,7 +92,7 @@ documentation. Maintain it along with code and documentation.
|
|||
|
||||
.. target-notes::
|
||||
|
||||
.. _`bugtracker`:
|
||||
.. _`bugtracker`:
|
||||
https://github.com/jazzband/django-downloadview/issues
|
||||
.. _`rebase`: http://git-scm.com/book/en/Git-Branching-Rebasing
|
||||
.. _`merge-based rebase`: https://tech.people-doc.com/psycho-rebasing.html
|
||||
|
|
|
|||
4
INSTALL
4
INSTALL
|
|
@ -12,8 +12,8 @@ Install
|
|||
Requirements
|
||||
************
|
||||
|
||||
`django-downloadview` has been tested with `Python`_ 3.7, 3.8, 3.9 and 3.10.
|
||||
Other versions may work, but they are not part of the test suite at the moment.
|
||||
`django-downloadview` has been tested with `Python`_ 3.6, 3.7 and 3.8. Other
|
||||
versions may work, but they are not part of the test suite at the moment.
|
||||
|
||||
Installing `django-downloadview` will automatically trigger the installation of
|
||||
the following requirements:
|
||||
|
|
|
|||
|
|
@ -6,3 +6,4 @@ include CONTRIBUTING.rst
|
|||
include INSTALL
|
||||
include LICENSE
|
||||
include README.rst
|
||||
include VERSION
|
||||
|
|
|
|||
6
Makefile
6
Makefile
|
|
@ -92,6 +92,12 @@ demo:
|
|||
runserver: demo
|
||||
demo runserver
|
||||
|
||||
|
||||
#: release - Tag and push to PyPI.
|
||||
.PHONY: release
|
||||
release:
|
||||
$(TOX) -e release
|
||||
|
||||
.PHONY: black
|
||||
black:
|
||||
$(BLACK) demo tests django_downloadview
|
||||
|
|
|
|||
36
README.rst
36
README.rst
|
|
@ -3,39 +3,32 @@ django-downloadview
|
|||
###################
|
||||
|
||||
.. image:: https://jazzband.co/static/img/badge.svg
|
||||
:target: https://jazzband.co/
|
||||
:alt: Jazzband
|
||||
:target: https://jazzband.co/
|
||||
:alt: Jazzband
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/django-downloadview.svg
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
|
||||
.. image:: https://img.shields.io/pypi/pyversions/django-downloadview.svg
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
|
||||
.. image:: https://img.shields.io/pypi/djversions/django-downloadview.svg
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
.. image:: https://img.shields.io/pypi/dm/django-downloadview.svg
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
:target: https://pypi.python.org/pypi/django-downloadview
|
||||
.. image:: https://travis-ci.org/jazzband/django-downloadview.svg?branch=master
|
||||
:target: https://travis-ci.org/jazzband/django-downloadview
|
||||
.. image:: https://coveralls.io/repos/github/jazzband/django-downloadview/badge.svg?branch=master
|
||||
:target: https://coveralls.io/github/jazzband/django-downloadview?branch=master
|
||||
|
||||
.. image:: https://github.com/jazzband/django-downloadview/workflows/Test/badge.svg
|
||||
:target: https://github.com/jazzband/django-downloadview/actions
|
||||
:alt: GitHub Actions
|
||||
|
||||
.. image:: https://codecov.io/gh/jazzband/django-downloadview/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/jazzband/django-downloadview
|
||||
:alt: Coverage
|
||||
|
||||
``django-downloadview`` makes it easy to serve files with `Django`_:
|
||||
|
||||
`django-downloadview` makes it easy to serve files with `Django`_:
|
||||
|
||||
* you manage files with Django (permissions, filters, generation, ...);
|
||||
|
||||
* files are stored somewhere or generated somehow (local filesystem, remote
|
||||
storage, memory...);
|
||||
|
||||
* ``django-downloadview`` helps you stream the files with very little code;
|
||||
* `django-downloadview` helps you stream the files with very little code;
|
||||
|
||||
* ``django-downloadview`` helps you improve performances with reverse proxies,
|
||||
* `django-downloadview` helps you improve performances with reverse proxies,
|
||||
via mechanisms such as Nginx's X-Accel or Apache's X-Sendfile.
|
||||
|
||||
|
||||
|
|
@ -67,7 +60,8 @@ Resources
|
|||
* PyPI page: http://pypi.python.org/pypi/django-downloadview
|
||||
* Code repository: https://github.com/jazzband/django-downloadview
|
||||
* Bugtracker: https://github.com/jazzband/django-downloadview/issues
|
||||
* Continuous integration: https://github.com/jazzband/django-downloadview/actions
|
||||
* Continuous integration: https://travis-ci.org/jazzband/django-downloadview
|
||||
* Roadmap: https://github.com/jazzband/django-downloadview/milestones
|
||||
|
||||
|
||||
.. _`Django`: https://djangoproject.com
|
||||
|
|
|
|||
1
VERSION
Normal file
1
VERSION
Normal file
|
|
@ -0,0 +1 @@
|
|||
2.2
|
||||
|
|
@ -3,7 +3,7 @@ Demo project
|
|||
############
|
||||
|
||||
`Demo folder in project's repository`_ contains a Django project to illustrate
|
||||
``django-downloadview`` usage.
|
||||
`django-downloadview` usage.
|
||||
|
||||
|
||||
*****************************************
|
||||
|
|
@ -31,8 +31,8 @@ Deploy the demo
|
|||
|
||||
System requirements:
|
||||
|
||||
* `Python`_ version 3.7+, available as ``python`` command.
|
||||
|
||||
* `Python`_ version 2.7, available as ``python`` command.
|
||||
|
||||
.. note::
|
||||
|
||||
You may use `Virtualenv`_ to make sure the active ``python`` is the right
|
||||
|
|
|
|||
|
|
@ -43,19 +43,3 @@ class OptimizedByDecoratorTestCase(django.test.TestCase):
|
|||
basename="hello-world.txt",
|
||||
file_path="/apache-optimized-by-decorator/hello-world.txt",
|
||||
)
|
||||
|
||||
|
||||
class ModifiedHeadersTestCase(django.test.TestCase):
|
||||
def test_response(self):
|
||||
"""'apache:modified_headers' returns X-Sendfile response."""
|
||||
setup_file()
|
||||
url = reverse("apache:modified_headers")
|
||||
response = self.client.get(url)
|
||||
assert_x_sendfile(
|
||||
self,
|
||||
response,
|
||||
content_type="text/plain; charset=utf-8",
|
||||
basename="hello-world.txt",
|
||||
file_path="/apache-modified-headers/hello-world.txt",
|
||||
)
|
||||
self.assertEqual(response["X-Test"], "header")
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""URL mapping."""
|
||||
|
||||
from django.urls import path
|
||||
|
||||
from demoproject.apache import views
|
||||
|
|
@ -16,9 +15,4 @@ urlpatterns = [
|
|||
views.optimized_by_decorator,
|
||||
name="optimized_by_decorator",
|
||||
),
|
||||
path(
|
||||
"modified_headers/",
|
||||
views.modified_headers,
|
||||
name="modified_headers",
|
||||
),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -22,17 +22,3 @@ optimized_by_decorator = x_sendfile(
|
|||
source_url=storage.base_url,
|
||||
destination_dir="/apache-optimized-by-decorator/",
|
||||
)
|
||||
|
||||
|
||||
def _modified_headers(request):
|
||||
view = StorageDownloadView.as_view(storage=storage, path="hello-world.txt")
|
||||
response = view(request)
|
||||
response["X-Test"] = "header"
|
||||
return response
|
||||
|
||||
|
||||
modified_headers = x_sendfile(
|
||||
_modified_headers,
|
||||
source_url=storage.base_url,
|
||||
destination_dir="/apache-modified-headers/",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
[
|
||||
{
|
||||
"pk": 1,
|
||||
"model": "object.document",
|
||||
"pk": 1,
|
||||
"model": "object.document",
|
||||
"fields": {
|
||||
"slug": "hello-world",
|
||||
"slug": "hello-world",
|
||||
"file": "object/hello-world.txt"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,19 +43,3 @@ class OptimizedByDecoratorTestCase(django.test.TestCase):
|
|||
basename="hello-world.txt",
|
||||
file_path="/lighttpd-optimized-by-decorator/hello-world.txt",
|
||||
)
|
||||
|
||||
|
||||
class ModifiedHeadersTestCase(django.test.TestCase):
|
||||
def test_response(self):
|
||||
"""'lighttpd:modified_headers' returns X-Sendfile response."""
|
||||
setup_file()
|
||||
url = reverse("lighttpd:modified_headers")
|
||||
response = self.client.get(url)
|
||||
assert_x_sendfile(
|
||||
self,
|
||||
response,
|
||||
content_type="text/plain; charset=utf-8",
|
||||
basename="hello-world.txt",
|
||||
file_path="/lighttpd-modified-headers/hello-world.txt",
|
||||
)
|
||||
self.assertEqual(response["X-Test"], "header")
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""URL mapping."""
|
||||
|
||||
from django.urls import path
|
||||
|
||||
from demoproject.lighttpd import views
|
||||
|
|
@ -16,9 +15,4 @@ urlpatterns = [
|
|||
views.optimized_by_decorator,
|
||||
name="optimized_by_decorator",
|
||||
),
|
||||
path(
|
||||
"modified_headers/",
|
||||
views.modified_headers,
|
||||
name="modified_headers",
|
||||
),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -22,17 +22,3 @@ optimized_by_decorator = x_sendfile(
|
|||
source_url=storage.base_url,
|
||||
destination_dir="/lighttpd-optimized-by-decorator/",
|
||||
)
|
||||
|
||||
|
||||
def _modified_headers(request):
|
||||
view = StorageDownloadView.as_view(storage=storage, path="hello-world.txt")
|
||||
response = view(request)
|
||||
response["X-Test"] = "header"
|
||||
return response
|
||||
|
||||
|
||||
modified_headers = x_sendfile(
|
||||
_modified_headers,
|
||||
source_url=storage.base_url,
|
||||
destination_dir="/lighttpd-modified-headers/",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -51,23 +51,3 @@ class OptimizedByDecoratorTestCase(django.test.TestCase):
|
|||
with_buffering=None,
|
||||
limit_rate=None,
|
||||
)
|
||||
|
||||
|
||||
class ModifiedHeadersTestCase(django.test.TestCase):
|
||||
def test_response(self):
|
||||
"""'nginx:modified_headers' returns X-Sendfile response."""
|
||||
setup_file()
|
||||
url = reverse("nginx:modified_headers")
|
||||
response = self.client.get(url)
|
||||
assert_x_accel_redirect(
|
||||
self,
|
||||
response,
|
||||
content_type="text/plain; charset=utf-8",
|
||||
charset="utf-8",
|
||||
basename="hello-world.txt",
|
||||
redirect_url="/nginx-modified-headers/hello-world.txt",
|
||||
expires=None,
|
||||
with_buffering=None,
|
||||
limit_rate=None,
|
||||
)
|
||||
self.assertEqual(response["X-Test"], "header")
|
||||
|
|
|
|||
|
|
@ -16,9 +16,4 @@ urlpatterns = [
|
|||
views.optimized_by_decorator,
|
||||
name="optimized_by_decorator",
|
||||
),
|
||||
path(
|
||||
"modified_headers/",
|
||||
views.modified_headers,
|
||||
name="modified_headers",
|
||||
),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -22,17 +22,3 @@ optimized_by_decorator = x_accel_redirect(
|
|||
source_url=storage.base_url,
|
||||
destination_url="/nginx-optimized-by-decorator/",
|
||||
)
|
||||
|
||||
|
||||
def _modified_headers(request):
|
||||
view = StorageDownloadView.as_view(storage=storage, path="hello-world.txt")
|
||||
response = view(request)
|
||||
response["X-Test"] = "header"
|
||||
return response
|
||||
|
||||
|
||||
modified_headers = x_accel_redirect(
|
||||
_modified_headers,
|
||||
source_url=storage.base_url,
|
||||
destination_url="/nginx-modified-headers/",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ class DynamicPathDownloadView(PathDownloadView):
|
|||
def get_path(self):
|
||||
"""Return path inside fixtures directory."""
|
||||
# Get path from URL resolvers or as_view kwarg.
|
||||
relative_path = super().get_path()
|
||||
relative_path = super(DynamicPathDownloadView, self).get_path()
|
||||
# Make it absolute.
|
||||
absolute_path = os.path.join(fixtures_dir, relative_path)
|
||||
return absolute_path
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
"""Django settings for django-downloadview demo project."""
|
||||
|
||||
from distutils.version import StrictVersion
|
||||
import os
|
||||
|
||||
from django.utils.version import get_version
|
||||
|
||||
# Configure some relative directories.
|
||||
demoproject_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
|
@ -54,18 +55,30 @@ INSTALLED_APPS = (
|
|||
"django.contrib.sites",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
# Stuff that must be at the end.
|
||||
"django_nose",
|
||||
)
|
||||
|
||||
|
||||
# BEGIN middlewares
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django_downloadview.SmartDownloadMiddleware",
|
||||
]
|
||||
if StrictVersion(get_version()) >= StrictVersion("1.10"):
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django_downloadview.SmartDownloadMiddleware",
|
||||
]
|
||||
else:
|
||||
MIDDLEWARE_CLASSES = [
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django_downloadview.SmartDownloadMiddleware",
|
||||
]
|
||||
# END middlewares
|
||||
|
||||
|
||||
|
|
@ -110,25 +123,37 @@ DOWNLOADVIEW_RULES += [
|
|||
|
||||
# Test/development settings.
|
||||
DEBUG = True
|
||||
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [os.path.join(os.path.dirname(__file__), "templates")],
|
||||
"OPTIONS": {
|
||||
"debug": DEBUG,
|
||||
"context_processors": [
|
||||
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
|
||||
# list if you haven't customized them:
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.i18n",
|
||||
"django.template.context_processors.media",
|
||||
"django.template.context_processors.static",
|
||||
"django.template.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
TEST_RUNNER = "django_nose.NoseTestSuiteRunner"
|
||||
NOSE_ARGS = [
|
||||
"--verbosity=2",
|
||||
"--no-path-adjustment",
|
||||
"--nocapture",
|
||||
"--all-modules",
|
||||
"--with-coverage",
|
||||
"--with-doctest",
|
||||
]
|
||||
|
||||
if StrictVersion(get_version()) >= StrictVersion("1.8"):
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [os.path.join(os.path.dirname(__file__), "templates")],
|
||||
"OPTIONS": {
|
||||
"debug": DEBUG,
|
||||
"context_processors": [
|
||||
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
|
||||
# list if you haven't customized them:
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.i18n",
|
||||
"django.template.context_processors.media",
|
||||
"django.template.context_processors.static",
|
||||
"django.template.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
else:
|
||||
TEMPLATE_DEBUG = DEBUG
|
||||
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), "templates"),)
|
||||
|
|
|
|||
|
|
@ -44,7 +44,8 @@ class StaticPathTestCase(django.test.TestCase):
|
|||
url = reverse("storage:static_path", kwargs={"path": "1.txt"})
|
||||
year = datetime.date.today().year + 4
|
||||
response = self.client.get(
|
||||
url, headers={"if-modified-since": f"Sat, 29 Oct {year} 19:43:31 GMT"}
|
||||
url,
|
||||
HTTP_IF_MODIFIED_SINCE=f"Sat, 29 Oct {year} 19:43:31 GMT",
|
||||
)
|
||||
self.assertTrue(isinstance(response, HttpResponseNotModified))
|
||||
|
||||
|
|
@ -54,7 +55,7 @@ class StaticPathTestCase(django.test.TestCase):
|
|||
setup_file("1.txt")
|
||||
url = reverse("storage:static_path", kwargs={"path": "1.txt"})
|
||||
response = self.client.get(
|
||||
url, headers={"if-modified-since": "Sat, 29 Oct 1980 19:43:31 GMT"}
|
||||
url, HTTP_IF_MODIFIED_SINCE="Sat, 29 Oct 1980 19:43:31 GMT"
|
||||
)
|
||||
assert_download_response(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ class DynamicStorageDownloadView(StorageDownloadView):
|
|||
|
||||
def get_path(self):
|
||||
"""Return uppercase path."""
|
||||
return super().get_path().upper()
|
||||
return super(DynamicStorageDownloadView, self).get_path().upper()
|
||||
|
||||
|
||||
dynamic_path = DynamicStorageDownloadView.as_view(storage=storage)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Test suite for demoproject.download."""
|
||||
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ middleware here, or combine a Django application with an application of another
|
|||
framework.
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
|
|
|||
|
|
@ -1,26 +1,46 @@
|
|||
"""Python packaging."""
|
||||
import os
|
||||
|
||||
from setuptools import setup
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
project_root = os.path.dirname(here)
|
||||
|
||||
setup(
|
||||
name="django-downloadview-demo",
|
||||
version="1.0",
|
||||
description="Serve files with Django and reverse-proxies.",
|
||||
long_description=open(os.path.join(here, "README.rst")).read(),
|
||||
classifiers=[
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"License :: OSI Approved :: BSD License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Framework :: Django",
|
||||
],
|
||||
author="Benoît Bryon",
|
||||
author_email="benoit@marmelune.net",
|
||||
url="https://django-downloadview.readthedocs.io/",
|
||||
license="BSD",
|
||||
packages=["demoproject"],
|
||||
include_package_data=True,
|
||||
zip_safe=False,
|
||||
install_requires=["django-downloadview", "pytest-django"],
|
||||
entry_points={"console_scripts": ["demo = demoproject.manage:main"]},
|
||||
)
|
||||
|
||||
NAME = "django-downloadview-demo"
|
||||
DESCRIPTION = "Serve files with Django and reverse-proxies."
|
||||
README = open(os.path.join(here, "README.rst")).read()
|
||||
VERSION = open(os.path.join(project_root, "VERSION")).read().strip()
|
||||
AUTHOR = "Benoît Bryon"
|
||||
EMAIL = "benoit@marmelune.net"
|
||||
URL = "https://django-downloadview.readthedocs.io/"
|
||||
CLASSIFIERS = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"License :: OSI Approved :: BSD License",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Framework :: Django",
|
||||
]
|
||||
KEYWORDS = []
|
||||
PACKAGES = ["demoproject"]
|
||||
REQUIREMENTS = ["django-downloadview", "django-nose"]
|
||||
ENTRY_POINTS = {"console_scripts": ["demo = demoproject.manage:main"]}
|
||||
|
||||
|
||||
if __name__ == "__main__": # Don't run setup() when we import this module.
|
||||
setup(
|
||||
name=NAME,
|
||||
version=VERSION,
|
||||
description=DESCRIPTION,
|
||||
long_description=README,
|
||||
classifiers=CLASSIFIERS,
|
||||
keywords=" ".join(KEYWORDS),
|
||||
author=AUTHOR,
|
||||
author_email=EMAIL,
|
||||
url=URL,
|
||||
license="BSD",
|
||||
packages=PACKAGES,
|
||||
include_package_data=True,
|
||||
zip_safe=False,
|
||||
install_requires=REQUIREMENTS,
|
||||
entry_points=ENTRY_POINTS,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
"""Serve files with Django and reverse proxies."""
|
||||
|
||||
from django_downloadview.api import * # NoQA
|
||||
|
||||
import importlib.metadata
|
||||
import pkg_resources
|
||||
|
||||
#: Module version, as defined in PEP-0396.
|
||||
__version__ = importlib.metadata.version(__package__.replace("-", "_"))
|
||||
__version__ = pkg_resources.get_distribution(__package__.replace("-", "_")).version
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ See also `documentation of mod_xsendfile for Apache
|
|||
Apache optimizations </optimizations/apache>`.
|
||||
|
||||
"""
|
||||
|
||||
# API shortcuts.
|
||||
from django_downloadview.apache.decorators import x_sendfile # NoQA
|
||||
from django_downloadview.apache.middlewares import XSendfileMiddleware # NoQA
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Decorators to apply Apache X-Sendfile on a specific view."""
|
||||
|
||||
from django_downloadview.apache.middlewares import XSendfileMiddleware
|
||||
from django_downloadview.decorators import DownloadDecorator
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,9 @@ class XSendfileMiddleware(ProxiedDownloadMiddleware):
|
|||
self, get_response=None, source_dir=None, source_url=None, destination_dir=None
|
||||
):
|
||||
"""Constructor."""
|
||||
super().__init__(get_response, source_dir, source_url, destination_dir)
|
||||
super(XSendfileMiddleware, self).__init__(
|
||||
get_response, source_dir, source_url, destination_dir
|
||||
)
|
||||
|
||||
def process_download_response(self, request, response):
|
||||
"""Replace DownloadResponse instances by XSendfileResponse ones."""
|
||||
|
|
@ -32,5 +34,4 @@ class XSendfileMiddleware(ProxiedDownloadMiddleware):
|
|||
content_type=response["Content-Type"],
|
||||
basename=response.basename,
|
||||
attachment=response.attachment,
|
||||
headers=response.headers,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Apache's specific responses."""
|
||||
|
||||
import os.path
|
||||
|
||||
from django_downloadview.response import ProxiedDownloadResponse, content_disposition
|
||||
|
|
@ -8,14 +7,9 @@ from django_downloadview.response import ProxiedDownloadResponse, content_dispos
|
|||
class XSendfileResponse(ProxiedDownloadResponse):
|
||||
"Delegates serving file to Apache via X-Sendfile header."
|
||||
|
||||
def __init__(
|
||||
self, file_path, content_type, basename=None, attachment=True, headers=None
|
||||
):
|
||||
def __init__(self, file_path, content_type, basename=None, attachment=True):
|
||||
"""Return a HttpResponse with headers for Apache X-Sendfile."""
|
||||
# content-type must be provided only as keyword argument to response
|
||||
if headers and content_type:
|
||||
headers.pop("Content-Type", None)
|
||||
super().__init__(content_type=content_type, headers=headers)
|
||||
super(XSendfileResponse, self).__init__(content_type=content_type)
|
||||
if attachment:
|
||||
self.basename = basename or os.path.basename(file_path)
|
||||
self["Content-Disposition"] = content_disposition(self.basename)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
from django_downloadview.apache.response import XSendfileResponse
|
||||
|
||||
|
||||
class XSendfileValidator:
|
||||
class XSendfileValidator(object):
|
||||
"""Utility class to validate XSendfileResponse instances.
|
||||
|
||||
See also :py:func:`assert_x_sendfile` shortcut function.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
# flake8: noqa
|
||||
"""Declaration of API shortcuts."""
|
||||
|
||||
from django_downloadview.files import HTTPFile, StorageFile, VirtualFile
|
||||
from django_downloadview.io import BytesIteratorIO, TextIteratorIO
|
||||
from django_downloadview.middlewares import (
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""File wrappers for use as exchange data between views and responses."""
|
||||
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
|
@ -168,7 +167,7 @@ class VirtualFile(File):
|
|||
File URL.
|
||||
|
||||
"""
|
||||
super().__init__(file, name)
|
||||
super(VirtualFile, self).__init__(file, name)
|
||||
self.url = url
|
||||
if size is not None:
|
||||
self._size = size
|
||||
|
|
@ -184,7 +183,7 @@ class VirtualFile(File):
|
|||
return self._size
|
||||
|
||||
def _set_size(self, value):
|
||||
return super()._set_size(value)
|
||||
return super(VirtualFile, self)._set_size(value)
|
||||
|
||||
size = property(_get_size, _set_size)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
"""Low-level IO operations, for use with file wrappers."""
|
||||
|
||||
import io
|
||||
|
||||
from django.utils.encoding import force_bytes, force_str
|
||||
from django.utils.encoding import force_bytes, force_text
|
||||
|
||||
|
||||
class TextIteratorIO(io.TextIOBase):
|
||||
|
|
@ -33,7 +32,7 @@ class TextIteratorIO(io.TextIOBase):
|
|||
break
|
||||
else:
|
||||
# Make sure we handle text.
|
||||
self._left = force_str(self._left)
|
||||
self._left = force_text(self._left)
|
||||
ret = self._left[:n]
|
||||
self._left = self._left[len(ret) :]
|
||||
return ret
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ See also `documentation of X-Sendfile for Lighttpd
|
|||
</optimizations/lighttpd>`.
|
||||
|
||||
"""
|
||||
|
||||
# API shortcuts.
|
||||
from django_downloadview.lighttpd.decorators import x_sendfile # NoQA
|
||||
from django_downloadview.lighttpd.middlewares import XSendfileMiddleware # NoQA
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Decorators to apply Lighttpd X-Sendfile on a specific view."""
|
||||
|
||||
from django_downloadview.decorators import DownloadDecorator
|
||||
from django_downloadview.lighttpd.middlewares import XSendfileMiddleware
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,9 @@ class XSendfileMiddleware(ProxiedDownloadMiddleware):
|
|||
self, get_response=None, source_dir=None, source_url=None, destination_dir=None
|
||||
):
|
||||
"""Constructor."""
|
||||
super().__init__(get_response, source_dir, source_url, destination_dir)
|
||||
super(XSendfileMiddleware, self).__init__(
|
||||
get_response, source_dir, source_url, destination_dir
|
||||
)
|
||||
|
||||
def process_download_response(self, request, response):
|
||||
"""Replace DownloadResponse instances by XSendfileResponse ones."""
|
||||
|
|
@ -32,5 +34,4 @@ class XSendfileMiddleware(ProxiedDownloadMiddleware):
|
|||
content_type=response["Content-Type"],
|
||||
basename=response.basename,
|
||||
attachment=response.attachment,
|
||||
headers=response.headers,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Lighttpd's specific responses."""
|
||||
|
||||
import os.path
|
||||
|
||||
from django_downloadview.response import ProxiedDownloadResponse, content_disposition
|
||||
|
|
@ -8,14 +7,9 @@ from django_downloadview.response import ProxiedDownloadResponse, content_dispos
|
|||
class XSendfileResponse(ProxiedDownloadResponse):
|
||||
"Delegates serving file to Lighttpd via X-Sendfile header."
|
||||
|
||||
def __init__(
|
||||
self, file_path, content_type, basename=None, attachment=True, headers=None
|
||||
):
|
||||
def __init__(self, file_path, content_type, basename=None, attachment=True):
|
||||
"""Return a HttpResponse with headers for Lighttpd X-Sendfile."""
|
||||
# content-type must be porvided only as keyword argument to response
|
||||
if headers and content_type:
|
||||
headers.pop("Content-Type", None)
|
||||
super().__init__(content_type=content_type, headers=headers)
|
||||
super(XSendfileResponse, self).__init__(content_type=content_type)
|
||||
if attachment:
|
||||
self.basename = basename or os.path.basename(file_path)
|
||||
self["Content-Disposition"] = content_disposition(self.basename)
|
||||
|
|
|
|||
|
|
@ -4,8 +4,7 @@ Download middlewares capture :py:class:`django_downloadview.DownloadResponse`
|
|||
responses and may replace them with optimized download responses.
|
||||
|
||||
"""
|
||||
|
||||
import collections.abc
|
||||
import collections
|
||||
import copy
|
||||
import os
|
||||
|
||||
|
|
@ -15,6 +14,14 @@ from django.core.exceptions import ImproperlyConfigured
|
|||
from django_downloadview.response import DownloadResponse
|
||||
from django_downloadview.utils import import_member
|
||||
|
||||
try:
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
except ImportError:
|
||||
|
||||
class MiddlewareMixin(object):
|
||||
def __init__(self, get_response=None):
|
||||
super(MiddlewareMixin, self).__init__()
|
||||
|
||||
|
||||
#: Sentinel value to detect whether configuration is to be loaded from Django
|
||||
#: settings or not.
|
||||
|
|
@ -31,20 +38,13 @@ def is_download_response(response):
|
|||
return isinstance(response, DownloadResponse)
|
||||
|
||||
|
||||
class BaseDownloadMiddleware:
|
||||
class BaseDownloadMiddleware(MiddlewareMixin):
|
||||
"""Base (abstract) Django middleware that handles download responses.
|
||||
|
||||
Subclasses **must** implement :py:meth:`process_download_response` method.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
response = self.get_response(request)
|
||||
return self.process_response(request, response)
|
||||
|
||||
def is_download_response(self, response):
|
||||
"""Return True if ``response`` can be considered as a file download.
|
||||
|
||||
|
|
@ -77,13 +77,21 @@ class RealDownloadMiddleware(BaseDownloadMiddleware):
|
|||
whose file attribute have either an URL or a file name.
|
||||
|
||||
"""
|
||||
return super().is_download_response(response) and bool(
|
||||
getattr(response.file, "url", None) or getattr(response.file, "name", None)
|
||||
)
|
||||
if super(RealDownloadMiddleware, self).is_download_response(response):
|
||||
try:
|
||||
return response.file.url or response.file.name
|
||||
except AttributeError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class DownloadDispatcher:
|
||||
def __init__(self, middlewares=AUTO_CONFIGURE):
|
||||
class DownloadDispatcherMiddleware(BaseDownloadMiddleware):
|
||||
"Download middleware that dispatches job to several middleware instances."
|
||||
|
||||
def __init__(self, get_response=None, middlewares=AUTO_CONFIGURE):
|
||||
super(DownloadDispatcherMiddleware, self).__init__(get_response)
|
||||
#: List of children middlewares.
|
||||
self.middlewares = middlewares
|
||||
if self.middlewares is AUTO_CONFIGURE:
|
||||
|
|
@ -92,42 +100,34 @@ class DownloadDispatcher:
|
|||
def auto_configure_middlewares(self):
|
||||
"""Populate :attr:`middlewares` from
|
||||
``settings.DOWNLOADVIEW_MIDDLEWARES``."""
|
||||
for key, import_string, kwargs in getattr(
|
||||
for (key, import_string, kwargs) in getattr(
|
||||
settings, "DOWNLOADVIEW_MIDDLEWARES", []
|
||||
):
|
||||
factory = import_member(import_string)
|
||||
middleware = factory(**kwargs)
|
||||
self.middlewares.append((key, middleware))
|
||||
|
||||
def dispatch(self, request, response):
|
||||
def process_download_response(self, request, response):
|
||||
"""Dispatches job to children middlewares."""
|
||||
for key, middleware in self.middlewares:
|
||||
for (key, middleware) in self.middlewares:
|
||||
response = middleware.process_response(request, response)
|
||||
return response
|
||||
|
||||
|
||||
class DownloadDispatcherMiddleware(BaseDownloadMiddleware):
|
||||
"Download middleware that dispatches job to several middleware instances."
|
||||
|
||||
def __init__(self, get_response, middlewares=AUTO_CONFIGURE):
|
||||
super().__init__(get_response)
|
||||
self.dispatcher = DownloadDispatcher(middlewares)
|
||||
|
||||
def process_download_response(self, request, response):
|
||||
return self.dispatcher.dispatch(request, response)
|
||||
|
||||
|
||||
class SmartDownloadMiddleware(DownloadDispatcherMiddleware):
|
||||
class SmartDownloadMiddleware(BaseDownloadMiddleware):
|
||||
"""Easy to configure download middleware."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
get_response,
|
||||
get_response=None,
|
||||
backend_factory=AUTO_CONFIGURE,
|
||||
backend_options=AUTO_CONFIGURE,
|
||||
):
|
||||
"""Constructor."""
|
||||
super().__init__(get_response, middlewares=[])
|
||||
super(SmartDownloadMiddleware, self).__init__(get_response)
|
||||
#: :class:`DownloadDispatcher` instance that can hold multiple
|
||||
#: backend instances.
|
||||
self.dispatcher = DownloadDispatcherMiddleware(middlewares=[])
|
||||
#: Callable (typically a class) to instantiate backend (typically a
|
||||
#: :class:`DownloadMiddleware` subclass).
|
||||
self.backend_factory = backend_factory
|
||||
|
|
@ -145,7 +145,7 @@ class SmartDownloadMiddleware(DownloadDispatcherMiddleware):
|
|||
self.backend_factory = import_member(settings.DOWNLOADVIEW_BACKEND)
|
||||
except AttributeError:
|
||||
raise ImproperlyConfigured(
|
||||
"SmartDownloadMiddleware requires settings.DOWNLOADVIEW_BACKEND"
|
||||
"SmartDownloadMiddleware requires " "settings.DOWNLOADVIEW_BACKEND"
|
||||
)
|
||||
|
||||
def auto_configure_backend_options(self):
|
||||
|
|
@ -155,12 +155,12 @@ class SmartDownloadMiddleware(DownloadDispatcherMiddleware):
|
|||
options_list = copy.deepcopy(settings.DOWNLOADVIEW_RULES)
|
||||
except AttributeError:
|
||||
raise ImproperlyConfigured(
|
||||
"SmartDownloadMiddleware requires settings.DOWNLOADVIEW_RULES"
|
||||
"SmartDownloadMiddleware requires " "settings.DOWNLOADVIEW_RULES"
|
||||
)
|
||||
for key, options in enumerate(options_list):
|
||||
args = []
|
||||
kwargs = {}
|
||||
if isinstance(options, collections.abc.Mapping): # Using kwargs.
|
||||
if isinstance(options, collections.Mapping): # Using kwargs.
|
||||
kwargs = options
|
||||
else:
|
||||
args = options
|
||||
|
|
@ -172,6 +172,10 @@ class SmartDownloadMiddleware(DownloadDispatcherMiddleware):
|
|||
middleware_instance = factory(*args, **kwargs)
|
||||
self.dispatcher.middlewares.append((key, middleware_instance))
|
||||
|
||||
def process_download_response(self, request, response):
|
||||
"""Use :attr:`dispatcher` to process download response."""
|
||||
return self.dispatcher.process_download_response(request, response)
|
||||
|
||||
|
||||
class NoRedirectionMatch(Exception):
|
||||
"""Response object does not match redirection rules."""
|
||||
|
|
@ -181,10 +185,10 @@ class ProxiedDownloadMiddleware(RealDownloadMiddleware):
|
|||
"""Base class for middlewares that use optimizations of reverse proxies."""
|
||||
|
||||
def __init__(
|
||||
self, get_response, source_dir=None, source_url=None, destination_url=None
|
||||
self, get_response=None, source_dir=None, source_url=None, destination_url=None
|
||||
):
|
||||
"""Constructor."""
|
||||
super().__init__(get_response)
|
||||
super(ProxiedDownloadMiddleware, self).__init__(get_response)
|
||||
|
||||
self.source_dir = source_dir
|
||||
self.source_url = source_url
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ See also `Nginx X-accel documentation <http://wiki.nginx.org/X-accel>`_ and
|
|||
</optimizations/nginx>`.
|
||||
|
||||
"""
|
||||
|
||||
# API shortcuts.
|
||||
from django_downloadview.nginx.decorators import x_accel_redirect # NoQA
|
||||
from django_downloadview.nginx.middlewares import XAccelRedirectMiddleware # NoQA
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Decorators to apply Nginx X-Accel on a specific view."""
|
||||
|
||||
from django_downloadview.decorators import DownloadDecorator
|
||||
from django_downloadview.nginx.middlewares import XAccelRedirectMiddleware
|
||||
|
||||
|
|
|
|||
|
|
@ -58,7 +58,9 @@ class XAccelRedirectMiddleware(ProxiedDownloadMiddleware):
|
|||
else:
|
||||
source_dir = source_dir
|
||||
|
||||
super().__init__(get_response, source_dir, source_url, destination_url)
|
||||
super(XAccelRedirectMiddleware, self).__init__(
|
||||
get_response, source_dir, source_url, destination_url
|
||||
)
|
||||
|
||||
self.expires = expires
|
||||
self.with_buffering = with_buffering
|
||||
|
|
@ -85,7 +87,6 @@ class XAccelRedirectMiddleware(ProxiedDownloadMiddleware):
|
|||
with_buffering=self.with_buffering,
|
||||
limit_rate=self.limit_rate,
|
||||
attachment=response.attachment,
|
||||
headers=response.headers,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -131,7 +132,7 @@ class SingleXAccelRedirectMiddleware(XAccelRedirectMiddleware):
|
|||
"settings.NGINX_DOWNLOAD_MIDDLEWARE_DESTINATION_URL is "
|
||||
"required by %s middleware" % self.__class__.__name__
|
||||
)
|
||||
super().__init__(
|
||||
super(SingleXAccelRedirectMiddleware, self).__init__(
|
||||
get_response=get_response,
|
||||
source_dir=settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR,
|
||||
source_url=settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_URL,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Nginx's specific responses."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from django.utils.timezone import now
|
||||
|
|
@ -20,13 +19,9 @@ class XAccelRedirectResponse(ProxiedDownloadResponse):
|
|||
with_buffering=None,
|
||||
limit_rate=None,
|
||||
attachment=True,
|
||||
headers=None,
|
||||
):
|
||||
"""Return a HttpResponse with headers for Nginx X-Accel-Redirect."""
|
||||
# content-type must be porvided only as keyword argument to response
|
||||
if headers and content_type:
|
||||
headers.pop("Content-Type", None)
|
||||
super().__init__(content_type=content_type, headers=headers)
|
||||
super(XAccelRedirectResponse, self).__init__(content_type=content_type)
|
||||
if attachment:
|
||||
self.basename = basename or url_basename(redirect_url, content_type)
|
||||
self["Content-Disposition"] = content_disposition(self.basename)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@
|
|||
for details.
|
||||
|
||||
"""
|
||||
|
||||
import warnings
|
||||
|
||||
from django.conf import settings
|
||||
|
|
@ -18,7 +17,14 @@ from django.core.exceptions import ImproperlyConfigured
|
|||
deprecated_middleware = "django_downloadview.nginx.XAccelRedirectMiddleware"
|
||||
|
||||
|
||||
if deprecated_middleware in settings.MIDDLEWARE:
|
||||
def get_middlewares():
|
||||
try:
|
||||
return settings.MIDDLEWARE
|
||||
except AttributeError:
|
||||
return settings.MIDDLEWARE_CLASSES
|
||||
|
||||
|
||||
if deprecated_middleware in get_middlewares():
|
||||
raise ImproperlyConfigured(
|
||||
"{deprecated_middleware} middleware has been renamed as of "
|
||||
"django-downloadview version 1.3. You may use "
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
from django_downloadview.nginx.response import XAccelRedirectResponse
|
||||
|
||||
|
||||
class XAccelRedirectValidator:
|
||||
class XAccelRedirectValidator(object):
|
||||
"""Utility class to validate XAccelRedirectResponse instances.
|
||||
|
||||
See also :py:func:`assert_x_accel_redirect` shortcut function.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
""":py:class:`django.http.HttpResponse` subclasses."""
|
||||
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
|
|
@ -73,13 +72,7 @@ def content_disposition(filename):
|
|||
"""
|
||||
if not filename:
|
||||
return "attachment"
|
||||
# ASCII filenames are quoted and must ensure escape sequences
|
||||
# in the filename won't break out of the quoted header value
|
||||
# which can permit a reflected file download attack. The UTF-8
|
||||
# version is immune because it's not quoted.
|
||||
ascii_filename = (
|
||||
encode_basename_ascii(filename).replace("\\", "\\\\").replace('"', r"\"")
|
||||
)
|
||||
ascii_filename = encode_basename_ascii(filename)
|
||||
utf8_filename = encode_basename_utf8(filename)
|
||||
if ascii_filename == utf8_filename: # ASCII only.
|
||||
return f'attachment; filename="{ascii_filename}"'
|
||||
|
|
@ -145,7 +138,7 @@ class DownloadResponse(StreamingHttpResponse):
|
|||
#: A :doc:`file wrapper instance </files>`, such as
|
||||
#: :class:`~django.core.files.base.File`.
|
||||
self.file = file_instance
|
||||
super().__init__(
|
||||
super(DownloadResponse, self).__init__(
|
||||
streaming_content=self.file, status=status, content_type=content_type
|
||||
)
|
||||
|
||||
|
|
@ -202,6 +195,16 @@ class DownloadResponse(StreamingHttpResponse):
|
|||
self._default_headers = headers
|
||||
return self._default_headers
|
||||
|
||||
def items(self):
|
||||
"""Return iterable of (header, value).
|
||||
|
||||
This method is called by http handlers just before WSGI's
|
||||
start_response() is called... but it is not called by
|
||||
django.test.ClientHandler! :'(
|
||||
|
||||
"""
|
||||
return super(DownloadResponse, self).items()
|
||||
|
||||
def get_basename(self):
|
||||
"""Return basename."""
|
||||
if self.basename:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Port of django-sendfile in django-downloadview."""
|
||||
|
||||
from django_downloadview.views.path import PathDownloadView
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ class SignedURLMixin:
|
|||
"""
|
||||
|
||||
def url(self, name):
|
||||
path = super().url(name)
|
||||
path = super(SignedURLMixin, self).url(name)
|
||||
signer = TimestampSigner()
|
||||
signature = signer.sign(path)
|
||||
return "{}?X-Signature={}".format(path, signature)
|
||||
|
|
|
|||
|
|
@ -71,13 +71,13 @@ class temporary_media_root(override_settings):
|
|||
settings.MEDIA_ROOT."""
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
self.options["MEDIA_ROOT"] = tmp_dir
|
||||
super().enable()
|
||||
super(temporary_media_root, self).enable()
|
||||
|
||||
def disable(self):
|
||||
"""Remove directory settings.MEDIA_ROOT then restore original
|
||||
setting."""
|
||||
shutil.rmtree(settings.MEDIA_ROOT)
|
||||
super().disable()
|
||||
super(temporary_media_root, self).disable()
|
||||
|
||||
|
||||
class DownloadResponseValidator(object):
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Utility functions that may be implemented in external packages."""
|
||||
|
||||
import re
|
||||
|
||||
charset_pattern = re.compile(r"charset=(?P<charset>.+)$", re.I | re.U)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Views to stream files."""
|
||||
|
||||
# API shortcuts.
|
||||
from django_downloadview.views.base import BaseDownloadView, DownloadMixin # NoQA
|
||||
from django_downloadview.views.http import HTTPDownloadView # NoQA
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
"""Base material for download views: :class:`DownloadMixin` and
|
||||
:class:`BaseDownloadView`"""
|
||||
|
||||
import calendar
|
||||
|
||||
from django.http import Http404, HttpResponseNotModified
|
||||
|
|
@ -103,9 +102,9 @@ class DownloadMixin(object):
|
|||
Else, fallbacks to default implementation, which uses
|
||||
:py:func:`django.views.static.was_modified_since`.
|
||||
|
||||
Django's ``was_modified_since`` function needs a datetime.
|
||||
It is passed the ``modified_time`` attribute from file
|
||||
wrapper. If file wrapper does not support this attribute
|
||||
Django's ``was_modified_since`` function needs a datetime and a size.
|
||||
It is passed ``modified_time`` and ``size`` attributes from file
|
||||
wrapper. If file wrapper does not support these attributes
|
||||
(``AttributeError`` or ``NotImplementedError`` is raised), then
|
||||
the file is considered as modified and ``True`` is returned.
|
||||
|
||||
|
|
@ -117,11 +116,12 @@ class DownloadMixin(object):
|
|||
modification_time = calendar.timegm(
|
||||
file_instance.modified_time.utctimetuple()
|
||||
)
|
||||
size = file_instance.size
|
||||
except (AttributeError, NotImplementedError) as e:
|
||||
print("!=======!", e)
|
||||
return True
|
||||
else:
|
||||
return was_modified_since(since, modification_time)
|
||||
return was_modified_since(since, modification_time, size)
|
||||
|
||||
def not_modified_response(self, *response_args, **response_kwargs):
|
||||
"""Return :class:`django.http.HttpResponseNotModified` instance."""
|
||||
|
|
@ -157,7 +157,7 @@ class DownloadMixin(object):
|
|||
except exceptions.FileNotFound:
|
||||
return self.file_not_found_response()
|
||||
# Respect the If-Modified-Since header.
|
||||
since = self.request.headers.get("if-modified-since", None)
|
||||
since = self.request.META.get("HTTP_IF_MODIFIED_SINCE", None)
|
||||
if since is not None:
|
||||
if not self.was_modified_since(self.file_instance, since):
|
||||
return self.not_modified_response(**response_kwargs)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Stream files given an URL, i.e. files you want to proxy."""
|
||||
|
||||
from django_downloadview.files import HTTPFile
|
||||
from django_downloadview.views.base import BaseDownloadView
|
||||
|
||||
|
|
@ -45,5 +44,5 @@ class HTTPDownloadView(BaseDownloadView):
|
|||
request_factory=self.get_request_factory(),
|
||||
name=self.get_basename(),
|
||||
url=self.get_url(),
|
||||
**self.get_request_kwargs(),
|
||||
**self.get_request_kwargs()
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Stream files that live in models."""
|
||||
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from django_downloadview.exceptions import FileNotFound
|
||||
|
|
@ -84,7 +83,7 @@ class ObjectDownloadView(SingleObjectMixin, BaseDownloadView):
|
|||
|
||||
def get_basename(self):
|
||||
"""Return client-side filename."""
|
||||
basename = super().get_basename()
|
||||
basename = super(ObjectDownloadView, self).get_basename()
|
||||
if basename is None:
|
||||
field = "basename"
|
||||
model_field = getattr(self, "%s_field" % field, False)
|
||||
|
|
@ -94,4 +93,4 @@ class ObjectDownloadView(SingleObjectMixin, BaseDownloadView):
|
|||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
return super().get(request, *args, **kwargs)
|
||||
return super(ObjectDownloadView, self).get(request, *args, **kwargs)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
""":class:`PathDownloadView`."""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.files import File
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Stream files from storage."""
|
||||
|
||||
from django.core.files.storage import DefaultStorage
|
||||
|
||||
from django_downloadview.files import StorageFile
|
||||
|
|
@ -15,6 +14,16 @@ class StorageDownloadView(PathDownloadView):
|
|||
#: Path to the file to serve relative to storage.
|
||||
path = None # Override docstring.
|
||||
|
||||
def get_path(self):
|
||||
"""Return path of the file to serve, relative to storage.
|
||||
|
||||
Default implementation simply returns view's :py:attr:`path` attribute.
|
||||
|
||||
Override this method if you want custom implementation.
|
||||
|
||||
"""
|
||||
return super(StorageDownloadView, self).get_path()
|
||||
|
||||
def get_file(self):
|
||||
"""Return :class:`~django_downloadview.files.StorageFile` instance."""
|
||||
return StorageFile(self.storage, self.get_path())
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Stream files that you generate or that live in memory."""
|
||||
|
||||
from django_downloadview.views.base import BaseDownloadView
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -23,4 +23,4 @@ optimizations.
|
|||
|
||||
.. target-notes::
|
||||
|
||||
.. _`Django`: https://www.djangoproject.com
|
||||
.. _`Django`: https://djangoproject.com
|
||||
|
|
|
|||
17
docs/conf.py
17
docs/conf.py
|
|
@ -1,10 +1,8 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""django-downloadview documentation build configuration file."""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import importlib.metadata
|
||||
|
||||
# Minimal Django settings. Required to use sphinx.ext.autodoc, because
|
||||
# django-downloadview depends on Django...
|
||||
from django.conf import settings
|
||||
|
|
@ -47,11 +45,14 @@ author_slug = re.sub(r"([\w_.-]+)", "-", author)
|
|||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
configuration_dir = os.path.dirname(__file__)
|
||||
documentation_dir = configuration_dir
|
||||
version_file = os.path.normpath(os.path.join(documentation_dir, "../VERSION"))
|
||||
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = importlib.metadata.version("django-downloadview")
|
||||
release = open(version_file).read().strip()
|
||||
# The short X.Y version.
|
||||
version = ".".join(release.split(".")[:2])
|
||||
version = ".".join(release.split(".")[0:1])
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
|
@ -88,10 +89,10 @@ htmlhelp_basename = "{project}doc".format(project=project_slug)
|
|||
# -- Options for sphinx.ext.intersphinx ---------------------------------------
|
||||
|
||||
intersphinx_mapping = {
|
||||
"python": ("https://docs.python.org/3", None),
|
||||
"python": ("https://docs.python.org/2.7", None),
|
||||
"django": (
|
||||
"https://docs.djangoproject.com/en/3.1/",
|
||||
"https://docs.djangoproject.com/en/3.1/_objects/",
|
||||
"https://docs.djangoproject.com/en/1.8/",
|
||||
"https://docs.djangoproject.com/en/1.8/_objects/",
|
||||
),
|
||||
"requests": ("https://requests.readthedocs.io/en/master/", None),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ Here are tips to migrate from `django-sendfile` to `django-downloadview`...
|
|||
* setup ``DOWNLOADVIEW_RULES``. It replaces ``SENDFILE_ROOT`` and can do
|
||||
more.
|
||||
* register ``django_downloadview.SmartDownloadMiddleware`` in
|
||||
``MIDDLEWARE``.
|
||||
``MIDDLEWARE_CLASSES``.
|
||||
|
||||
4. Change your tests if any. You can no longer use `django-senfile`'s
|
||||
``development`` backend. See :doc:`/testing` for `django-downloadview`'s
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ Django's builtins
|
|||
wrapper in :doc:`/views/path`.
|
||||
|
||||
* :class:`django.db.models.fields.files.FieldFile` wraps a file that is
|
||||
managed in a model. ``django-downloadview`` uses this wrapper in
|
||||
managed in a model. ``django-downloadview`` uses this wrapper in
|
||||
:doc:`/views/object`.
|
||||
|
||||
* :class:`django.core.files.base.ContentFile` wraps a bytes, string or
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ Setup XSendfile middlewares
|
|||
***************************
|
||||
|
||||
Make sure ``django_downloadview.SmartDownloadMiddleware`` is in
|
||||
``MIDDLEWARE`` of your `Django` settings.
|
||||
``MIDDLEWARE_CLASSES`` of your `Django` settings.
|
||||
|
||||
Example:
|
||||
|
||||
|
|
@ -128,4 +128,4 @@ setup.
|
|||
|
||||
.. target-notes::
|
||||
|
||||
.. _`Apache mod_xsendfile documentation`: https://tn123.org/mod_xsendfile/
|
||||
.. _`Apache mod_xsendfile documentation`: https://tn123.org/mod_xsendfile/
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ Setup XSendfile middlewares
|
|||
***************************
|
||||
|
||||
Make sure ``django_downloadview.SmartDownloadMiddleware`` is in
|
||||
``MIDDLEWARE`` of your `Django` settings.
|
||||
``MIDDLEWARE_CLASSES`` of your `Django` settings.
|
||||
|
||||
Example:
|
||||
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ Let's consider the following view:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/nginx/views.py
|
||||
:language: python
|
||||
:lines: 1-6, 8-17
|
||||
:lines: 1-6, 8-16
|
||||
|
||||
What is important here is that the files will have an ``url`` property
|
||||
implemented by storage. Let's setup an optimization rule based on that URL.
|
||||
|
|
@ -46,26 +46,26 @@ Setup XAccelRedirect middlewares
|
|||
********************************
|
||||
|
||||
Make sure ``django_downloadview.SmartDownloadMiddleware`` is in
|
||||
``MIDDLEWARE`` of your `Django` settings.
|
||||
``MIDDLEWARE_CLASSES`` of your `Django` settings.
|
||||
|
||||
Example:
|
||||
|
||||
.. literalinclude:: /../demo/demoproject/settings.py
|
||||
:language: python
|
||||
:lines: 62-69
|
||||
:lines: 63-70
|
||||
|
||||
Then set ``django_downloadview.nginx.XAccelRedirectMiddleware`` as
|
||||
``DOWNLOADVIEW_BACKEND``:
|
||||
|
||||
.. literalinclude:: /../demo/demoproject/settings.py
|
||||
:language: python
|
||||
:lines: 75
|
||||
:lines: 76
|
||||
|
||||
Then register as many ``DOWNLOADVIEW_RULES`` as you wish:
|
||||
|
||||
.. literalinclude:: /../demo/demoproject/settings.py
|
||||
:language: python
|
||||
:lines: 83-88
|
||||
:lines: 84-89
|
||||
|
||||
Each item in ``DOWNLOADVIEW_RULES`` is a dictionary of keyword arguments passed
|
||||
to the middleware factory. In the example above, we capture responses by
|
||||
|
|
@ -142,7 +142,7 @@ Here is what you could have in :file:`/etc/nginx/sites-available/default`:
|
|||
internal;
|
||||
# Location to files on disk.
|
||||
alias /var/www/files/;
|
||||
}
|
||||
}
|
||||
|
||||
# Proxy to Django-powered frontend.
|
||||
location / {
|
||||
|
|
@ -154,7 +154,7 @@ Here is what you could have in :file:`/etc/nginx/sites-available/default`:
|
|||
}
|
||||
|
||||
... where specific configuration is the ``location /optimized-download``
|
||||
section.
|
||||
section.
|
||||
|
||||
.. note::
|
||||
|
||||
|
|
@ -183,7 +183,7 @@ Add ``charset utf-8;`` in your nginx configuration file.
|
|||
``open() "path/to/something" failed (2: No such file or directory)``
|
||||
====================================================================
|
||||
|
||||
Check your ``settings.NGINX_DOWNLOAD_MIDDLEWARE_SOURCE_DIR`` in Django
|
||||
Check your ``settings.NGINX_DOWNLOAD_MIDDLEWARE_MEDIA_ROOT`` in Django
|
||||
configuration VS ``alias`` in nginx configuration: in a standard configuration,
|
||||
they should be equal.
|
||||
|
||||
|
|
@ -192,4 +192,4 @@ they should be equal.
|
|||
|
||||
.. target-notes::
|
||||
|
||||
.. _`Nginx X-accel documentation`: http://wiki.nginx.org/X-accel
|
||||
.. _`Nginx X-accel documentation`: http://wiki.nginx.org/X-accel
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ possible, file wrappers do not embed file data, in order to save memory.
|
|||
|
||||
Learn more about available file wrappers in :doc:`files`.
|
||||
|
||||
|
||||
|
||||
*****************************************************************
|
||||
Middlewares convert DownloadResponse into ProxiedDownloadResponse
|
||||
*****************************************************************
|
||||
|
|
|
|||
|
|
@ -13,11 +13,11 @@ There is no need to register this application in ``INSTALLED_APPS``.
|
|||
|
||||
|
||||
******************
|
||||
MIDDLEWARE
|
||||
MIDDLEWARE_CLASSES
|
||||
******************
|
||||
|
||||
If you plan to setup :doc:`reverse-proxy optimizations </optimizations/index>`,
|
||||
add ``django_downloadview.SmartDownloadMiddleware`` to ``MIDDLEWARE``.
|
||||
add ``django_downloadview.SmartDownloadMiddleware`` to ``MIDDLEWARE_CLASSES``.
|
||||
It is a response middleware. Move it after middlewares that compute the
|
||||
response content such as gzip middleware.
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ URLs, and they can then be verified with the supplied ``signature_required`` wra
|
|||
download = ObjectDownloadView.as_view(model=Document, file_field='file')
|
||||
|
||||
urlpatterns = [
|
||||
path('download/<str:slug>/', signature_required(download)),
|
||||
path('download/<str:slug>/', signature_required(download),
|
||||
]
|
||||
|
||||
Make sure to test the desired functionality after configuration.
|
||||
|
|
@ -91,7 +91,7 @@ Example:
|
|||
See :doc:`/optimizations/index` for a list of available backends (middlewares).
|
||||
|
||||
When ``django_downloadview.SmartDownloadMiddleware`` is in your
|
||||
``MIDDLEWARE``, this setting must be explicitely configured (no default
|
||||
``MIDDLEWARE_CLASSES``, this setting must be explicitely configured (no default
|
||||
value). Else, you can ignore this setting.
|
||||
|
||||
|
||||
|
|
@ -119,5 +119,5 @@ See :doc:`/optimizations/index` for details about builtin backends
|
|||
(middlewares) and their options.
|
||||
|
||||
When ``django_downloadview.SmartDownloadMiddleware`` is in your
|
||||
``MIDDLEWARE``, this setting must be explicitely configured (no default
|
||||
value). Else, you can ignore this setting.
|
||||
``MIDDLEWARE_CLASSES``, this setting must be explicitely configured (no default
|
||||
value). Else, you can ignore this setting.
|
||||
|
|
@ -41,3 +41,4 @@ Example, related to :doc:`StorageDownloadView demo </views/storage>`:
|
|||
.. literalinclude:: /../demo/demoproject/storage/tests.py
|
||||
:language: python
|
||||
:lines: 1-2, 8-12, 59-
|
||||
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ Setup a view to stream the ``file`` attribute:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/object/views.py
|
||||
:language: python
|
||||
:lines: 1-6
|
||||
:lines: 1-5, 7
|
||||
|
||||
:class:`~django_downloadview.views.object.ObjectDownloadView` inherits from
|
||||
:class:`~django.views.generic.detail.BaseDetailView`, i.e. it expects either
|
||||
|
|
@ -38,7 +38,7 @@ Setup a view to stream the ``file`` attribute:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/object/urls.py
|
||||
:language: python
|
||||
:lines: 1-7, 8-11, 27
|
||||
:lines: 1-7, 8-11, 20
|
||||
|
||||
|
||||
************
|
||||
|
|
@ -69,7 +69,7 @@ Then here is the code to serve "another_file" instead of the default "file":
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/object/views.py
|
||||
:language: python
|
||||
:lines: 1-4, 8-11
|
||||
:lines: 1-5, 10-12
|
||||
|
||||
|
||||
**********************************
|
||||
|
|
@ -90,7 +90,7 @@ Then you can configure the :attr:`ObjectDownloadView.basename_field` option:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/object/views.py
|
||||
:language: python
|
||||
:lines: 1-4, 13-17
|
||||
:lines: 1-5, 16-18
|
||||
|
||||
.. note::
|
||||
|
||||
|
|
|
|||
|
|
@ -24,8 +24,8 @@ Setup a view to stream files given path:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/path/views.py
|
||||
:language: python
|
||||
:lines: 1-13
|
||||
:emphasize-lines: 13
|
||||
:lines: 1-14
|
||||
:emphasize-lines: 14
|
||||
|
||||
|
||||
************
|
||||
|
|
|
|||
|
|
@ -18,20 +18,20 @@ Given a storage:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/storage/views.py
|
||||
:language: python
|
||||
:lines: 1, 4-5
|
||||
:lines: 1, 4-6
|
||||
|
||||
Setup a view to stream files in storage:
|
||||
|
||||
.. literalinclude:: /../demo/demoproject/storage/views.py
|
||||
:language: python
|
||||
:lines: 3-6, 8-9
|
||||
:lines: 3-5, 10
|
||||
|
||||
The view accepts a ``path`` argument you can setup either in ``as_view`` or
|
||||
via URLconfs:
|
||||
|
||||
.. literalinclude:: /../demo/demoproject/storage/urls.py
|
||||
:language: python
|
||||
:lines: 1-6, 7-11, 17
|
||||
:lines: 1-7, 8-10, 14
|
||||
|
||||
|
||||
************
|
||||
|
|
@ -56,7 +56,7 @@ uppercase:
|
|||
|
||||
.. literalinclude:: /../demo/demoproject/storage/views.py
|
||||
:language: python
|
||||
:lines: 3-5, 11-20
|
||||
:lines: 3-5, 13-20
|
||||
|
||||
|
||||
*************
|
||||
|
|
|
|||
153
setup.py
153
setup.py
|
|
@ -1,67 +1,98 @@
|
|||
#!/usr/bin/env python
|
||||
"""Python packaging."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from setuptools import setup
|
||||
from setuptools.command.test import test as TestCommand
|
||||
|
||||
|
||||
class Tox(TestCommand):
|
||||
"""Test command that runs tox."""
|
||||
|
||||
def finalize_options(self):
|
||||
TestCommand.finalize_options(self)
|
||||
self.test_args = []
|
||||
self.test_suite = True
|
||||
|
||||
def run_tests(self):
|
||||
import tox # import here, cause outside the eggs aren't loaded.
|
||||
|
||||
errno = tox.cmdline(self.test_args)
|
||||
sys.exit(errno)
|
||||
|
||||
|
||||
#: Absolute path to directory containing setup.py file.
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
setup(
|
||||
name="django-downloadview",
|
||||
use_scm_version={"version_scheme": "post-release"},
|
||||
setup_requires=["setuptools_scm"],
|
||||
description="Serve files with Django and reverse-proxies.",
|
||||
long_description=open(os.path.join(here, "README.rst")).read(),
|
||||
long_description_content_type="text/x-rst",
|
||||
classifiers=[
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"License :: OSI Approved :: BSD License",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Programming Language :: Python :: 3.14",
|
||||
"Framework :: Django",
|
||||
"Framework :: Django :: 4.2",
|
||||
"Framework :: Django :: 5.0",
|
||||
],
|
||||
keywords=" ".join(
|
||||
[
|
||||
"file",
|
||||
"stream",
|
||||
"download",
|
||||
"FileField",
|
||||
"ImageField",
|
||||
"x-accel",
|
||||
"x-accel-redirect",
|
||||
"x-sendfile",
|
||||
"sendfile",
|
||||
"mod_xsendfile",
|
||||
"offload",
|
||||
]
|
||||
),
|
||||
author="Benoît Bryon",
|
||||
author_email="benoit@marmelune.net",
|
||||
url="https://django-downloadview.readthedocs.io/",
|
||||
license="BSD",
|
||||
packages=[
|
||||
"django_downloadview",
|
||||
"django_downloadview.apache",
|
||||
"django_downloadview.lighttpd",
|
||||
"django_downloadview.nginx",
|
||||
"django_downloadview.views",
|
||||
],
|
||||
include_package_data=True,
|
||||
zip_safe=False,
|
||||
python_requires=">=3.8",
|
||||
install_requires=[
|
||||
# BEGIN requirements
|
||||
"Django>=4.2",
|
||||
"requests",
|
||||
# END requirements
|
||||
],
|
||||
extras_require={
|
||||
"test": ["tox"],
|
||||
},
|
||||
)
|
||||
|
||||
NAME = "django-downloadview"
|
||||
DESCRIPTION = "Serve files with Django and reverse-proxies."
|
||||
README = open(os.path.join(here, "README.rst")).read()
|
||||
VERSION = open(os.path.join(here, "VERSION")).read().strip()
|
||||
AUTHOR = "Benoît Bryon"
|
||||
EMAIL = "benoit@marmelune.net"
|
||||
LICENSE = "BSD"
|
||||
URL = "https://{name}.readthedocs.io/".format(name=NAME)
|
||||
CLASSIFIERS = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Framework :: Django",
|
||||
"License :: OSI Approved :: BSD License",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
]
|
||||
KEYWORDS = [
|
||||
"file",
|
||||
"stream",
|
||||
"download",
|
||||
"FileField",
|
||||
"ImageField",
|
||||
"x-accel",
|
||||
"x-accel-redirect",
|
||||
"x-sendfile",
|
||||
"sendfile",
|
||||
"mod_xsendfile",
|
||||
"offload",
|
||||
]
|
||||
PACKAGES = [NAME.replace("-", "_")]
|
||||
REQUIREMENTS = [
|
||||
# BEGIN requirements
|
||||
"Django>=1.11",
|
||||
"requests",
|
||||
"setuptools",
|
||||
# END requirements
|
||||
]
|
||||
ENTRY_POINTS = {}
|
||||
SETUP_REQUIREMENTS = ["setuptools"]
|
||||
TEST_REQUIREMENTS = ["tox"]
|
||||
CMDCLASS = {"test": Tox}
|
||||
EXTRA_REQUIREMENTS = {
|
||||
"test": TEST_REQUIREMENTS,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__": # Don't run setup() when we import this module.
|
||||
setup(
|
||||
name=NAME,
|
||||
version=VERSION,
|
||||
description=DESCRIPTION,
|
||||
long_description=README,
|
||||
classifiers=CLASSIFIERS,
|
||||
keywords=" ".join(KEYWORDS),
|
||||
author=AUTHOR,
|
||||
author_email=EMAIL,
|
||||
url=URL,
|
||||
license=LICENSE,
|
||||
packages=PACKAGES,
|
||||
include_package_data=True,
|
||||
zip_safe=False,
|
||||
install_requires=REQUIREMENTS,
|
||||
entry_points=ENTRY_POINTS,
|
||||
tests_require=TEST_REQUIREMENTS,
|
||||
cmdclass=CMDCLASS,
|
||||
setup_requires=SETUP_REQUIREMENTS,
|
||||
extras_require=EXTRA_REQUIREMENTS,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Test suite around :mod:`django_downloadview.api` and deprecation plan."""
|
||||
|
||||
from importlib import import_module, reload
|
||||
import unittest
|
||||
import warnings
|
||||
|
|
@ -101,6 +100,7 @@ class DeprecatedAPITestCase(django.test.SimpleTestCase):
|
|||
def test_nginx_x_accel_redirect_middleware(self):
|
||||
"XAccelRedirectMiddleware in settings triggers ImproperlyConfigured."
|
||||
with override_settings(
|
||||
MIDDLEWARE_CLASSES=["django_downloadview.nginx.XAccelRedirectMiddleware"],
|
||||
MIDDLEWARE=["django_downloadview.nginx.XAccelRedirectMiddleware"],
|
||||
):
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
|
|
@ -131,7 +131,7 @@ class DeprecatedAPITestCase(django.test.SimpleTestCase):
|
|||
reload(django_downloadview.nginx.settings)
|
||||
caught = False
|
||||
for warning_item in warning_list:
|
||||
if warning_item.category is DeprecationWarning:
|
||||
if warning_item.category == DeprecationWarning:
|
||||
if "deprecated" in str(warning_item.message):
|
||||
if setting_name in str(warning_item.message):
|
||||
caught = True
|
||||
|
|
@ -141,5 +141,5 @@ class DeprecatedAPITestCase(django.test.SimpleTestCase):
|
|||
if missed_warnings:
|
||||
self.fail(
|
||||
f"No DeprecationWarning raised about following settings: "
|
||||
f"{', '.join(missed_warnings)}."
|
||||
f'{", ".join(missed_warnings)}.'
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Tests around :mod:`django_downloadview.io`."""
|
||||
|
||||
import unittest
|
||||
|
||||
from django_downloadview import BytesIteratorIO, TextIteratorIO
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
"""Tests around project's distribution and packaging."""
|
||||
|
||||
import importlib.metadata
|
||||
import os
|
||||
import unittest
|
||||
|
||||
|
|
@ -26,15 +24,37 @@ class VersionTestCase(unittest.TestCase):
|
|||
self.fail("django_downloadview package has no __version__.")
|
||||
|
||||
def test_version_match(self):
|
||||
"""django_downloadview.__version__ matches importlib metadata."""
|
||||
distribution = importlib.metadata.distribution("django-downloadview")
|
||||
"""django_downloadview.__version__ matches pkg_resources info."""
|
||||
try:
|
||||
import pkg_resources
|
||||
except ImportError:
|
||||
self.fail(
|
||||
"Cannot import pkg_resources module. It is part of "
|
||||
"setuptools, which is a dependency of "
|
||||
"django_downloadview."
|
||||
)
|
||||
distribution = pkg_resources.get_distribution("django-downloadview")
|
||||
installed_version = distribution.version
|
||||
self.assertEqual(
|
||||
installed_version,
|
||||
self.get_version(),
|
||||
"Version mismatch: django_downloadview.__version__ "
|
||||
'is "%s" whereas importlib.metadata tells "%s". '
|
||||
'is "%s" whereas pkg_resources tells "%s". '
|
||||
"You may need to run ``make develop`` to update the "
|
||||
"installed version in development environment."
|
||||
% (self.get_version(), installed_version),
|
||||
)
|
||||
|
||||
def test_version_file(self):
|
||||
"""django_downloadview.__version__ matches VERSION file info."""
|
||||
version_file = os.path.join(project_dir, "VERSION")
|
||||
file_version = open(version_file).read().strip()
|
||||
self.assertEqual(
|
||||
file_version,
|
||||
self.get_version(),
|
||||
"Version mismatch: django_downloadview.__version__ "
|
||||
'is "%s" whereas VERSION file tells "%s". '
|
||||
"You may need to run ``make develop`` to update the "
|
||||
"installed version in development environment."
|
||||
% (self.get_version(), file_version),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Unit tests around responses."""
|
||||
|
||||
import unittest
|
||||
|
||||
from django_downloadview.response import DownloadResponse
|
||||
|
|
@ -20,13 +19,3 @@ class DownloadResponseTestCase(unittest.TestCase):
|
|||
self.assertIn(
|
||||
"filename*=UTF-8''espac%C3%A9%20.txt", headers["Content-Disposition"]
|
||||
)
|
||||
|
||||
def test_content_disposition_escaping(self):
|
||||
"""Content-Disposition headers escape special characters."""
|
||||
response = DownloadResponse(
|
||||
"fake file", attachment=True, basename=r'"malicious\file.exe'
|
||||
)
|
||||
headers = response.default_headers
|
||||
self.assertIn(
|
||||
r'filename="\"malicious\\file.exe"', headers["Content-Disposition"]
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Tests around :py:mod:`django_downloadview.sendfile`."""
|
||||
|
||||
from django.http import Http404
|
||||
import django.test
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
"""Tests around :mod:`django_downloadview.views`."""
|
||||
|
||||
import calendar
|
||||
from datetime import datetime
|
||||
import os
|
||||
|
|
@ -86,12 +85,13 @@ class DownloadMixinTestCase(unittest.TestCase):
|
|||
When calling file wrapper's ``was_modified_since()`` raises
|
||||
``NotImplementedError`` or ``AttributeError``,
|
||||
:meth:`django_downloadview.views.base.DownloadMixin.was_modified_since`
|
||||
tries to pass file wrapper's ``modified_time`` to
|
||||
tries to pass file wrapper's ``size`` and ``modified_time`` to
|
||||
:func:`django.views.static import was_modified_since`.
|
||||
|
||||
"""
|
||||
file_wrapper = mock.Mock()
|
||||
file_wrapper.was_modified_since = mock.Mock(side_effect=AttributeError)
|
||||
file_wrapper.size = mock.sentinel.size
|
||||
file_wrapper.modified_time = datetime.now()
|
||||
was_modified_since_mock = mock.Mock(return_value=mock.sentinel.was_modified)
|
||||
mixin = views.DownloadMixin()
|
||||
|
|
@ -106,6 +106,7 @@ class DownloadMixinTestCase(unittest.TestCase):
|
|||
was_modified_since_mock.assert_called_once_with(
|
||||
mock.sentinel.since,
|
||||
calendar.timegm(file_wrapper.modified_time.utctimetuple()),
|
||||
mock.sentinel.size,
|
||||
)
|
||||
|
||||
def test_was_modified_since_fallback(self):
|
||||
|
|
@ -116,7 +117,7 @@ class DownloadMixinTestCase(unittest.TestCase):
|
|||
* calling file wrapper's ``was_modified_since()`` raises
|
||||
``NotImplementedError`` or ``AttributeError``;
|
||||
|
||||
* and accessing ``modified_time`` from file wrapper raises
|
||||
* and accessing ``size`` and ``modified_time`` from file wrapper raises
|
||||
``NotImplementedError`` or ``AttributeError``...
|
||||
|
||||
... then
|
||||
|
|
|
|||
88
tox.ini
88
tox.ini
|
|
@ -1,63 +1,34 @@
|
|||
[tox]
|
||||
envlist =
|
||||
py{38,39,310,311,312}-dj{42}-{unittest,pytest,checkmigrations}
|
||||
py{310,311,312,313}-dj{50}-{unittest,pytest,checkmigrations}
|
||||
py{310,311,312,313}-dj{51}-{unittest,pytest,checkmigrations}
|
||||
py{310,311,312,313,314}-dj{52}-{unittest,pytest,checkmigrations}
|
||||
py{312,313,314}-dj{main}-{unittest,pytest,checkmigrations}
|
||||
lint
|
||||
sphinx
|
||||
readme
|
||||
envlist = py{36,37,38,39}-django{22,30,31},
|
||||
flake8, sphinx, readme
|
||||
|
||||
[gh-actions]
|
||||
python =
|
||||
3.8: py38, lint, sphinx, readme
|
||||
3.9: py39
|
||||
3.10: py310
|
||||
3.11: py311
|
||||
3.12: py312
|
||||
3.13: py313
|
||||
3.14: py314
|
||||
|
||||
[gh-actions:env]
|
||||
DJANGO =
|
||||
4.2: dj42
|
||||
5.0: dj50
|
||||
5.1: dj51
|
||||
5.2: dj52
|
||||
main: djmain
|
||||
[travis]
|
||||
python=
|
||||
3.8: py38, flake8, sphinx, readme
|
||||
|
||||
[testenv]
|
||||
deps =
|
||||
coverage
|
||||
dj42: Django>=4.2,<5.0
|
||||
dj50: Django>=5.0,<5.1
|
||||
dj51: django>=5.1,<5.2
|
||||
dj52: django>=5.2,<5.3
|
||||
djmain: https://github.com/django/django/archive/main.tar.gz
|
||||
pytest
|
||||
pytest-cov
|
||||
django22: Django>=2.2,<3.0
|
||||
django30: Django>=3.0,<3.1
|
||||
django31: Django>=3.1,<3.2
|
||||
nose
|
||||
py27: mock
|
||||
commands =
|
||||
pip install -e .
|
||||
pip install -e demo
|
||||
# doctests and unit tests
|
||||
pytest --cov=django_downloadview --cov=demoproject {posargs}
|
||||
# demo project integration tests
|
||||
coverage run --append {envbindir}/demo test {posargs: demoproject}
|
||||
coverage xml
|
||||
python -Wd {envbindir}/demo test --cover-package=django_downloadview --cover-package=demoproject {posargs: tests demoproject}
|
||||
pip freeze
|
||||
ignore_outcome =
|
||||
djmain: True
|
||||
|
||||
[testenv:lint]
|
||||
[testenv:flake8]
|
||||
deps =
|
||||
flake8
|
||||
black
|
||||
isort
|
||||
black
|
||||
isort
|
||||
commands =
|
||||
flake8 demo django_downloadview tests
|
||||
black --check demo django_downloadview tests
|
||||
isort --check-only --recursive demo django_downloadview tests
|
||||
black --check demo django_downloadview tests
|
||||
isort --check-only --recursive demo django_downloadview tests
|
||||
|
||||
[testenv:sphinx]
|
||||
deps =
|
||||
|
|
@ -69,20 +40,23 @@ whitelist_externals =
|
|||
make
|
||||
|
||||
[testenv:readme]
|
||||
description = Ensure README renders on PyPI
|
||||
deps = twine
|
||||
deps =
|
||||
docutils
|
||||
pygments
|
||||
commands =
|
||||
{envpython} setup.py -q sdist bdist_wheel
|
||||
twine check dist/*
|
||||
mkdir -p var/docs
|
||||
rst2html.py --exit-status=2 README.rst var/docs/README.html
|
||||
rst2html.py --exit-status=2 CONTRIBUTING.rst var/docs/CONTRIBUTING.html
|
||||
whitelist_externals =
|
||||
mkdir
|
||||
|
||||
[testenv:release]
|
||||
deps =
|
||||
wheel
|
||||
zest.releaser
|
||||
commands =
|
||||
fullrelease
|
||||
|
||||
[flake8]
|
||||
max-line-length = 88
|
||||
ignore = E203, W503
|
||||
|
||||
[coverage:run]
|
||||
source = django_downloadview,demo
|
||||
|
||||
[pytest]
|
||||
DJANGO_SETTINGS_MODULE = demoproject.settings
|
||||
addopts = --doctest-modules --ignore=docs/
|
||||
python_files = tests/*.py
|
||||
|
|
|
|||
Loading…
Reference in a new issue