-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
73 lines (56 loc) · 1.72 KB
/
app.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import io
from urllib.parse import parse_qsl, urlparse
import aiohttp
from aiohttp import web
from PIL import Image
from voluptuous import MultipleInvalid
from validation import schema
def main(host, port):
app = web.Application()
app.add_routes([web.get("/", handle)])
print("Server started at http://{}:{}".format(host, port))
web.run_app(app, host=host, port=port)
async def handle(request):
print(request.path_qs)
query_components = dict(parse_qsl(urlparse(request.path_qs).query))
try:
query_components = schema(query_components)
except MultipleInvalid:
raise web.HTTPBadRequest
url = query_components["source"]
resize = query_components["resize"]
data = await download_file(url)
try:
img = Image.open(data)
except OSError:
raise web.HTTPBadRequest
try:
img.thumbnail(resize)
except IndexError:
raise web.HTTPBadRequest
return await stream_from_image(img, request=request)
async def download_file(url):
async with aiohttp.ClientSession() as session:
req = await session.get(url)
if req.status == 404:
raise web.HTTPNotFound
fd = io.BytesIO()
while True:
chunk = await req.content.read(1024)
if not chunk:
break
fd.write(chunk)
fd.seek(0)
return fd
async def stream_from_image(img, request):
stream = web.StreamResponse()
stream.content_type = "image/" + img.format.lower()
await stream.prepare(request)
data = io.BytesIO()
img.save(data, format=img.format)
await stream.write(data.getvalue())
return stream
HOST = "0.0.0.0"
PORT = 8000
if __name__ == "__main__":
main(HOST, PORT)