-Try running the program created in Previous article (Redis on Mac) on heroku. --It is assumed that heroku itself is available.
--The result of the tree command looks like this. --The virtualenv environment is also included.
.
├── Procfile
├── __pycache__
├── app.py
├── bin
├── include
├── lib
├── pip-selfcheck.json
├── requirements.txt
└── runtime.txt
requirements.txt
--The necessary libraries are described.
--You can do it with pip freeze> requirements.txt
.
――Specifically, it is as follows.
click==6.7
Flask==0.12.2
gunicorn==19.7.1
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==1.0
redis==2.10.5
Werkzeug==0.12.2
runtime.txt
--Describe the version of python to run. ――Specifically, it is as follows.
python-3.6.0
Procfile
--Heroku's web server uses gunicorn, so write the configuration file. ――Specifically, it is as follows. ――Since it is app.py, it is difficult to understand because it becomes app: app w
web: gunicorn app:app --log-file -
Heroku Redis
--You can try it on heroku's free course, but you need to register for a credit card to authenticate to use redis. --You can also choose a free course for the redis plugin.
--Use heroku cli. You can also do it on the web console.
% heroku plugins:install heroku-redis Installing plugin heroku-redis... done
--You can use redis by adding a plugin.
% heroku config -a APP_NAME
=== APP_NAME Config Vars
LANG: ja_JP.utf8
REDIS_URL: redis://h:pc16fb4fb5781c56263fe9b8ac2〜〜〜2980da@ec2-34-〜〜〜.compute-1.amazonaws.com:9289
TZ: Asia/Tokyo
--LANG and TZ are set separately. The point is the environment variable called REDIS_URL.
--If there is no environment variable, the default value is set to correspond to the local machine.
app.py
import os
import sys
import redis
import random
from flask import Flask
from datetime import datetime as dt
app = Flask(__name__)
#If it is in the connection path or environment variable, it has priority
REDIS_URL = os.environ.get('REDIS_URL') if os.environ.get(
'REDIS_URL') != None else 'redis://localhost:6379'
#Database specification
DATABASE_INDEX = 1 #Dare 1 instead of 0
#Get one from the connection pool
pool = redis.ConnectionPool.from_url(REDIS_URL, db=DATABASE_INDEX)
#Use connection
r = redis.StrictRedis(connection_pool=pool)
@app.route('/')
def root():
return '{"status":"OK"}'
@app.route('/get')
def get():
n = random.randrange(len(r.keys()))
key = r.keys()[n]
return str(r.get(key))
@app.route('/set')
def set():
tdatetime = dt.now()
key = tdatetime.strftime('%Y-%m-%d %H:%M:%S')
r.set(key, {'val': key})
return '{"action":"set"}'
if __name__ == '__main__':
app.run(threaded=True)
Recommended Posts