cari
Rumahpembangunan bahagian belakangTutorial PythonMemburu Heisenberg dengan Rangka Kerja Django Rest

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
</secret>

참고: 원하는 경우 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)

캐릭터

모든 문자 검색

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

/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를 enpoint에 전달하세요.

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

새 캐릭터 만들기

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

포스트 /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}

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

Kenyataan
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
Cara Menggunakan Python untuk Mencari Pengagihan Zipf Fail TeksCara Menggunakan Python untuk Mencari Pengagihan Zipf Fail TeksMar 05, 2025 am 09:58 AM

Tutorial ini menunjukkan cara menggunakan Python untuk memproses konsep statistik undang -undang ZIPF dan menunjukkan kecekapan membaca dan menyusun fail teks besar Python semasa memproses undang -undang. Anda mungkin tertanya -tanya apa maksud pengedaran ZIPF istilah. Untuk memahami istilah ini, kita perlu menentukan undang -undang Zipf. Jangan risau, saya akan cuba memudahkan arahan. Undang -undang Zipf Undang -undang Zipf hanya bermaksud: Dalam korpus bahasa semulajadi yang besar, kata -kata yang paling kerap berlaku muncul kira -kira dua kali lebih kerap sebagai kata -kata kerap kedua, tiga kali sebagai kata -kata kerap ketiga, empat kali sebagai kata -kata kerap keempat, dan sebagainya. Mari kita lihat contoh. Jika anda melihat corpus coklat dalam bahasa Inggeris Amerika, anda akan melihat bahawa perkataan yang paling kerap adalah "th

Bagaimana saya menggunakan sup yang indah untuk menghuraikan html?Bagaimana saya menggunakan sup yang indah untuk menghuraikan html?Mar 10, 2025 pm 06:54 PM

Artikel ini menerangkan cara menggunakan sup yang indah, perpustakaan python, untuk menghuraikan html. Ia memperincikan kaedah biasa seperti mencari (), find_all (), pilih (), dan get_text () untuk pengekstrakan data, pengendalian struktur dan kesilapan HTML yang pelbagai, dan alternatif (sel

Penapisan gambar di pythonPenapisan gambar di pythonMar 03, 2025 am 09:44 AM

Berurusan dengan imej yang bising adalah masalah biasa, terutamanya dengan telefon bimbit atau foto kamera resolusi rendah. Tutorial ini meneroka teknik penapisan imej di Python menggunakan OpenCV untuk menangani isu ini. Penapisan Imej: Alat yang berkuasa Penapis Imej

Bagaimana untuk melakukan pembelajaran mendalam dengan Tensorflow atau Pytorch?Bagaimana untuk melakukan pembelajaran mendalam dengan Tensorflow atau Pytorch?Mar 10, 2025 pm 06:52 PM

Artikel ini membandingkan tensorflow dan pytorch untuk pembelajaran mendalam. Ia memperincikan langkah -langkah yang terlibat: penyediaan data, bangunan model, latihan, penilaian, dan penempatan. Perbezaan utama antara rangka kerja, terutamanya mengenai grap pengiraan

Pengenalan kepada pengaturcaraan selari dan serentak di PythonPengenalan kepada pengaturcaraan selari dan serentak di PythonMar 03, 2025 am 10:32 AM

Python, kegemaran sains dan pemprosesan data, menawarkan ekosistem yang kaya untuk pengkomputeran berprestasi tinggi. Walau bagaimanapun, pengaturcaraan selari dalam Python memberikan cabaran yang unik. Tutorial ini meneroka cabaran -cabaran ini, memberi tumpuan kepada Interprete Global

Cara Melaksanakan Struktur Data Anda Sendiri di PythonCara Melaksanakan Struktur Data Anda Sendiri di PythonMar 03, 2025 am 09:28 AM

Tutorial ini menunjukkan mewujudkan struktur data saluran paip tersuai di Python 3, memanfaatkan kelas dan pengendali yang berlebihan untuk fungsi yang dipertingkatkan. Fleksibiliti saluran paip terletak pada keupayaannya untuk menggunakan siri fungsi ke set data, GE

Serialization dan deserialisasi objek python: Bahagian 1Serialization dan deserialisasi objek python: Bahagian 1Mar 08, 2025 am 09:39 AM

Serialization dan deserialization objek Python adalah aspek utama dari mana-mana program bukan remeh. Jika anda menyimpan sesuatu ke fail python, anda melakukan siri objek dan deserialization jika anda membaca fail konfigurasi, atau jika anda menjawab permintaan HTTP. Dalam erti kata, siri dan deserialization adalah perkara yang paling membosankan di dunia. Siapa yang peduli dengan semua format dan protokol ini? Anda mahu berterusan atau mengalirkan beberapa objek python dan mengambilnya sepenuhnya pada masa yang akan datang. Ini adalah cara yang baik untuk melihat dunia pada tahap konseptual. Walau bagaimanapun, pada tahap praktikal, skim siri, format atau protokol yang anda pilih boleh menentukan kelajuan, keselamatan, kebebasan status penyelenggaraan, dan aspek lain dari program

Modul Matematik dalam Python: StatistikModul Matematik dalam Python: StatistikMar 09, 2025 am 11:40 AM

Modul Statistik Python menyediakan keupayaan analisis statistik data yang kuat untuk membantu kami dengan cepat memahami ciri -ciri keseluruhan data, seperti biostatistik dan analisis perniagaan. Daripada melihat titik data satu demi satu, cuma melihat statistik seperti min atau varians untuk menemui trend dan ciri dalam data asal yang mungkin diabaikan, dan membandingkan dataset besar dengan lebih mudah dan berkesan. Tutorial ini akan menjelaskan cara mengira min dan mengukur tahap penyebaran dataset. Kecuali dinyatakan sebaliknya, semua fungsi dalam modul ini menyokong pengiraan fungsi min () dan bukan hanya menjumlahkan purata. Nombor titik terapung juga boleh digunakan. Import secara rawak Statistik import dari fracti

See all articles

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Alat panas

mPDF

mPDF

mPDF ialah perpustakaan PHP yang boleh menjana fail PDF daripada HTML yang dikodkan UTF-8. Pengarang asal, Ian Back, menulis mPDF untuk mengeluarkan fail PDF "dengan cepat" dari tapak webnya dan mengendalikan bahasa yang berbeza. Ia lebih perlahan dan menghasilkan fail yang lebih besar apabila menggunakan fon Unicode daripada skrip asal seperti HTML2FPDF, tetapi menyokong gaya CSS dsb. dan mempunyai banyak peningkatan. Menyokong hampir semua bahasa, termasuk RTL (Arab dan Ibrani) dan CJK (Cina, Jepun dan Korea). Menyokong elemen peringkat blok bersarang (seperti P, DIV),

SublimeText3 versi Inggeris

SublimeText3 versi Inggeris

Disyorkan: Versi Win, menyokong gesaan kod!

Dreamweaver Mac版

Dreamweaver Mac版

Alat pembangunan web visual

Muat turun versi mac editor Atom

Muat turun versi mac editor Atom

Editor sumber terbuka yang paling popular

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa