This repository was archived by the owner on Jul 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
68 lines (61 loc) · 2.54 KB
/
api.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
from quart import Blueprint, request, url_for, send_file, redirect
from style import Style, DEFAULT_STYLE
import data_response as response
from PIL import Image
import aiofiles
from pathlib import Path
from string import ascii_letters
import random
import time
import json
SAVE_PATH = Path('tmp_images')
style = Style()
api = Blueprint('API', __name__)
abcs = ascii_letters + '0123456789'
if not SAVE_PATH.exists():
SAVE_PATH.mkdir()
@api.route('/image/<string:filename>')
async def get_images(filename):
file_path = Path('tmp_images') / filename
if not file_path.exists():
return response.not_found(filename)
return await send_file(file_path)
@api.route('/generator/user_info', methods=['GET', 'POST'])
async def gen_info_card():
if request.method == 'POST':
args: dict = dict(request.args)
try:
data = json.loads(await request.data)
except json.decoder.JSONDecodeError as err:
return response.data_error(err)
cur_style = args.get("style") if "style" in args else DEFAULT_STYLE
if cur_style not in style.styles:
return response.style_err(cur_style)
try:
t1 = time.time()
generated = (await style.user_info(cur_style, data, **args)).convert('RGB')
t2 = time.time()
except KeyError:
return response.data_error("Data is not in standard format")
pic_type = args.get("type").lower() if "type" in args else 'jpg'
filename = time.strftime('%Y%m%d%H%M%S-' + ''.join(random.choices(abcs, k=8)) + '.' + pic_type)
filepath = SAVE_PATH / filename
quality = args.get("quality") if "quality" in args else 100
if isinstance(generated, Image.Image):
try:
generated.save(filepath, quality=quality)
except Exception as err:
if str(err) == 'Invalid quality setting':
generated.save(filepath)
else:
return response.generator_error(err)
return response.success(url_for('.get_images', filename=filename), time=t2 - t1)
if isinstance(generated, bytes):
async with aiofiles.open(filepath, 'rb') as f:
await f.write(generated)
return response.success(url_for('.get_images', filename=filename), time=t2 - t1)
if isinstance(generated, str):
return response.success(generated, "Text")
return response.success(generated, "Data")
if request.method == 'GET':
return redirect(url_for('Page.query_user_info'))