概要
- Flaskライブラリで作成したWebアプリを「ロリポップ!レンタルサーバー」で
稼働させる
フォルダ構成
.
├── [-rw----r--] .htaccess
├── [-rw-------] app.py
├── [-rwx------] index.cgi
├── [drwx---r-x] static
│ └── [-rw----r--] favicon.ico
└── [drwx---r-x] templates
└── [-rw----r--] index.html
- 上記のパーミッションについて
Pythonコード(Flask)
app.py
from os.path import join
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
@app.route('/favicon.ico')
def favicon():
# ./static/favicon.icoを送信
return send_from_directory(join(app.root_path, 'static'), 'favicon.ico')
@app.route("/")
def index():
# ./templates/index.htmlを送信
return render_template('index.html')
if __name__ == "__main__":
app.run(threaded=True)
CGIコード
index.cgi
#!/usr/local/bin/python3
from wsgiref.handlers import CGIHandler
# index.cgiファイルと同階層にあるapp.pyファイルを呼び出し
from app import app
# Flaskアプリ実行
CGIHandler().run(app)
.htaccessコード(Apacheサーバ向け)
.htaccess
RewriteEngine On
# HTTPからHTTPSへの強制リダイレクト
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# index.cgiを利用したリクエスト処理
# ・クライアントからのリクエスト(https://<ドメイン名>/<コンテキストパス>)を
# ロリポップのApacheサーバが受けた際、常に「/index.cgi/<コンテキストパス>」の
# 実行を行うことでFlaskで作られたWebアプリを使って、クライアントにレスポンスを返す
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.cgi/$1 [QSA,L]
参考ページ