LoginSignup
4
6

More than 5 years have passed since last update.

【Python】Bottleで手軽にLAN内やLAN外からアクセスできるページを用意

Last updated at Posted at 2018-12-13

社内デモや勉強会等で軽く公開したい場合用のメモです。

軽量Webフレームワーク:Bottle

今回は、Django、Flaskと並び有名なPythonのWebフレームワーク Bottleを利用します。

1.「bottle.py」をダウンロードし、プログラムを実行したい任意のフォルダに格納する。
今回は簡単に以下のような配置で格納。
 ├ bottle.py
 ├ index.html
 └ main.py
 格納したソースはそれぞれ以下。

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

from bottle import route, run, template


@route('/')
def index():
    return template("index")


if __name__ == '__main__':
    run(host="localhost", port=8080, debug=True, reloader=True)
index.html
<!DOCTYPE html>
<html lang="jp">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
</head>
<body>
  <h1>sample</h1>
</body>
</html>

2.「main.py」を実行し、http://localhost:8080 にアクセスする

参考:
 Bottle: Python Web Framework
 Pythonを始めるなら、1ファイルの軽量Webフレームワーク「Bottle」がおすすめ
 PythonのWebフレームワーク6種をかんたんに紹介

LAN内の端末からアクセスする

サンプルでは、localhost指定(localhostか127.0.0.1のみ)になっていたため、以下のように修正すればLAN内の端末からアクセス可能になります。

main.py
    run(host="192.168.xxx.xxx", port=8080, debug=True, reloader=True)

→実行する端末のIPを調べて「host」に指定する。この場合はloalhost指定でのアクセスが出来なくなる。

main.py
    run(host="0.0.0.0", port=8080, debug=True, reloader=True)

→「host」に"0.0.0.0"を指定すると、localhost指定か端末IP指定(http://192.168.xxx.xxx:8080/) でアクセス出来る。

LAN外の端末からアクセスする

サクっと実現したいため「ngrok」を利用(もう少し気合を入れる場合はherokuとか。。。

1.ngrokのページへ行き、「Get started for free →」ボタンを押下、次画面にてライセンスの登録を行う
2.「Setup & Installation」に従いngrokをインストール
3. コンソール上で「./ngrok http 8080」を実行(例はUbuntuの場合
無題.png
上記例の場合は、http://775ebd31.ngrok.io にアクセスすることでLAN外からアクセス可能(Freeプランの場合は、ngrokを起動するたびにURLが変わる

参考:
 ngrokが便利すぎる

pyinstallerでexe化

pyinstallerでexe化しておくと取り回ししやすいかもしれない(上記のサンプルプログラムだと「--noconsole」オプションは指定せずにコンソール表示しておかないと何やってるかわからなく、、、

    pyinstaller main.py --onefile

以下のようにexeファイルが生成されるため、「main.exe」から見える場所に「index.html」を格納すれば、実行可能。
 ├ dist
 │ └ main.exe
 ├ bottle.py
 ├ index.html
 └ main.py

以上。

4
6
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
4
6