LoginSignup
363
338

More than 5 years have passed since last update.

pythonでローカルwebサーバを立ち上げる

Last updated at Posted at 2018-02-13

概要

pythonで検証用のwebサーバを起動する方法です。
ローカル上で動作確認をしたいので、pythonの標準ライブラリでwebサーバを立ち上げてHTMLの表示まで。

環境

Mac Sierra 10.12.6
python3.5

pythonのインストール

pythonのインストール

webサーバの起動

ターミナルの任意の場所で以下を実行

$ python -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

【python2.7の場合】※2系と3系でモジュール名が変わっているので注意

$ python -m SimpleHTTPServer 8000

となります。

起動できたらお使いのブラウザから
http://localhost:8000
を開きましょう。

スクリーンショット 2018-02-13 16.49.59.png

実行したディレクトリが表示されます。
確認ができたらCtrl+cでwebサーバを閉じます。

ドキュメントルートの作成

今度はpythonスクリプトでwebサーバを起動します。
まず、ドキュメントルートとなるディレクトリを作成しましょう。
ディレクトリを作成したらその中に以下を作成します。

*simpleserver.py・・・webサーバ起動用スクリプト

simpleserver.py
import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

【python2.7の場合】

simpleserver.py
import SimpleHTTPServer
import SocketServer

PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

*index.html・・・ブラウザに表示するHTMLファイル

index.html
<html>
<body>
successfully!
</body>
</html>

今度はpythonスクリプトでwebサーバを起動します。

$ python simpleserver.py

http://localhost:8000
を開いてsuccessfully!が表示されればOKです。

が、このままではあまりにも寂しいので、形だけでもホームページを置こうと思います。

https://aperitif.io/
☝️ここからサンプルをもらう

HEADER、CONTENT、FOOTERあたりを適当に選択します。
右上のGENERATEをクリック👉file.zipがインストールされる

これの解凍した中身を先ほど作成したドキュメントルートに置きましょう。
で、仮で作ったindex.htmlを削除してtemplate.htmlをindex.htmlにリネームします。
で、またアクセスすると👉http://localhost:8000

スクリーンショット 2018-02-13 19.05.18.png

画面が表示されるようになりました。

363
338
1

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
363
338