Ajax
前回、Pythonの数式(関数)を扱うライブラリsympyで、数値の代入や式の展開・因数分解、解の求め方、微分・積分の方法を解説しました。

今回はAjaxでPythonを実行する際、matplotlibやnumpy、pandasが動かなかったという件をお話しします。
ちなみに問題は解決していませんので、解決法を知っている方はぜひコメントをもらえると嬉しいです。
それでは始めていきましょう。
Ajaxのおさらい
まずはAjaxのおさらいからです。
前にも解説していますので、よかったらこちらの記事もどうぞ。

Ajaxを使うにはまず「jQuery」を読み込みます。
この記事を書いている時点での最新のコードはこちら。
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
もしかしたら古くなっているかもしれないので、最新版はjQueryのサイトで確認してください。
そしてAjaxで特定のURLに接続するには、こんな感じです。
$.ajax({
url: 'URL',
type: 'post',
data: ''
})
さらに返ってきたデータの処理や接続失敗した際の表示のために、「done」や「fail」の処理を追加します。
$.ajax({
url: 'URL',
type: 'post',
data: ''
}).done(function(){
成功した際の処理;
}).fail(function(){
失敗した際の処理;
});
今回は「Ajax_test1.py」という
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<meta charset="UTF-8">
</head>
<body>
<button id="start">Button</button>
<script>
$("#start").on("click", function(){
$.ajax({
url: 'Ajax_test1.py',
type: 'post',
data: ''
}).done(function(res){
console.log(res);
}).fail(function(){
alert('failed');
});
});
</script>
</body>
</html>
続いてPythonのプログラムです。
#!/pythonのパス/python
import sys
recieve = sys.stdin.readline()
print('Content-type: text/html\n')
def main():
print("test")
if __name__ == '__main__':
main()
ここで重要なのは、出力の最初は「print(‘Content-type: text/html\n’)」とすることです。
これでサーバーにアップロードし、アクセスした後、ボタンをクリックすると「test」が表示されます。
それでは今回の問題を見ていきましょう。
特定のライブラリをインポートするとエラー
今回発生した問題はPythonのプログラム側で特定のライブラリをインポートするとエラーになるというものです。
一番最初に試したのは「matplotlib」でした。
ということでこんな感じ。
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<meta charset="UTF-8">
</head>
<body>
<button id="start">Button</button>
<script>
$("#start").on("click", function(){
$.ajax({
url: 'Ajax_test2.py',
type: 'post',
data: ''
}).done(function(res){
console.log(res);
}).fail(function(){
alert('failed');
});
});
</script>
</body>
</html>
#!/pythonのパス/python
import sys
import matplotlib
recieve = sys.stdin.readline()
print('Content-type: text/html\n')
def main():
print("test_matplotlib")
if __name__ == '__main__':
main()
これを実行するとエラーとなってしまいました。

ちなみに「numpy」や「pandas」でも同じく500エラーが発生します。
「os」や「random」は問題なくインポートできるので、外部ライブラリをインポートすることができてないようです。
結構色々と粘ったのですが、エラーの内容が詳しくわからないことから、まだこの問題を解消できていません。
もし対処方法をご存知の方がいらっしゃいましたら、コメント欄にでもご連絡いただけると嬉しいです。
次回からはJavaScriptのようにPythonのプログラムをHTML上にPyScriptを使ってみたのでそのお話をしていきます。
次回はPyScriptで文字を出力する方法を紹介していきます。

ではでは今回はこんな感じで。
コメント