Home >Backend Development >Python Tutorial >Hunting Heisenberg with Django Rest Framework
这个想法是为 DEA 特工创建一个简单的平台,来管理《绝命毒师》/《风骚律师》宇宙中角色的信息。为了让 DEA 特工的工作变得更轻松,他们需要一个 API 端点,允许根据人物的姓名、出生日期、职业或他们是否是嫌疑人的事实来过滤有关人物的信息。
缉毒局试图将毒枭关进监狱,他们正在追踪他们以及他们所在位置周围的人。它们将时间戳和特定位置作为地理坐标存储在相关表中。将公开数据的端点需要允许过滤距特定地理点特定距离内的位置条目,以及它们被分配给谁,以及记录它们的日期时间范围。此端点的排序应允许考虑距指定地理点的距离,升序和降序。
要了解它是如何完成的,您可以按照下面的文档在本地设置此项目并自行测试。
您可以在我的 GitHub 存储库中找到代码。
作为先决条件,您需要在系统上安装 Docker 和 docker-compose。
首先,转到您的项目文件夹并克隆 Breaking Bad API 存储库:
git克隆git@github.com:drangovski/writing-bad-api.git
cd 破坏-bad-api
然后您需要创建 .env 文件,在其中放置以下变量的值:
POSTGRES_USER=heisenberg POSTGRES_PASSWORD=iamthedanger POSTGRES_DB=breakingbad DEBUG=True SECRET_KEY="<SECRET KEY>" DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=breakingbad SQL_USER=heisenberg SQL_PASSWORD=iamthedanger SQL_HOST=db<br /> SQL_PORT=5432
注意:如果需要,您可以使用 env_generator.sh 文件为您创建 .env 文件。这也会自动生成SECRET_KEY。要运行此文件,首先使用 chmod x env_generator.sh 授予其权限,然后使用 ./env_generator.sh
运行它
一旦你有了这套,你就可以运行:
docker-compose 构建
docker-compose up
这将在 localhost:8000 启动 Django 应用程序。要访问 API,URL 将为 localhost:8000/api。
为了这些项目的主题(最终,为了让你的生活更轻松一点:)),你最终可以使用以下位置及其坐标:
Location | Longitude | Latitude |
---|---|---|
Los Pollos Hermanos | 35.06534619552971 | -106.64463423464572 |
Walter White House | 35.12625330483283 | -106.53566597939896 |
Saul Goodman Office | 35.12958969793146 | -106.53106126774908 |
Mike Ehrmantraut House | 35.08486667169461 | -106.64115047513016 |
Jessie Pinkman House | 35.078341181544396 | -106.62404891988452 |
Hank & Marrie House | 35.13512843853582 | -106.48159991250327 |
import requests import json url = 'http://localhost:8000/api/characters/' headers = {'Content-Type' : "application/json"} response = requests.get(url, headers=headers, verify=False) if response.status_code == 200: data = response.json() print(json.dumps(data, indent=2)) else: print("Request failed with status code:", response.status_code)
检索数据库中所有现有的字符。
获取/api/字符/
[ { "id": 1, "name": "Walter White", "occupation": "Chemistry Professor", "date_of_birth": "1971", "suspect": false }, { "id": 2, "name": "Tuco Salamanca", "occupation": "Grandpa Keeper", "date_of_birth": "1976", "suspect": true } ]
要检索单个角色,请将角色的 ID 传递给 enpoint。
GET /api/characters/{id}
您可以使用 POST 方法到 /characters/ 端点来创建新角色。
POST /api/characters/
您需要在查询中传递以下参数,才能成功创建角色:
{ "name": "string", "occupation": "string", "date_of_birth": "string", "suspect": boolean }
Parameter | Description |
---|---|
name | String value for the name of the character. |
occupation | String value for the occupation of the character. |
date_of_birth | String value for the date of brith. |
suspect | Boolean parameter. True if suspect, False if not. |
Ordering of the characters can be done by two fields as parameters: name and date_of_birth
GET /api/characters/?ordering={name / date_of_birth}
Parameter | Description |
---|---|
name | Order the results by the name field. |
date_of_birth | Order the results by the date_of_birth field. |
Additionally, you can add the parameter ascending with a value 1 or 0 to order the results in ascending or descending order.
GET /api/characters/?ordering={name / date_of_birth}&ascending={1 / 0}
Parameter | Description |
---|---|
&ascending=1 | Order the results in ascending order by passing 1 as a value. |
&ascending=0 | Order the results in descending order by passing 0 as a value. |
To filter the characters, you can use the parameters in the table below. Case insensitive.
GET /api/characters/?name={text}
Parameter | Description |
---|---|
/?name={text} | Filter the results by name. It can be any length and case insensitive. |
/?occupaton={text} | Filter the results by occupation. It can be any length and case insensitive. |
/?suspect={True / False} | Filter the results by suspect status. It can be True or False. |
You can also use the search parameter in the query to search characters and retrieve results based on the fields listed below.
GET /api/characters/?search={text}
name
occupation
date_of_birth
To update a character, you will need to pass the {id} of a character to the URL and make a PUT method request with the parameters in the table below.
PUT /api/characters/{id}
{ "name": "Mike Ehrmantraut", "occupation": "Retired Officer", "date_of_birth": "1945", "suspect": false }
Parameter | Description |
---|---|
name | String value for the name of the character. |
occupation | String value for the occupation of the character. |
date_of_birth | String value for the date of birth. |
suspect | Boolean parameter. True if suspect, False if not. |
To delete a character, you will need to pass the {id} of a character to the URL and make DELETE method request.
DELETE /api/characters/{id}
To retrieves all existing locations in the database.
GET /api/locations/
[ { "id": 1, "name": "Los Pollos Hermanos", "longitude": 35.065442792232716, "latitude": -106.6444840309555, "created": "2023-02-09T22:04:32.441106Z", "character": { "id": 2, "name": "Tuco Salamanca", "details": "http://localhost:8000/api/characters/2" } }, ]
To retrieve a single location, pass the locations ID to the endpoint.
GET /api/locations/{id}
You can use the POST method to /locations/ endpoint to create a new location.
POST /api/locations/
You will need to pass the following parameters in the query, to successfully create a location:
{ "name": "string", "longitude": float, "latitude": float, "character": integer }
Parameter | Description |
---|---|
name | The name of the location. |
longitude | Longitude of the location. |
latitude | Latitude of the location. |
character | This is the id of a character. It is basically ForeignKey relation to the Character model. |
Note: Upon creation of an entry, the Longitude and the Latitude will be converted to a PointField() type of field in the model and stored as a calculated geographical value under the field coordinates, in order for the location coordinates to be eligible for GeoDjango operations.
Ordering of the locations can be done by providing the parameters for the longitude and latitude coordinates for a single point, and a radius (in meters). This will return all of the locations stored in the database, that are in the provided radius from the provided point (coordinates).
GET /api/locations/?longitude={longitude}&latitude={latitude}&radius={radius}
Parameter | Description |
---|---|
longitude | The longitude parameter of the radius point. |
latitude | The latitude parameter of the radius point. |
radius | The radius parameter (in meters). |
Additionally, you can add the parameter ascending with values 1 or 0 to order the results in ascending or descending order.
GET /api/locations/?longitude={longitude}&latitude={latitude}&radius={radius}&ascending={1 / 0}
Parameter | Description |
---|---|
&ascending=1 | Order the results in ascending order by passing 1 as a value. |
&ascending=0 | Order the results in descending order by passing 0 as a value. |
To filter the locations, you can use the parameters in the table below. Case insensitive.
GET /api/locations/?character={text}
Parameter | Description |
---|---|
/?name={text} | Filter the results by location name. It can be any length and case insensitive. |
/?character={text} | Filter the results by character. It can be any length and case insensitive. |
/?created={timeframe} | Filter the results by when they were created. Options: today, yesterday, week, month & year. |
Note: You can combine filtering parameters with ordering parameters. Just keep in mind that if you filter by any of these fields above and want to use the ordering parameters, you will always need to pass longitude, latitude and radius altogether. Additionally, if you need to use ascending parameter for ordering, this parameter can't be passed without longitude, latitude and radius as well.
To update a location, you will need to pass the {id} of locations to the URL and make a PUT method request with the parameters in the table below.
PUT /api/locations/{id}
{ "id": 1, "name": "Los Pollos Hermanos", "longitude": 35.065442792232716, "latitude": -106.6444840309555, "created": "2023-02-09T22:04:32.441106Z", "character": { "id": 2, "name": "Tuco Salamanca", "occupation": "Grandpa Keeper", "date_of_birth": "1975", "suspect": true } }
Parameter | Description |
---|---|
name | String value for the name of the location. |
longitude | Float value for the longitude of the location. |
latitude | Float value for the latitude of the location. |
To delete a location, you will need to pass the {id} of a location to the URL and make a DELETE method request.
DELETE /api/locations/{id}
The above is the detailed content of Hunting Heisenberg with Django Rest Framework. For more information, please follow other related articles on the PHP Chinese website!