Thanks. The day before Don't lose to Ruby! How to run Python (Django) on Heroku inspired me to register. This is kounoike.
The article Drawing SVG graphs with matplotlib on heroku also mentions the introduction of Flask + heroku, but this time let's make it an article without matplotlib. .. Instead, try using MongoHQ for a moment.
If Django is a "full stack" web framework, Flask is a "micro" web framework. The standard Flask core relies only on two libraries, the Jinja2 template engine and the Werkzeug WSGI toolkit. The main features it provides are routing, Jinja2 templates, static file provision, and debugging assistance (because I don't know everything ...). Of course, there are various Flask extension libraries available, so you should be able to do more elaborate things.
It's a very simple framework that allows you to start a .py file in one file, which is useful when you want to create and publish a simple web app.
Also, as you can see from yesterday's article, Django seems to take a lot of time to deliver static files, but Flask simply puts them under static, so it's easy to deliver js / css / img.
You have already created a heroku account and installed Toolbelt. In addition, it is assumed that pyenv and pyenv-virtualenv have been installed on Mac as the environment.
Heroku's python is 2.7.8 or 3.4.1, but I chose 2.7.8 here.
$ mkdir heroku-qiita-advent-2014
$ cd heroku-qiita-advent-2014
$ pyenv virtualenv 2.7.8 qiita-advent-2014
$ pyenv local qiita-advent-2014
$ echo .python-version > .gitignore
$ pip install flask
app.py
#!/bin/env python
# coding: utf-8
import os
from flask import Flask, render_template
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return u'test'
@app.route('/hello/<name>')
def hello(name=''):
if name == '':
¦ name = u'Nanashi'
return render_template('hello.html', name=name)
@app.route('/debug')
def debug():
return render_template('notemplate.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(port=port)
Place the template file under templates /. Also, place static files under static /.
templates/hello.html
<html>
<head>
<title>Hello {{ name }}</title>
</head>
<body>
<h1>Hello{{ name }}Mr.</h1>
<a href="http://flask.pocoo.org/"><img src="/static/img/flask.png "></a>
</body>
</html>
$ tree
.
├── Procfile
├── app.py
├── requirements.txt
├── runtime.txt
├── static
│ └── img
│ └── flask.png
└── templates
└── hello.html
python app.py
will launch the app on localhost port 5000. There are / and / hello / names and / debug, so let's try them.
Since ʻapp.debug = True` is entered, an error page appears when accessing http: // localhost: 5000 / debug.
$ pip install gunicorn
$ pip freeze > requirements.txt
$ echo python-2.7.8 > runtime.txt
$ echo web: gunicorn app:app --log-file=- > Procfile
$ git init
$ git add .gitignore
$ git add .
$ git commit -m "initial commit"
$ heroku login
$ heroku apps:create
$ git push heroku master
You can see this app at https://stark-forest-4893.herokuapp.com/. Please enter a suitable name after https://stark-forest-4893.herokuapp.com/hello/.
Also, Flask's ʻapp.debug = True` is disabled on heroku.
Check with the heroku logs
command.
How to use PostgreSQL is an English article, but Flask and PostgreSQL on Heroku You may want to refer to it (I have never used it ...).
The reason I haven't used it is that the free tier is limited to 10,000 lines and I use MongoHQ. Mongo HQ is free up to 512MB. If you have a lot of small data, this is easier to use.
Let's prepare various things.
$ heroku addons:add mongohq
$ pip install pymongo
$ pip freeze > requirements.txt
Modify apps & templates
app.py
#!/bin/env python
# coding: utf-8
import os
from urlparse import urlparse
from flask import Flask, render_template
from pymongo import Connection
app = Flask(__name__)
app.debug = True
MONGO_URL = os.environ.get('MONGOHQ_URL')
if MONGO_URL:
# Get a connection
connection = Connection(MONGO_URL)
# Get the database
db = connection[urlparse(MONGO_URL).path[1:]]
else:
# Not on an app with the MongoHQ add-on, do some localhost action
connection = Connection('localhost', 27017)
db = connection['QiitaAdvent2014']
@app.route('/')
def index():
return u'test'
@app.route('/hello/<name>')
def hello(name=''):
if name == '':
name = u'Nanashi'
return render_template('hello.html', name=name)
@app.route('/hello2/<name>')
def hello2(name=''):
if name == '':
name = u'Nanashi'
helloObj = db.hello.find_one({'name': name})
if not helloObj:
helloObj = {'name': name, 'count': 1}
else:
helloObj['count'] += 1
db.hello.save(helloObj)
return render_template('hello2.html', hello=helloObj)
@app.route('/debug')
def debug():
return render_template('notemplate.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(port=port)
hello2.html
<html>
<head>
<title>Hello {{ hello.name }}</title>
</head>
<body>
<h1>Hello{{ hello.name }}Mr.</h1>
<h2>{{ hello.count }}It's the second time!</h2>
</body>
</html>
https://stark-forest-4893.herokuapp.com/hello2/
It seems that it is related to fluentd, Postgres, TreasureData by kiyoto! Fluentd has been a hot topic these days. I am also interested. I'm looking forward to seeing how these connect with heroku.
Recommended Posts