From c47b0c4425adf3c8ec918448fcf5dd71d897d47f Mon Sep 17 00:00:00 2001 From: felinae98 <731499577@qq.com> Date: Fri, 26 Feb 2021 20:16:16 +0800 Subject: [PATCH] use tempfile, test --- src/plugins/nonebot_hk_reporter/utils.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/plugins/nonebot_hk_reporter/utils.py b/src/plugins/nonebot_hk_reporter/utils.py index 509466b..b43329d 100644 --- a/src/plugins/nonebot_hk_reporter/utils.py +++ b/src/plugins/nonebot_hk_reporter/utils.py @@ -7,6 +7,7 @@ import base64 from pyppeteer import launch from html import escape from hashlib import sha256 +from tempfile import NamedTemporaryFile from .plugin_config import plugin_config @@ -44,14 +45,14 @@ class Render(metaclass=Singleton): return str(data) async def text_to_pic(self, text: str) -> str: - hash_text = sha256(text.encode()).hexdigest()[:20] lines = text.split('\n') parsed_lines = list(map(lambda x: '

{}

'.format(escape(x)), lines)) html_text = '
{}
'.format(''.join(parsed_lines)) - with open('/tmp/text-{}.html'.format(hash_text), 'w') as f: - f.write(html_text) - data = await self.render('file:///tmp/text-{}.html'.format(hash_text), target='div') - os.remove('/tmp/text-{}.html'.format(hash_text)) + with NamedTemporaryFile('wt', suffix='.html', delete=False) as tmp: + tmp_path = tmp.name + tmp.write(html_text) + data = await self.render('file://{}'.format(tmp_path), target='div') + os.remove(tmp_path) return data async def text_to_pic_cqcode(self, text:str) -> str: @@ -68,3 +69,8 @@ async def parse_text(text: str): else: return text +async def test(): + ren = Render() + res = await ren.text_to_pic('12333333') + logger.debug(res) +nonebot.get_driver().on_startup(test)