This version illustrates Test Driven Development (TDD) and the use of decorator functions to extend functionality and code reuse to remove duplication.
TDD Simplified
The Test Driven Development Cycle
User Model
A Simple User model
We are going to start with a simple User Model so that we can fully grasp and appreciate the TDD workflow
End Points Sequence Diagrams
Get Users: GET /users
Get a User: GET /users/<user_id>
Create a User: POST /users
Update a User: PUT /users
Delete a User: DELETE /users/<user_id>
Dependencies
How to set up and run the project
-
Create and Activate a Python virtual environment
-
Install requirements
pip install -r requirements.txt
-
Set environment variables specified in the env_sample.txt
- DATABASE_URL for Production
- DEV_DATABASE_URL for Development
- TEST_DATABASE_URL for Testing
Remember to create separate databases for testing and running the code
-
Update the migrations
flask db upgrade
-
Run the project
python -m run
How to Create and Activate a Python virtual Environment
-
Open your terminal at the root of the project
-
create a virtual environment
python -m venv env
-
Activate the virtual environment
- for windows
env\Scripts\activate
- for linux\macOS
source env/bin/activate
- for windows
-
Deactivate the virtual environment
deactivate
How to run tests
- Activate the virtual environment
- Create you test database
- SET the
TEST_DATABASE_URL
environment variable - Run the tests using pytest
pytest tests
Important to know
how to get json data from the request object
{
"username": "Arthur"
}
-
json returns
apython dictionary
withkey-value
pairs-
The parsed JSON data
ifmimetype
indicates
JSON (*application/json
)is_json
)
. -
Calls
get_json()
with
default arguments. -
If the request content type is not
application/json
, this will raise a 400 Bad Request error.data = request.json username = data["username"]
-
-
get_json(force=False, silent=False, _
cache=True_) returns
adict
withkey-value
pairs-
Raises a 400 error if the content type is incorrect.
-
force (bool) – Ignore the mimetype and always try
to parse JSON.data = request.get_json(force=True)
-
-
flask.json.loads(s, app=None, **
kwargs)-
Serialize an object to a string of JSON.
data = json.loads(request.data.decode())
-
How to convert to python objects to JSON String
-
-
Serialize data to JSON and wrap it in a Response with the
application/json
mimetypejsonify({"username": "Arthur"})
-
-
flask.json.dumps(obj, app=None, **
kwargs)-
Serialize an object to a string of JSON.
user_dict = { "username": "Arthur" } json_data = json.dumps(user_dict)
-