Building RESTful APIs with Django/Python

thuymaiphamthuc

New member
## Xây dựng API RESTful với Django/Python

API RESTful là một lựa chọn phổ biến để xây dựng các ứng dụng web hiện đại.Chúng rất dễ sử dụng, có thể mở rộng và được ghi chép tốt.Django là một khung Python giúp dễ dàng xây dựng các ứng dụng web phức tạp.Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách xây dựng một API yên tĩnh với Django và Python.

### Điều kiện tiên quyết

Để làm theo hướng dẫn này, bạn sẽ cần những điều sau đây:

* Một môi trường phát triển Python.Chúng tôi khuyên bạn nên sử dụng [pycharm] (https://www.jetbrains.com/pycharm/).
* [Khung django] (https://www.djangoproject.com/).
* [Djangorestframework] (https://www.django-rest-framework.org/).

### Tạo một dự án mới

Đầu tiên, chúng ta cần tạo một dự án Django mới.Chúng tôi có thể làm điều này bằng cách chạy lệnh sau trong thiết bị đầu cuối của chúng tôi:

`` `
Django-admin StartProject MyProject
`` `

Điều này sẽ tạo ra một thư mục mới gọi là `myproject`.Bên trong thư mục này, bạn sẽ tìm thấy một số tệp và thư mục.Các tệp quan trọng nhất là `Manage.py` và` myProject/settings.py`.

### Cấu hình dự án

Chúng ta cần định cấu hình dự án của mình để sử dụng gói `djangorestframework`.Để thực hiện việc này, hãy mở tệp `myProject/settings.py` và thêm các dòng sau vào danh sách` install_apps`:

`` `
'rest_framework',
`` `

Chúng tôi cũng cần thêm các dòng sau vào danh sách `middleware`:

`` `
'django.middleware.security.securitymiddleware',
'django.contrib.sessions.middleware.sessionMiddleware',
'django.middleware.common.commonmiddleware',
'django.middleware.csrf.csrfviewmiddleware',
'Django.Contrib.Auth.MiddleWare.AuthenticationMiddleWare',
'django.contrib.messages.middleware.messagemiddleware',
'django.middleware.clickjacking.xframeoptionsmiddleware',
`` `

### Tạo chế độ xem API mới

Bây giờ chúng ta có thể tạo một chế độ xem API mới.Để thực hiện việc này, hãy mở tệp `myProject/api/views.py` và thêm mã sau:

`` `Python
Từ REST_FRAMEWORK METERSTS

từ .Models nhập bài viết

Lớp bài viếtviewset (ViewSets.ModelViewset):
queryset = pritse.Objects.all ()
serializer_class = articleerializer
`` `

Mã này tạo ra một chế độ xem mới gọi là `articleViewset`.Thuộc tính `queryset` chỉ định truy vấn mà ViewSet sẽ sử dụng để truy xuất dữ liệu từ cơ sở dữ liệu.Thuộc tính `serializer_class` chỉ định lớp serializer mà viewset sẽ sử dụng để tuần tự hóa và khử dữ liệu.

### Tạo một serializer mới

Chúng tôi cũng cần tạo ra một serializer mới cho các bài viết của chúng tôi.Để thực hiện việc này, hãy mở tệp `myProject/api/serializer.py` và thêm mã sau:

`` `Python
từ rest_framework serializer

từ .Models nhập bài viết

Lớp bài viết (serializer.modelserializer):
title = serializer.charfield (max_length = 255)
nội dung = serializer.charfield (max_length = 10000)

Lớp Meta:
Model = Bài báo
Các trường = ('Tiêu đề', 'Nội dung')
`` `

Mã này tạo ra một lớp serializer mới có tên là `articleerializer`.Thuộc tính `Field` chỉ định các trường sẽ được tuần tự hóa và phân rã.

### Kiểm tra API

Bây giờ chúng tôi có thể kiểm tra API của chúng tôi.Để làm điều này, chúng ta có thể sử dụng [Django Rest Framework API có thể duyệt] (https://www.django-rest-framework.org/tutorial/3-class-c bảnĐể truy cập API có thể duyệt, hãy mở URL sau trong trình duyệt của bạn:

`` `
http: // localhost: 8000/api/
`` `

Bạn sẽ thấy một danh sách tất cả các bài viết trong cơ sở dữ liệu của bạn.Bạn cũng có thể nhấp vào một bài viết riêng lẻ để xem chi tiết của nó.

### Bản tóm tắt
=======================================
## Building Restful APIs with Django/Python

RESTful APIs are a popular choice for building modern web applications. They are easy to use, scalable, and well-documented. Django is a Python framework that makes it easy to build complex web applications. In this tutorial, we will show you how to build a RESTful API with Django and Python.

### Prerequisites

To follow this tutorial, you will need the following:

* A Python development environment. We recommend using [PyCharm](https://www.jetbrains.com/pycharm/).
* The [Django framework](https://www.djangoproject.com/).
* The [djangorestframework](https://www.django-rest-framework.org/) package.

### Creating a new project

First, we need to create a new Django project. We can do this by running the following command in our terminal:

```
django-admin startproject myproject
```

This will create a new directory called `myproject`. Inside this directory, you will find a number of files and folders. The most important files are `manage.py` and `myproject/settings.py`.

### Configuring the project

We need to configure our project to use the `djangorestframework` package. To do this, open the `myproject/settings.py` file and add the following lines to the `INSTALLED_APPS` list:

```
'rest_framework',
```

We also need to add the following lines to the `MIDDLEWARE` list:

```
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
```

### Creating a new API view

Now we can create a new API view. To do this, open the `myproject/api/views.py` file and add the following code:

```python
from rest_framework import viewsets

from .models import Article

class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
```

This code creates a new viewset called `ArticleViewSet`. The `queryset` property specifies the queryset that the viewset will use to retrieve data from the database. The `serializer_class` property specifies the serializer class that the viewset will use to serialize and deserialize data.

### Creating a new serializer

We also need to create a new serializer for our articles. To do this, open the `myproject/api/serializers.py` file and add the following code:

```python
from rest_framework import serializers

from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
title = serializers.CharField(max_length=255)
content = serializers.CharField(max_length=10000)

class Meta:
model = Article
fields = ('title', 'content')
```

This code creates a new serializer class called `ArticleSerializer`. The `fields` property specifies the fields that will be serialized and deserialized.

### Testing the API

Now we can test our API. To do this, we can use the [Django REST Framework Browsable API](https://www.django-rest-framework.org/tutorial/3-class-based-views/#browsable-api). To access the browsable API, open the following URL in your browser:

```
```

You should see a list of all the articles in your database. You can also click on an individual article to view its details.

### Summary
 
Làm thế nào để tạo một chế độ xem Django trả về phản hồi JSON với danh sách tất cả người dùng trong cơ sở dữ liệu?
 
Join ToolsKiemTrieuDoGroup
Back
Top
AdBlock Detected

We get it, advertisements are annoying!

Sure, ad-blocking software does a great job at blocking ads, but it also blocks useful features of our website. For the best site experience please disable your AdBlocker.

I've Disabled AdBlock