> 백엔드 개발 > 파이썬 튜토리얼 > Django Rest Framework로 Heisenberg 사냥하기

Django Rest Framework로 Heisenberg 사냥하기

DDD
풀어 주다: 2024-10-15 22:14:02
원래의
478명이 탐색했습니다.

Hunting Heisenberg with Django Rest Framework

アイデア

そのアイデアは、DEA 捜査官向けのシンプルなプラットフォームを作成し、ブレイキング バッド/ベター コール ソウルの世界のキャラクターに関する情報を管理することでした。 DEA 捜査官の業務を楽にするためには、登場人物に関する情報を名前、生年月日、職業、容疑者であるかどうかなどでフィルタリングできる API エンドポイントが必要です。

DEA は麻薬組織を刑務所に入れようとしているため、麻薬組織とその周囲の人々を追跡しています。タイムスタンプと特定の場所を地理座標として関連テーブルに保存します。データを公開するエンドポイントでは、特定の地理的地点から特定の距離内にある位置エントリ、割り当て先、および記録時の日時範囲のフィルタリングを許可する必要があります。このエンドポイントの順序付けでは、指定された地理的地点からの距離 (昇順と降順の両方) を考慮できるようにする必要があります。

それがどのように行われたかを確認するには、以下のドキュメントに従ってこのプロジェクトをローカルにセットアップし、自分でテストしてください。

コードは私の GitHub リポジトリにあります。

プロジェクトのセットアップ

前提条件として、システムに Dockerdocker-compose がインストールされている必要があります。

まず、プロジェクトのフォルダーに移動し、Breaking Bad API リポジトリのクローンを作成します。

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

CD ブレイキング・バッド 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

これにより、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)
로그인 후 복사

キャラクター

すべての文字を取得する

データベース内のすべての既存の文字を取得します。

GET /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
    }
]
로그인 후 복사

単一の文字を取得する

単一の文字を取得するには、その文字の ID をエンポイントに渡します。

GET /api/characters/{id}

新しいキャラクターを作成する

新しいキャラクターを作成するには、/characters/ エンドポイントへの POST メソッドを使用できます。

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.

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
}
로그인 후 복사
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"
        }
    },
]
로그인 후 복사

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
}
로그인 후 복사
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
    }
}
로그인 후 복사
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}

위 내용은 Django Rest Framework로 Heisenberg 사냥하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿