LoginSignup
2
3

More than 3 years have passed since last update.

Flaskの自分用いろいろ

Last updated at Posted at 2019-07-01

インストール

pythonはインストール済みのUbuntu(18.04)前提です。
pip install Flask

メインになるやつ

run.py
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=80)

備考

これだと80ポートで動くのでapache2とか動いてるとエラーが出ます.
誰でもアクセスできる状態(変更したい場合はapp.runのあたりを変える)
デバッグモードが有効化されてる状態(無効化したいときはapp.debugをFalseに)
処理とかはここに書く..らしい(他サイト参照)

htmlとか各種ファイルのパス

ここで2時間ぐらい躓いてた

htmlはtemplatesフォルダ内に置く

css、JavaScript、画像等はstatic内にフォルダを作って置く

run.py
/templates
//index.html
//hogehoge.html
/static
//css
///main.css
///ほげほげ.css
//images
///hoge.png
//JS
///hogehoge.js

(見にくいなこれ)
置く場所を変更することもできるらしいけど標準だとこうなるらしい.

htmlでのパスの書き方

index.html
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css')}}">
<script src="{{ url_for('static',filename='JS/hogehoge.js')}}"></script>
</head>
<body>
...
<img src="{{ url_for('static',filename='images/hoge.png')}}"></img>
...
</body>

{{ url_for('static',filename='hoge/hoge')}}って形で指定するらしい。

実行

hoge@hoge:/var/www/html$ sudo python3 run.py
 * Serving Flask app "run" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 810-364-364

感想(?)

色々なサイトからのコピペの集合体なのでもっと効率のいい方法があると思います。見つけた方は教えていただけると幸いです。
お疲れ様でした。

2
3
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
2
3