Rumah > pembangunan bahagian belakang > Tutorial Python > Memburu Heisenberg dengan Rangka Kerja Django Rest

Memburu Heisenberg dengan Rangka Kerja Django Rest

DDD
Lepaskan: 2024-10-15 22:14:02
asal
459 orang telah melayarinya

Hunting Heisenberg with Django Rest Framework

아이디어

Breaking Bad/Better Call Saul 세계의 캐릭터에 대한 정보를 관리하기 위해 DEA 요원을 위한 간단한 플랫폼을 만드는 것이 아이디어였습니다. DEA 요원의 삶을 더 쉽게 만들려면 이름, 생년월일, 직업 또는 용의자 여부를 기준으로 캐릭터에 대한 정보를 필터링할 수 있는 API 엔드포인트가 필요합니다.

DEA가 마약왕을 감옥에 가두려고 하는 동안 마약왕과 그 주변 사람들을 추적하고 있습니다. 타임스탬프와 특정 위치를 관련 테이블에 지리적 좌표로 저장합니다. 데이터를 노출하는 엔드포인트는 특정 지리적 지점에서 특정 거리 내에 있는 위치 항목, 할당된 사람, 기록된 날짜/시간 범위를 필터링할 수 있어야 합니다. 이 끝점의 순서는 오름차순 및 내림차순 모두 지정된 지리적 지점으로부터의 거리를 고려할 수 있어야 합니다.

어떻게 완료되었는지 확인하려면 아래 문서에 따라 직접 테스트하여 이 프로젝트를 로컬로 설정할 수 있습니다.

내 GitHub 저장소에서 코드를 찾을 수 있습니다.

프로젝트 설정

전제 조건으로 시스템에 Dockerdocker-compose가 설치되어 있어야 합니다.

먼저 프로젝트 폴더로 이동하여 Breaking Bad API 저장소를 복제하세요.

git clone git@github.com:drangovski/breaking-bad-api.git

cd Breaking-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
Salin selepas log masuk

참고: 원하는 경우 env_generator.sh 파일을 사용하여 .env 파일을 생성할 수 있습니다. 그러면 SECRET_KEY도 자동으로 생성됩니다. 이 파일을 실행하려면 먼저 chmod x env_generator.sh로 권한을 부여한 다음 ./env_generator.sh로 실행하세요

이 세트가 있으면 다음을 실행할 수 있습니다.

docker-compose 빌드

docker-compose

이렇게 하면 Django 애플리케이션이 localhost:8000에서 시작됩니다. 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)
Salin selepas log masuk

캐릭터

모든 문자 검색

데이터베이스에 있는 모든 기존 문자를 검색합니다.

/api/characters/받기

[
    {
        "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
    }
]
Salin selepas log masuk

단일 문자 검색

단일 캐릭터를 검색하려면 해당 캐릭터의 ID를 enpoint에 전달하세요.

/api/characters/{id} 가져오기

새 캐릭터 만들기

새 캐릭터를 생성하려면 POST 메서드를 사용하여 /characters/ 엔드포인트에 연결할 수 있습니다.

포스트 /api/characters/

생성 매개변수

캐릭터를 성공적으로 생성하려면 쿼리에 다음 매개변수를 전달해야 합니다.

{
    "name": "string",
    "occupation": "string",
    "date_of_birth": "string",
    "suspect": boolean
}
Salin selepas log masuk
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.

Character ordering

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.

Character filtering

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.

Character search

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

Update a character

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
}
Salin selepas log masuk
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.

Delete a character

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}

Locations

Retrieve all locations

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"
        }
    },
]
Salin selepas log masuk

Retrieve a single location

To retrieve a single location, pass the locations ID to the endpoint.

GET /api/locations/{id}

Create a new location

You can use the POST method to /locations/ endpoint to create a new location.

POST /api/locations/

Creation parameters

You will need to pass the following parameters in the query, to successfully create a location:

{
    "name": "string",
    "longitude": float,
    "latitude": float,
    "character": integer
}
Salin selepas log masuk
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.

Location ordering

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.

Locaton filtering

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.

Update a location

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
    }
}
Salin selepas log masuk
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.

Delete a 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}

Atas ialah kandungan terperinci Memburu Heisenberg dengan Rangka Kerja Django Rest. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan