0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

herokuでpythonのFlask触るための備忘録

Last updated at Posted at 2020-03-04

取るに足らないapiを作るときに、Heroku × Flask(Python) が個人的に最速だけど、いつも初期設定で謎に時間を食うのでまとめとく。
##ローカルでの準備

まずHerokuでアプリ作るところ

mkdir "フォルダー名"
cd "フォルダー名"
git init 
heroku create -a "アプリ名"

作成したフォルダーに必要なファイルは3つ

  • reqirements.txt
  • Procfile
  • hello.py(ファイル名はなんでもいい、とりあえずmain.py的ななにか)

まずrequirements.txtから(==の後ろのverは適当)

requirements.txt
Flask==1.1.0
gunicorn==19.9.0
psycopg2==2.7.6.1

psycopg2はpostgresqlをいじるためのライブラリだからpostgresqlいじらないときは不要
他はFlask使うなら必須

次はProcfile

Procfile
web: gunicorn hello:app --log-file -

最後はhello.py

hello.py
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------
#
#   hello.py
#
#                       Mar/04/2020
# -------------------------------------------------------------------
import os
from flask import Flask,request

app = Flask(__name__)

@app.route("/")
def hello():
    str_out = ""
    str_out += "<h2>Hello from Python!</h2>"
    str_out += "<blockquote>"
    str_out += "こんにちは<p />"
    str_out += "</blockquote>"
    str_out += "Mar/04/2020 14:40<br />"
#
    return str_out

#localでテストするときに必要なだけでサーバーでは不要
if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

# -------------------------------------------------------------------

##デプロイ

git add .
git commit -m "First Commit"
git push heroku master

本来pythonをbuildpackとして設定してあげないといけないけど、pushした時点でherokuがPythonを認識して最新版のpythonをダウンロードしてくれるっぽい

上手く動いていれば下のコマンドで"Hello From Python"が表示されるはず

heroku open

終わり

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?