![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0188.png)
Fabric’s
local
command runs a command on your local machine—it’s just a
wrapper around
subprocess.Popen
really, but it’s quite convenient. Here we
capture the output from that
git log
invocation to get the hash of the current
commit that’s in your local tree. That means the server will end up with whatever
code is currently checked out on your machine (as long as you’ve pushed it up
to the server).
We
reset --hard
to that commit, which will blow away any current changes in
the server’s code directory.
For this script to work, you need to have done a
git push
of your
current local commit, so that the server can pull it down and
reset
to it. If you see an error saying
Could not parse object
, try doing
a
git push
.
Next we update our settings file, to set the
ALLOWED_HOSTS
and
DEBUG
, and to create a
new secret key:
deploy_tools/fabfile.py.
def
_update_settings
(
source_folder
,
site_name
):
settings_path
=
source_folder
+
'/superlists/settings.py'
sed
(
settings_path
,
"DEBUG = True"
,
"DEBUG = False"
)
#
sed
(
settings_path
,
'ALLOWED_HOSTS =.+$'
,
'ALLOWED_HOSTS = ["
%s
"]'
%
(
site_name
,)
#
)
secret_key_file
=
source_folder
+
'/superlists/secret_key.py'
if
not
exists
(
secret_key_file
):
#
chars
=
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
key
=
''
.
join
(
random
.
SystemRandom
()
.
choice
(
chars
)
for
_
in
range
(
50
))
append
(
secret_key_file
,
"SECRET_KEY = '
%s
'"
%
(
key
,))
append
(
settings_path
,
'
\n
from .secret_key import SECRET_KEY'
)
#
The Fabric
sed
command does a string substitution in a file; here it’s changing
DEBUG from
True
to
False
.
And here it is adjusting
ALLOWED_HOSTS
, using a regex to match the right line.
Django uses
SECRET_KEY
for some of its crypto—cookies and CSRF protection.
It’s good practice to make sure the secret key on the server is different from the
one in your (possibly public) source code repo. This code will generate a new
key to import into settings, if there isn’t one there already (once you have a secret
key, it should stay the same between deploys). Find out more in the
Django docs.
append
just adds a line to the end of a file. (It’s clever enough not to bother if
the line is already there, but not clever enough to automatically add a newline
if the file doesn’t end in one. Hence the back-n.)
160
|
Chapter 9: Automating Deployment with Fabric