LoginSignup
0
0

More than 1 year has passed since last update.

python cgiでInternal Server Error(500)が出た時の対処法

Last updated at Posted at 2021-09-12

概要

windows10で、pythonのcgiプログラムを実行する場合、1行目の書き方がサーバによって異なる場合があるので、覚書。
因みに、この1行目はシバン(shebang)といい、スクリプトを実行する際のインタプリタを指定しているそうです。 コメントが付いているので、関係ないかなと思っていたら意味あったのね。スミマセン。

環境

 ・OS    :windwos10
 ・使用サーバ:apache, pythonサーバ

apacheサーバ

 apacheサーバでpython cgiを実行する場合、1行目にはpythonの実行ファイルのフルパスを書く。2021年9月時点でのpythonの最新バージョンはpython39だが、この部分は必要に応じて書き換える。".exe"は省略可。

test.py
#!C:\Users\{user name}\AppData\Local\Programs\Python\Python39\python.exe
# -*- coding: utf-8 -*-

print ('Content-Type: text/html\n\n')
print ("Hello world!")

呼び出しurl

 htdocsフォルダ直下にファイルを配置した場合。

http://localhost/test.py

設定ファイルの変更

 変更後、サーバを再起動する。

httpd.conf
#-- htdocs以下のフォルダに配置する場合 --
<Directory "${SRVROOT}/htdocs">
    #修正(ExecCGI追加)
    Options Indexes FollowSymLinks ExecCGI
    AllowOverride None
    Require all granted
    #追記
    AddHandler cgi-script .cgi .py
</Directory>

pythonサーバ

上記の書き方でも動作するが、test.pyの1行目は、下記の書き方でも良い。
逆に言うと、下記の様に書いてapacheサーバで呼び出すとエラーになるので注意。
コードがそのまま表示される場合があるが、ajaxからのget, post呼び出しでは問題なく動作する(仕様?)。
python + ajax通信の記事については、こちらを参照ください。

test.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

print ('Content-Type: text/html\n\n')
print ("Hello world!")

サーバの起動コマンド

 pythonのcgiファイルが存在するフォルダで実行する("--cgi"が必要)。

$ python -m http.server --cgi 8000

呼び出しurl

http://localhost:8000/test.py

補足

pythonサーバでは、pyファイルは呼び出せますが、htmlファイルを表示させるとエラーになりました。
html, js, pythonなどのソースを丸ごと実行したい場合は、apacheサーバなどを使用した方が良いかも。
それか、electronを使用するとか?

結論

色々書きましたが、実際に開発を行う場合はDjangoなどのフレームワークを使った方が良いかと思います(汗
一応、動作の確認として。

参考

1行目のpython.exeのパスを最後まで書かないと実行できない(500エラー)
https://teratail.com/questions/242869

Pythonスクリプトの1行目の意味
https://qiita.com/nafuka/items/c97bfd2a4ca26e70e722

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