Next, use Python (Flask) for Heroku!

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.

What is Flask?

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.

Let's get started easily

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.

Library preparation

$ 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

Template, app preparation

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

Let's try it locally

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.

スクリーンショット 2014-12-07 14.05.05.png

Deploy to heroku

Prepare files for heroku

$ pip install gunicorn
$ pip freeze > requirements.txt
$ echo python-2.7.8 > runtime.txt
$ echo web: gunicorn app:app --log-file=- > Procfile

Manage with git

$ git init
$ git add .gitignore
$ git add .
$ git commit -m "initial commit"

Deploy to heroku

$ 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.

スクリーンショット 2014-12-07 14.23.55.png

Check with the heroku logs command.

スクリーンショット 2014-12-07 14.23.48.png

Let's use the database

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.

Use MongoHQ

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/ now counts by name. It's a lot of omissions, but it's a sample.

Next is

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

Next, use Python (Flask) for Heroku!
A memorandum for touching python Flask on heroku
Use Flask as the next step for SimpleHTTPServer
[Python] Use Basic/Digest authentication with Flask
Beginners use Python for web scraping (1)
Beginners use Python for web scraping (4) ―― 1
Use DeepL with python (for dissertation translation)
[Python] Organizing how to use for statements
Easy web app with Python + Flask + Heroku
How to use "deque" for Python data
Use pathlib in Maya (Python 2.7) for upcoming Python 3.7
2016-10-30 else for Python3> for:
python [for myself]
LINE heroku python
How to upload with Heroku, Flask, Python, Git (4)
Wrap C with Cython for use from Python
Don't use readlines () in your Python for statement!
Until you use PhantomJS with Python on Heroku
Wrap C ++ with Cython for use from Python
python: Use your own class for numpy ndarray
Use data class for data storage of Python 3.7 or higher
About Python for loops
Use thingsspeak from python
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
Beginners can use Python for web scraping (1) Improved version
Use config.ini in Python
[Python] Use JSON with Python
Python basics ② for statement
Use fluentd from python
Use dates in Python
Easy to use Flask
Use Valgrind in Python
How to upload with Heroku, Flask, Python, Git (Part 3)
[Heroku] Memo for deploying Python apps using Heroku on Windows [Python]
Use MySQL from Python
Use mecab with Python3
Use LiquidTap Python Client ③
I tried python on heroku for the first time
Use DynamoDB with Python
About Python, for ~ (range)
Next Python in C
python textbook for beginners
Refactoring tools for Python
Use Python 3.8 with Anaconda
How to upload with Heroku, Flask, Python, Git (Part 1)
[Python] format methodical use
Use python with docker
python for android Toolchain
Use MySQL from Python
Use LiquidTap Python Client ②
heroku memo (for myself)
How to upload with Heroku, Flask, Python, Git (Part 2)
Use BigQuery from python.
Suppress python3 flask logging
Use profiler in Python
Use AWS SDK for Python (boto) under Proxy environment
OpenCV for Python beginners
Programming with Python Flask
Beginners use Python for web scraping (4) --2 Scraping on Cloud Shell
Install Python (for Windows)