0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでhtmlとjavascriptを直接書きたい!

Last updated at Posted at 2023-02-19

作った!!!

それを使ったサンプル!

QRコード生成器!!
qrcode.gif
ソース

簡素なチャット!!
chat.gif
ソース

インストール!

pip install pytohtml

書き方!

QRコード生成器の中身を見てみよう

# インポート省略
app = Flask(__name__)

this: object
window: object
fetch: object
JSON: object

class document:
    def getElementById(self, id: str): ...

class RequestData(typing.TypedDict):
    content: str

@util.api(app, '/api/generate', json=False, methods=['POST'])
def generate_qr():
    data: RequestData = request.json
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
        image_factory=PilImage
    )
    qr.add_data(data['content'])
    qr.make(fit=True)

    image = qr.make_image(fill_color='#3da0b4', back_color="white")

    buffered = BytesIO()
    image.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue())
    return b'data:image/png;base64,' + img_str

@app.route('/')
def index():
    @js
    def main():
        async def generate():
            data = document.getElementById('qr_data')
            image = document.getElementById('result')
            await generate_qr({
                'content': data.value
            })\
                .then(lambda response: response.text())\
                .then(lambda text: image.setAttribute('src', text))

    return html(lang='en')[
        util.cache(lambda: head[
            title['QR Code Generator'],
            SASS(href='styles_qr.scss'),
            Script[generate_qr],
            Script[main]
        ]),
        body[
            div(className='container')[
                div[
                    input(id='qr_data', name='qr_data', placeholder='data here'),
                    button(onclick='generate()')['>']
                ],
                img(id='result', src='', title='')
            ]
        ]
    ].render()

if __name__ == '__main__':
    app.run(debug=True, port=80)

まずhtmlを__call__と__getitem__でできるだけそれっぽく書けるようにしてます!
そしてindex()のmain()の中でjavascriptを記述して、
Script[main]で埋め込んでますん

どうやってjavascriptに変換してるかはこれで雑に詳細書いた!

ちなみに

属性も型ヒントで補完できます
image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?