Personal notes
I did a Python tutorial on Heroku. https://devcenter.heroku.com/articles/getting-started-with-python I left it as a memo, but I didn't get stuck, so it became a command memo instead of know-how.
Python is running locally There is also virtualenv
brew intall postgresql
Set for postgres
echo 'export PGDATA=/usr/local/var/postgres' >> ~/.zshrc #In each profile
Now you can start / stop with pg_ctl start
or pg_ctl stop
.
(Usually it is troublesome because it is confusing with postgres -D / usr / local / var / postgres
)
Check by entering as a postgres user from the beginning or displaying the database list
psql -l #DB display
psql postgres #Login as postgres user(When you leave\q)
https://www.heroku.com/
brew install heroku-toolbelt
Then log in to Heroku
$ heroku login
Enter your Heroku credentials.
Email: [email]
Password (typing will be hidden):
Logged in as [email]
Clone the sample app.
git clone https://github.com/heroku/python-getting-started.git
$ cd python-getting-started
If you can, register the app on Heroku
$ heroku create
Creating morning-plateau-xxxx... done, stack is cedar-14
https://morning-plateau-xxxx.herokuapp.com/ | https://git.heroku.com/morning-plateau-xxxx.git
Git remote heroku added
The app is registered with an appropriate name (morning-plateau-xxxx this time).
If you want to give it a name, put it after create
. heroku create sanmple-name-app
At this point, remote is registered with the local git under the name heroku.
When I accessed the URL, it looked like an initial page.
Next, deploy the sample app
$ git push heroku master
Counting objects: 185, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (91/91), done.
Writing objects: 100% (185/185), 30.52 KiB | 0 bytes/s, done.
Total 185 (delta 80), reused 185 (delta 80)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing runtime (python-2.7.9)
remote: -----> Installing dependencies with pip
#Omitted because it is long
remote: -----> Compressing... done, 42.9MB
remote: -----> Launching... done, v4
remote: https://morning-plateau-xxxx.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy.... done.
Deploy completed. Looking at the output, you can see that it is not just pushing, but somehow environment construction and command execution.
Start the process to run the application with the following command. I have specified scale as 1, but will it cost money to increase it? In order to move it for the time being, "Ensure that at least one instance of the app is running".
$ heroku ps:scale web=1
Scaling dynos... done, now running web at 1:Free.
When I run the ps command, it certainly seems to work.
$ heroku ps
=== web (Free): gunicorn gettingstarted.wsgi --log-file -
web.1: up 2016/01/06 02:36:49 (~ 8m ago)
By the way, when web = 2, it became like this. Hmm. (Look at later)
$ heroku ps:scale web=2
Scaling dynos... failed
! Cannot update to more than 1 Free size dynos per process type.
Finally, open the app below
heroku open
Easy. At this point, the page is opened.
heroku logs
heroku logs --tail #Seen in tail
Procfile?
In the text file in the root directory of the application, write the commands required to start the application. The Procfile of the Python sample application was as follows.
web: gunicorn gettingstarted.wsgi --log-file -
web
is the process type, followed by the command.
When started normally, the process runs with one dyno.
(What is dyno? Here is a lightweight container that runs Procfile commands)
If you want to do it properly, use heroku ps
.
By default, one dyno is & free, and if there is no access for 30 minutes or if you move for 18 hours or more a day, it will enter sleep mode. If it is within 18 hours, it will start up every time an access comes, but after sleep, it will start up, so it will be a little heavy. If you don't want to sleep or want to scale, change to Professional.
If requirements.txt is in the root directory, Heroku seems to recognize it as a python app. The contents of requirements.txt of the sample application are as follows.
$ cat requirements.txt
dj-database-url==0.3.0
Django==1.8.1
django-postgrespool==0.3.0
gunicorn==19.3.0
psycopg2==2.6
SQLAlchemy==1.0.4
whitenoise==1.0.6
Heroku installs the required libraries based on this, although it's slightly different from the one in the tutorial.
As you know, this is the same format as pip freeze
.
Since it is a sample application that I downloaded, I will create the same environment locally for the time being.
The version of python is written in runtime.txt
in the root directory.
(Because I was using pyenv, I created an environment with it.)
$ cat runtime.txt
python-2.7.9
$ pyenv install 2.7.9
$ pyenv virtualenv 2.7.9 sample-app
$ cd [workspace]
$ pyenv local sample-app
$ pip install -r requirements.txt --allow-all-external
What you run on heroku works locally.
$ python manage.py collectstatic #Collect static files in your project in one place
$ heroku local web
Access http: // localhost: 5000 / and confirm that it is working.
The flow of changing the local appropriately and pushing to heroku. I'm pushing by importing requests, making changes to skip requests to the appropriate site and display the response.
First, add the following to requirements.txt
.
requests==2.3.0
Add the following to the head of hello / views.py
and
import requests
Rewrite the function called index as follows
def index(request):
r = requests.get('http://httpbin.org/status/418')
print r.text
return HttpResponse('<pre>' + r.text + '</pre>')
Run locally
$ pip install -r requirements.txt --allow-all-external
$ heroku local
If you go to http: // localhost: 5000 /, you will find the contents of http://httpbin.org/status/418.
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
cute.
Since it changed safely, I will reflect it on heroku.
$ git add .
$ git commit -m "Demo"
$ git push heroku masterg
$ heroku open
Deploy completed, the same teapot page opens. Deploying to heroku is basically this flow.
As an example, add a paper trail.
$ heroku addons:create papertrail
! Please verify your account to install this add-on plan (please enter a credit card) For more information, see https://devcenter.heroku.com/categories/billing Verify now at https://heroku.com/verify
I got scolded. Addon seems to have verify to prevent abuse. I was scared to register my credit card information and try again.
$ heroku addons:create papertrail
Creating papertrail-rigid-xxxx... done, (free)
Adding papertrail-rigid-xxxx to morning-plateau-xxxx... done
Setting PAPERTRAIL_API_TOKEN and restarting morning-plateau-xxxx... done, v6
Welcome to Papertrail. Questions and ideas are welcome ([email protected]). Happy logging!
Use `heroku addons:docs papertrail` to view documentation.
Now deployed. You can see the current addon list with the following command.
$ heroku addons
Add-on Plan Price
───────────────────────────────────────────── ───────── ─────
heroku-postgresql (postgresql-octagonal-xxxx) hobby-dev free
└─ as DATABASE
papertrail (papertrail-rigid-xxxx) choklad free
└─ as PAPERTRAIL
The table above shows add-ons and the attachments to the current app (morning-plateau-xxxx) or other apps.
Take a look at papertrail
heroku addons:open papertrail
A browser opens and you can check the log.
You can use the heroku console with the heroku run COMMAND
command.
Here the command seems to be running on a temporary dyno called one-off dyno.
$ heroku run pwd
Running pwd on morning-plateau-xxxx... up, run.5945
/app
$ heroku run python manage.py shell
Running python manage.py shell on morning-plateau-xxxx... up, run.4047
Python 2.7.9 (default, Dec 11 2014, 17:18:51)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import requests
>>> print requests.get('http://httpbin.org/status/418').text
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
Similarly, you can run dyno's bash below.
$ heroku run bash
Running bash on morning-plateau-xxxx... up, run.3252
$ ls
app.json gettingstarted hello manage.py Procfile Procfile.windows README.md requirements.txt runtime.txt staticfiles
$ exit
exit
Setting variables and external resources such as secret key that you want to put externally.
At runtime, the configuration variables go into environment variables.
Add the following to the beginning of hello / view.py
.
import os
Also, rewrite ʻindex` as follows
def index(request):
times = int(os.environ.get('TIMES',3))
return HttpResponse('Hello! ' * times)
Add the following to your local .env file: See here and the environment variables are set.
TIMES=2
You can also set configuration variables on Heroku with heroku config: set
. You can also check it with heroku config
.
$ heroku config:set TIMES=2
Setting config vars and restarting morning-plateau-xxxx... done
TIMES: 2
$ heroku config
=== morning-plateau-xxxx Config Vars
DATABASE_URL: xxxx
PAPERTRAIL_API_TOKEN: xxxx
TIMES: 2
Various databases are also prepared by addon. Since it is addon, you can check the current one with heroku addons
.
You can see that the URL of the connection destination database is registered in DATABASE_URL
of heroku config
.
heroku config
=== morning-plateau-xxxx Config Vars
DATABASE_URL: postgres://~~~ #Abbreviation
Also, the heroku pg
command gives you more details.
$ heroku pg
=== DATABASE_URL
Plan: Hobby-dev
Status: Available
Connections: 0/20
PG Version: 9.4.4
Created: 2016-01-05 17:36 UTC
Data Size: 6.4 MB
Tables: 0
Rows: 0/10000 (In compliance)
Fork/Follow: Unsupported
Rollback: Unsupported
Add-on: postgresql-octagonal-xxxx
The DB is already enabled in the sample project, and you can access it by adding / db
to the end of the URL, but in the current state, the table has not been created yet, so an error will occur if you access it.
Run manage.py migrate
on Heroku to create a table in django.
$ heroku run python manage.py migrate
Running python manage.py migrate on morning-plateau-xxxx... up, run.6683
Operations to perform:
Synchronize unmigrated apps: messages, hello, staticfiles
Apply all migrations: admin, sessions, auth, contenttypes
# ...
#Abbreviation
When I access ʻURL + / db` again, this time I get a simple page with more records each time I access it, not an error.
The DB model is in hello / models.py
and the settings are in gettingstarted / settings.py
.
(I won't explain about django)
If you have postgresql locally, you can access heroku's db from your project's root directory with:
$ heroku pg:psql
---> Connecting to DATABASE_URL
psql (9.4.5, server 9.4.4)
Type "help" for help.
morning-plateau-xxxx::DATABASE=> select * from hello_greeting;
id | when
----+-------------------------------
1 | 2016-01-11 16:09:35.860529+00
2 | 2016-01-11 16:10:28.385479+00
(2 rows)
For more information on Heroku Postgres, see https://devcenter.heroku.com/articles/heroku-postgresql.
This is the end of the tutorial. Finally, two links are provided as the next step.
Recommended Posts