common.title

Docs
Quantum Circuit
TYTAN CLOUD

QUANTUM GAMING


Overview
Contact
Event
Project
Research

Terms of service (Web service)

Terms of service (Quantum and ML Cloud service)

Privacy policy


Sign in
Sign up
common.title

flaskとajax最小構成備忘録

Yuichiro Minato

2020/11/11 07:24

2

python flaskで量子アプリを作りたい場合に、フロントのhtmlとflaskのあたりを簡単に置いておきます。基本的には、

1、インターフェイスをhtmlで書いてボタンを押したらpythonバックエンドがわに投げる。

2、pythonのflaskで受けて、処理を返す。

3、処理を受けてhtml側で表示をする。

1、htmlからajaxでpython側に投げる

とりあえずjqueryを読み込んで、ajaxでgetを投げます。戻ってきたのをそのまま表示。

<!doctype html>
<html>
<head>
</head>
<body>
<button id="btn" type="button">button</button>

<script
 src="https://code.jquery.com/jquery-3.3.1.min.js"
 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
 crossorigin="anonymous"></script>

<script>
$(function(){
 $('#btn').click(function(){
 $.ajax({
  type : 'GET',
  url  : 'http://エンドポイント:5000/api/'
 }).done(function(data, textStatus, jqXHR) {
  alert(data)
 });
 });
})
</script>

</body>
</html>

2、pythonのflaskで受けて、処理を返す。

まずはレンダリングでhtmlをレンダリングします。

また、受ける側のAPIのエンドポイント(URL)は、サーバーのURL:5000/api/とします。

そのまま"test"という文字列を返します。

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def hello():
 return render_template("test.html")

@app.route('/api/')
def main():
 return "test"

if __name__ == '__main__':
    app.run(host='0.0.0.0')

3、html側で表示

先ほどのhtml側で、alertが設定されていますので、無事戻って来れば"test"が表示されます。

以上です。

© 2025, blueqat Inc. All rights reserved