It works on my laptop
Aisha builds an app. It works on her laptop. She puts it on the server. It breaks.
A package is missing. The password is wrong. The folder is not there.
Twelve habits, called the twelve factors, stop most of these problems. Today you learn the first six.
Key words
| Word | What it means | Example |
|---|---|---|
| Twelve-factor app | An app built with twelve habits that make it easy to deploy. | |
| Database | An organised store of data that programs can search and change. | |
| Version control | A tool that keeps every version of your files. | |
| Network | Computers joined together so they can send data to each other. | |
| Codebase | All the code of one app, kept in one repository. | |
| Repository | A store for code and its full history. | |
| Deploy | To put an app on a computer and start it. As a noun: one running copy of the app. | |
| Dependency | A package your code needs to run. | flask |
| Configuration | Settings that change between deploys. | |
| Environment variable | A setting stored where the app runs, outside the code. | PORT=9000 |
| Backing service | A service your app uses over the network. | |
| Stateless | A process that keeps nothing on itself between requests. |
The cells students fill in are left blank in this preview.
Six habits
Each factor is a short rule. It has a reason. Learn the reason and you can find the rule again.
Run the code below to see factor 3 at work: the configuration comes from outside the code.
Read a setting from outside the code
import os
# Read a setting. If there is none, use "Hello".
greeting = os.environ.get("GREETING", "Hello")
print(greeting, "world")
# The code does not change. Only the setting changes.
# A setting that is missing should give a clear error, not a guess.
Make a free account to save your work and track your progress.
Factors 1 to 6
| Factor | Rule in plain words | Why |
|---|---|---|
| 1 Codebase | One codebase in version control. Many deploys come from it | Test and live run the same code |
| 2 Dependencies | Write down every package you need. Keep them apart from other projects | A new machine installs the same things |
| 3 Config | Keep settings in the environment, not in the code | The same code runs anywhere. No passwords in the repository |
| 4 Backing services | Treat a database or email service as a plug you can swap by changing a setting | You can change the database without changing the code |
| 5 Build, release, run | Keep three stages apart: make the program, add the settings, then run it | You can go back to an old release if the new one is bad |
| 6 Processes | Run as stateless processes. Keep data in a database, not in the process | Any process can answer any request. One can die and nothing is lost |
The cells students fill in are left blank in this preview.
Never put a password in code
Warning
Many people think a password in the code is safe. It is not, because code goes into a repository that many people read. A password there is shared with all of them. Keep passwords in the environment, never in version control.
Factor 5: three separate stages
flowchart LR
code[Code from the repository] --> build[Build: make the program]
build --> release[Release: program plus settings, with a version number]
config[Settings for this deploy] --> release
release --> run[Run: start the processes]
Swap a backing service with a setting
import os
class MemoryStore:
def __init__(self):
self.items = []
def save(self, item):
self.items.append(item)
def load(self):
return self.items
class LoudStore(MemoryStore):
def save(self, item):
print("Saving", item)
super().save(item)
# The setting picks the store. The rest of the code does not change.
name = os.environ.get("STORE", "memory")
store = LoudStore() if name == "loud" else MemoryStore()
store.save("tea")
print(store.load())
# Change "memory" to "loud" in the line that reads STORE and run again.
# A real app swaps a small database for a big one in the same way.
Make a free account to save your work and track your progress.
Why processes must be stateless
class Process:
def __init__(self, name):
self.name = name
self.basket = [] # kept inside this process
def add(self, item):
self.basket.append(item)
def show(self):
print(self.name, "sees", self.basket)
one = Process("process 1")
two = Process("process 2")
one.add("tea")
one.show()
two.show() # the second process knows nothing
# Fix it: make one shared basket outside both processes.
# In a real app, that shared place is a database.
Make a free account to save your work and track your progress.
Match the factor to its rule
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Which factor is broken?
Have a go
Which factor is broken?
6 questionsRead the settings from the environment
Write the code that reads the settings, as a twelve-factor app should. read_settings takes the environment as a dictionary. It gives back the port, the debug flag and the database address. A missing database address is an error. missing_dependencies finds packages the code uses but nobody wrote down. Press Run Tests.
def read_settings(env):
# env is a dictionary of settings, like {"PORT": "9000", "DATABASE_URL": "db://x"}.
# Give back a dictionary with three keys:
# "port" the PORT setting as a whole number. If there is none, use 8000.
# "debug" True if DEBUG is the text "true" (any case), else False. No DEBUG means False.
# "database_url" the DATABASE_URL setting.
# If DATABASE_URL is missing, raise a ValueError. Never guess a password.
return None
def missing_dependencies(declared, used):
# declared: the list of package names written in the requirements file.
# used: the list of package names the code imports.
# Give back the names that are used but not declared, A to Z, with no repeats.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go