File: aiohttp_gridfs_example.py

package info (click to toggle)
python-motor 3.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,572 kB
  • sloc: python: 12,252; javascript: 137; makefile: 74; sh: 8
file content (54 lines) | stat: -rw-r--r-- 1,545 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Serve pre-compressed static content from GridFS with aiohttp.

Requires Python 3.5 or later and aiohttp 3.0 or later.

Start a MongoDB server on its default port, run this script, and visit:

http://localhost:8080/fs/my_file
"""
# -- include-start --
import asyncio
import gzip
import tempfile

import aiohttp.web

from motor.aiohttp import AIOHTTPGridFS
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorGridFSBucket

client = AsyncIOMotorClient()


# Use Motor to put compressed data in GridFS, with filename "my_file".
async def put_gridfile():
    with tempfile.TemporaryFile() as tmp:
        with gzip.GzipFile(mode="wb", fileobj=tmp) as gzfile:
            for _ in range(10):
                gzfile.write(b"Nonesuch nonsense\n")

        gfs = AsyncIOMotorGridFSBucket(client.my_database)
        tmp.seek(0)
        await gfs.upload_from_stream(
            filename="my_file", source=tmp, metadata={"contentType": "text", "compressed": True}
        )


asyncio.run(put_gridfile())


# Add "Content-Encoding: gzip" header for compressed data.
def gzip_header(response, gridout):
    if gridout.metadata.get("compressed"):
        response.headers["Content-Encoding"] = "gzip"


gridfs_handler = AIOHTTPGridFS(client.my_database, set_extra_headers=gzip_header)

app = aiohttp.web.Application()

# The GridFS URL pattern must have a "{filename}" variable.
resource = app.router.add_resource("/fs/{filename}")
resource.add_route("GET", gridfs_handler)
resource.add_route("HEAD", gridfs_handler)

aiohttp.web.run_app(app)