django-csv-downloads


Namedjango-csv-downloads JSON
Version 1.3 PyPI version JSON
download
home_pagehttps://github.com/yunojuno/django-csv-downloads
SummaryDjango app for enabling and tracking CSV downloads
upload_time2023-11-13 18:34:07
maintainerYunoJuno
docs_urlNone
authorYunoJuno
requires_python>=3.8,<4.0
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Django CSV Downloads

Django app for tracking queryset-backed CSV downloads

### Version support

The current version of the this app support **Python 3.8+** and **Django
3.2+**

## What does this app do?

This app is used to track user downloads of CSVs that are derived from
Django QuerySets. You provide the filename, queryset and the list of
columns that you want to output.

It has a single model (`CsvDownload`) that tracks downloads and stores
the user, filename, row count and timestamp.

## Usage

The recommended way to use this app is to rely on
`django_csv.views.download_csv`, which wraps up the creation of the
download object and the generation of the CSV itself:

```python
# DISPLAY PURPOSES ONLY: DO NOT ENABLE USER DATA DOWNLOADS IN PRODUCTION
def download_users(request: HttpRequest) -> HttpResponse:
    data = User.objects.all()
    columns = ("first_name", "last_name", "email")
    return download_csv(request.user, "users.csv", data, *columns)
```

## Settings

There is a `CSV_DOWNLOAD_MAX_ROWS` setting that is used to truncate
output. Defaults to 10000. This is a backstop, and can be overridden on
a per use basis.

## Examples

**Caution:** All of these examples invÄolve the User model as it's
ubiquitous - DO NOT DO THIS ON A PRODUCTION ENVIRONMENT.

Example of writing a QuerySet to a file:

```python
>>> data = User.objects.all()
>>> columns = ("first_name", "last_name", "email")
>>> with open('users.csv', 'w') as csvfile:
>>>     csv.write_csv(csvfile, data, *columns)
10  #<--- row count
```

adding a custom header:

```python
>>> data = User.objects.all()
>>> columns = ("first_name", "last_name", "email")
>>> column_headers = ("given_name", "family_name", "email_address")
>>> with open('users.csv', 'w') as csvfile:
>>>     csv.write_csv(csvfile, data, *columns, column_headers=column_headers)
10
```

Example of writing to an HttpResponse:

```python
>>> response = HttpResponse(content_type="text/csv")
>>> response["Content-Disposition"] = 'attachment; filename="users.csv"'
>>> csv.write_csv(response, data, *columns)
10
```

Example of writing to an in-memory text buffer:

```python
>>> buffer = io.StringIO()
>>> csv.write_csv(buffer, data, *columns)
10
```

Example of writing directly to S3:

```python
>>> with s3.s3_upload("bucket_name", "object_key") as buffer:
...     csv.write_csv(fileobj, queryset, *columns)
10
>>> # one-line convenience function
>>> s3.write_csv_s3("bucket_name/object_key", queryset, *columns)
10
```

Example of writing directly to SFTP:

```python
# requires a paramiko.SFTPClient to have been created / connected.
>>> with sft.sftp_upload(client, remote_filepath) as fileobj:
...     write_csv(fileobj, queryset, *columns)
10
>>> # one-line convenience function
>>> sftp.write_csv_sftp("sftp://user:pass@host:port/path", queryset, *columns)
10
```

Example of a custom admin action to download User data:

```python
class CustomUserAdmin(UserAdmin):

    actions = ['download']
    csv_fields = ("first_name", "last_name", "email", "is_staff")
    csv_filename = "users.csv"

    def download(self, request, queryset):
        """Download selected users as a CSV."""
        return download_csv(
            user=request.user,
            filename=CustomUserAdmin.csv_filename,
            queryset=queryset,
            *CustomUserAdmin.csv_fields
        )

    download.short_description = "Download selected users"
```

Example CBV that restricts queryset based on request.user:

```python
class DownloadUsers(CsvDownloadView):

    def has_permission(self, request: HttpRequest) -> bool:
        return request.user.is_authenticated

    def get_queryset(self, request: HttpRequest) -> QuerySetWriter:
        """Allow superusers to download Users."""
        if request.user.is_superuser:
            return User.objects.all().order_by("first_name", "last_name")
        return User.objects.none()

    def get_filename(self, request: HttpRequest) -> str:
        return "users.csv"

    def get_columns(self, request: HttpRequest) -> str:
        return ("first_name", "last_name")
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/yunojuno/django-csv-downloads",
    "name": "django-csv-downloads",
    "maintainer": "YunoJuno",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "code@yunojuno.com",
    "keywords": "",
    "author": "YunoJuno",
    "author_email": "code@yunojuno.com",
    "download_url": "https://files.pythonhosted.org/packages/3a/bb/e24a6c54235fb4affc03ee01543234aaf6608788fc9101237ec2a6f9f583/django_csv_downloads-1.3.tar.gz",
    "platform": null,
    "description": "# Django CSV Downloads\n\nDjango app for tracking queryset-backed CSV downloads\n\n### Version support\n\nThe current version of the this app support **Python 3.8+** and **Django\n3.2+**\n\n## What does this app do?\n\nThis app is used to track user downloads of CSVs that are derived from\nDjango QuerySets. You provide the filename, queryset and the list of\ncolumns that you want to output.\n\nIt has a single model (`CsvDownload`) that tracks downloads and stores\nthe user, filename, row count and timestamp.\n\n## Usage\n\nThe recommended way to use this app is to rely on\n`django_csv.views.download_csv`, which wraps up the creation of the\ndownload object and the generation of the CSV itself:\n\n```python\n# DISPLAY PURPOSES ONLY: DO NOT ENABLE USER DATA DOWNLOADS IN PRODUCTION\ndef download_users(request: HttpRequest) -> HttpResponse:\n    data = User.objects.all()\n    columns = (\"first_name\", \"last_name\", \"email\")\n    return download_csv(request.user, \"users.csv\", data, *columns)\n```\n\n## Settings\n\nThere is a `CSV_DOWNLOAD_MAX_ROWS` setting that is used to truncate\noutput. Defaults to 10000. This is a backstop, and can be overridden on\na per use basis.\n\n## Examples\n\n**Caution:** All of these examples inv\u00e5olve the User model as it's\nubiquitous - DO NOT DO THIS ON A PRODUCTION ENVIRONMENT.\n\nExample of writing a QuerySet to a file:\n\n```python\n>>> data = User.objects.all()\n>>> columns = (\"first_name\", \"last_name\", \"email\")\n>>> with open('users.csv', 'w') as csvfile:\n>>>     csv.write_csv(csvfile, data, *columns)\n10  #<--- row count\n```\n\nadding a custom header:\n\n```python\n>>> data = User.objects.all()\n>>> columns = (\"first_name\", \"last_name\", \"email\")\n>>> column_headers = (\"given_name\", \"family_name\", \"email_address\")\n>>> with open('users.csv', 'w') as csvfile:\n>>>     csv.write_csv(csvfile, data, *columns, column_headers=column_headers)\n10\n```\n\nExample of writing to an HttpResponse:\n\n```python\n>>> response = HttpResponse(content_type=\"text/csv\")\n>>> response[\"Content-Disposition\"] = 'attachment; filename=\"users.csv\"'\n>>> csv.write_csv(response, data, *columns)\n10\n```\n\nExample of writing to an in-memory text buffer:\n\n```python\n>>> buffer = io.StringIO()\n>>> csv.write_csv(buffer, data, *columns)\n10\n```\n\nExample of writing directly to S3:\n\n```python\n>>> with s3.s3_upload(\"bucket_name\", \"object_key\") as buffer:\n...     csv.write_csv(fileobj, queryset, *columns)\n10\n>>> # one-line convenience function\n>>> s3.write_csv_s3(\"bucket_name/object_key\", queryset, *columns)\n10\n```\n\nExample of writing directly to SFTP:\n\n```python\n# requires a paramiko.SFTPClient to have been created / connected.\n>>> with sft.sftp_upload(client, remote_filepath) as fileobj:\n...     write_csv(fileobj, queryset, *columns)\n10\n>>> # one-line convenience function\n>>> sftp.write_csv_sftp(\"sftp://user:pass@host:port/path\", queryset, *columns)\n10\n```\n\nExample of a custom admin action to download User data:\n\n```python\nclass CustomUserAdmin(UserAdmin):\n\n    actions = ['download']\n    csv_fields = (\"first_name\", \"last_name\", \"email\", \"is_staff\")\n    csv_filename = \"users.csv\"\n\n    def download(self, request, queryset):\n        \"\"\"Download selected users as a CSV.\"\"\"\n        return download_csv(\n            user=request.user,\n            filename=CustomUserAdmin.csv_filename,\n            queryset=queryset,\n            *CustomUserAdmin.csv_fields\n        )\n\n    download.short_description = \"Download selected users\"\n```\n\nExample CBV that restricts queryset based on request.user:\n\n```python\nclass DownloadUsers(CsvDownloadView):\n\n    def has_permission(self, request: HttpRequest) -> bool:\n        return request.user.is_authenticated\n\n    def get_queryset(self, request: HttpRequest) -> QuerySetWriter:\n        \"\"\"Allow superusers to download Users.\"\"\"\n        if request.user.is_superuser:\n            return User.objects.all().order_by(\"first_name\", \"last_name\")\n        return User.objects.none()\n\n    def get_filename(self, request: HttpRequest) -> str:\n        return \"users.csv\"\n\n    def get_columns(self, request: HttpRequest) -> str:\n        return (\"first_name\", \"last_name\")\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Django app for enabling and tracking CSV downloads",
    "version": "1.3",
    "project_urls": {
        "Documentation": "https://github.com/yunojuno/django-csv-downloads",
        "Homepage": "https://github.com/yunojuno/django-csv-downloads",
        "Repository": "https://github.com/yunojuno/django-csv-downloads"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d65994f77163b77027cbac6e002dedd4cf2d9b51aa53eb9fb4faa4197d2b4d3f",
                "md5": "2e88c0aed7284142b46b40127a08485e",
                "sha256": "240bc2c16a294a2ab7f52a6d157d29d4d0516b9d20890b2a3bffd6e4e2f57c27"
            },
            "downloads": -1,
            "filename": "django_csv_downloads-1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2e88c0aed7284142b46b40127a08485e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 12883,
            "upload_time": "2023-11-13T18:33:53",
            "upload_time_iso_8601": "2023-11-13T18:33:53.747202Z",
            "url": "https://files.pythonhosted.org/packages/d6/59/94f77163b77027cbac6e002dedd4cf2d9b51aa53eb9fb4faa4197d2b4d3f/django_csv_downloads-1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3abbe24a6c54235fb4affc03ee01543234aaf6608788fc9101237ec2a6f9f583",
                "md5": "66b84596b7a9000e9a7def14dcde4d53",
                "sha256": "7e42d6823481ad5f6ba9998d7bb4af17738abac92aee263635c6f1e82dac3168"
            },
            "downloads": -1,
            "filename": "django_csv_downloads-1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "66b84596b7a9000e9a7def14dcde4d53",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 10282,
            "upload_time": "2023-11-13T18:34:07",
            "upload_time_iso_8601": "2023-11-13T18:34:07.383463Z",
            "url": "https://files.pythonhosted.org/packages/3a/bb/e24a6c54235fb4affc03ee01543234aaf6608788fc9101237ec2a6f9f583/django_csv_downloads-1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-13 18:34:07",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yunojuno",
    "github_project": "django-csv-downloads",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "django-csv-downloads"
}
        
Elapsed time: 0.13788s