【GCP】Debian9+Apache+Python3.9.1で「Hello World!」

2021年1月21日木曜日

GCP Python Webサーバ

t f B! P L

 


その8.Python3.9.1で「Hello World!」









HTMLPHPで「Hellow World!」を出したので、今回はPythonを使って表示してみようと思います。


最新バージョンのPythonで「Hellow World!」できるところまでやります。





環境情報


Debian GNU/Linux 9 (stretch)
Apache/2.4.25 (Debian)
Python 2.7.13

※ この時点でPython 3.5.3 がインストール済みですがPython2が有効になっています





CGI を有効にして Python スクリプトが利用できるように設定する



Pythonは既にインストールされているので、CGIを有効にします。

対象のサーバにSSH接続してroot権限で下記コマンドを実行します。



■CGI モジュールを有効にします。

# a2enmod cgi


CGI モジュールを有効にすると、

デフォルトで [/usr/lib/cgi-bin] 配下が CGI 実行許可されます。


たとえば、
/usr/lib/cgi-bin/index.cgi スクリプトを配置して、

http://(外部IPアドレス)/cgi-bin/index.cgi

とすれば実行結果を表示することができます。



今回は、ドキュメントルートの下にフォルダを作ってそこにPythonのスクリプトを配置して実行できるように設定します。



新しいconfファイルを作成する

下記コマンドを実行して新規ファイルを作成編集画面を開きます。

※root権限で開く。なければsudo ~で



新規ファイル名:cgi-enabled.conf

# vi /etc/apache2/conf-available/cgi-enabled.conf



ファイルの中身を下記のようにします。

<Directory "/var/www/html/cgi-enabled">
    Options +ExecCGI
    AddHandler cgi-script .cgi .py
</Directory>


vimで編集するには、
[i]キー → (編集) → [ESC]キー → [:wq]を入力して終了です。



編集して保存できたら、ドキュメントルートの下にフォルダを新規作成します。


フォルダ名:cgi-enabled

# mkdir /var/www/html/cgi-enabled



作成したconfファイルを有効にします。

# a2enconf cgi-enabled



Apacheを再起動します。

# systemctl restart apache2





■Pythonスクリプトを配置する

先ほどと同じように、vimでスクリプトファイルを新規作成して編集画面を開きます。


ファイル名:hellow_world.py

# vi /var/www/html/cgi-enabled/hellow_world.py



ファイルの中身を下記の内容に編集します。

#!/usr/bin/env python

print "Content-type: text/html\n\n"
print "<html>\n<body>"
print "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">"
print "Hellow World!"
print "</div>\n</body>\n</html>"



スクリプトファイルを保存して終了します。



作成したスクリプトファイルの権限を変更します。

# chmod 705 /var/www/html/cgi-enabled/hellow_world.py




■ブラウザでアクセスする

下記URLをブラウザに入力します。

http://(外部IPアドレス)/cgi-enabled/hellow_world.py




↑のように表示されれば成功です。

これでPython2での「Hellow World!」表示が終了しました。



もし、500エラーが出たらファイルの改行コードCRLFになっているかもしれないのでLFに変更して再読み込みを試してください





最新のPython3をインストールする



下記サイトでPythonの最新バージョンを確認します。






現時点では安定版は Python 3.9.1 のようです。



■インストールに必要なパッケージをダウンロードする

ビルドするために必要な色々なものです。

# apt -y install zlib1g-dev libssl-dev libreadline-dev libsqlite3-dev libbz2-dev libncurses5-dev libgdbm-dev liblzma-dev tk-dev zlibc





■最新版のソースをダウンロードしてビルドする


/usr/local/src フォルダにソースの圧縮ファイルをダウンロードして展開します。


# cd /usr/local/src
# wget https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz
# tar zxvf Python-3.9.1.tgz




展開されたフォルダに移動してビルドします。

# cd  Python-3.9.1
# ./configure --prefix=/usr/local/python391 --with-ensurepip
# make -j$(grep '^processor' /proc/cpuinfo | wc -l)



ビルドが正常に終了したらインストールします。

# make altinstall




■Pythonの代替えリストを作成

システム全体でpythonのバージョンを変更するには、update-alternativesコマンドを使用します。

まずは、切り替える対象のPythonバージョンをリストへ登録します。


Python2.7 を 番号に登録
# update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1


Python3.5 を 番号に登録
# update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2


Pyrthon3.9 を 番号 に登録
# update-alternatives --install /usr/bin/python python /usr/local/python391/bin/python3.9 3

※最後に登録したものがリストのデフォルトバージョンになります




代替えリストを表示します。

# update-alternatives --list python
/usr/bin/python2.7
/usr/bin/python3.5
/usr/local/python391/bin/python3.9


Pythonのバージョンを確認する。

# python -V
Python 3.9.1



Pythonのバージョンを切り替えてみる

# update-alternatives --config python
There are 3 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                                Priority   Status
------------------------------------------------------------
* 0            /usr/local/python391/bin/python3.9   3         auto mode
  1            /usr/bin/python2.7                   1         manual mode
  2            /usr/bin/python3.5                   2         manual mode
  3            /usr/local/python391/bin/python3.9   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in manual mode

# python -V
Python 2.7.13

番号1にスイッチしたのでバージョンが 2.7.13 になっています。




この状態でもう一度ブラウザで確認してみます。

http://(外部IPアドレス)/cgi-enabled/hellow_world.py



問題なさそうです。

※Python3での確認は後ほどやります



■pipを更新する

念のため最新にしておきます。

# cd /usr/local/python391/bin
# ./pip3.9 install --upgrade pip





Python3.9.1で「Hellow World!」を表示する


Pythonのバージョンを切り替えます。

# update-alternatives --config python
There are 3 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                                Priority   Status
------------------------------------------------------------
  0            /usr/local/python391/bin/python3.9   3         auto mode
* 1            /usr/bin/python2.7                   1         manual mode
  2            /usr/bin/python3.5                   2         manual mode
  3            /usr/local/python391/bin/python3.9   3         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0
update-alternatives: using /usr/local/python391/bin/python3.9 to provide /usr/bin/python (python) in auto mode

# python -V
Python 3.9.1



試しにブラウザで表示してみると、、

http://(外部IPアドレス)/cgi-enabled/hellow_world.py




500エラーが出ます。



エラーログを確認します

# tail -f /var/log/apache2/error.log
出力(抜粋):
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Content-type: text/html\n\n")?
[Fri Jan 22 11:50:35.889245 2021] [cgid:error] [pid 808] [client 52.197.211.37:53379] End of script output before headers: hellow_world.py


Pythonの構文エラーのようです。

Python2 : print "文字列"
Python3 : print ("文字列")




■Pythonスクリプトの修正

Python3の構文に合わせてスクリプトを書き換えます。


/var/www/html/cgi-enabled/hellow_world.py

#!/usr/bin/env python

print ("Content-type: text/html\n\n")
print ("<html>\n<body>")
print ("<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">")
print ("Hellow World!")
print ("</div>\n</body>\n</html>")

※()を付けただけです



再度、ブラウザで表示してみます。

http://(外部IPアドレス)/cgi-enabled/hellow_world.py



無事成功しました!



今回、Pythonのインストールは初めてだったのですが、OSがDebianだったので比較的スムーズに実現することができました。


これからPythonの便利なライブラリを使って色々なことできるぞ!^^キット

このブログを検索

ブログをよくする

自己紹介

自分の写真
はじめまして。はるはるです。 中2の息子と小5の娘を抱える2児の父です。今はゲーム会社で働いています。 子供のプログラミング学習に協力できるように教え方を勉強中です。 このブログでは簡単なゲームを作りながら自分が学んだことを少しずつ共有していきます。 情報処理の試験をたまに受けます。 第二種情報処理技術者 ソフトウェア開発技術者 基本情報処理技術者 応用情報処理技術者 twitter: https://twitter.com/amaruchan007

連絡フォーム

名前

メール *

メッセージ *

ブログ アーカイブ

QooQ