您好,登錄后才能下訂單哦!
Django REST框架(DRF)和Flask是兩個(gè)不同的Python Web框架,它們都可以用來(lái)構(gòu)建API。這里我將分別介紹如何使用Django REST框架和Flask來(lái)構(gòu)建API。
首先,確保已經(jīng)安裝了Django REST框架。如果沒有安裝,可以使用以下命令安裝:
pip install djangorestframework
接下來(lái),創(chuàng)建一個(gè)新的Django項(xiàng)目和應(yīng)用:
django-admin startproject myproject
cd myproject
django-admin startapp myapp
在myproject/settings.py
中,將rest_framework
添加到INSTALLED_APPS
列表中:
INSTALLED_APPS = [
# ...
'rest_framework',
'myapp',
]
現(xiàn)在,我們可以在myapp
中創(chuàng)建一個(gè)簡(jiǎn)單的模型。例如,創(chuàng)建一個(gè)Book
模型:
# myapp/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
def __str__(self):
return self.title
接下來(lái),創(chuàng)建一個(gè)序列化器來(lái)將模型實(shí)例轉(zhuǎn)換為JSON格式:
# myapp/serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author']
然后,創(chuàng)建一個(gè)視圖來(lái)處理API請(qǐng)求:
# myapp/views.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
最后,在myproject/urls.py
中配置路由:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
# ...
path('', include(router.urls)),
]
現(xiàn)在,你可以運(yùn)行Django開發(fā)服務(wù)器并訪問(wèn)API:
python manage.py runserver
訪問(wèn)http://127.0.0.1:8000/books/
,你將看到所有書籍的列表。
首先,確保已經(jīng)安裝了Flask。如果沒有安裝,可以使用以下命令安裝:
pip install flask
接下來(lái),創(chuàng)建一個(gè)新的Flask應(yīng)用:
# app.py
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db'
db = SQLAlchemy(app)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
author = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f'<Book {self.title}>'
db.create_all()
@app.route('/books', methods=['POST'])
def create_book():
data = request.get_json()
new_book = Book(title=data['title'], author=data['author'])
db.session.add(new_book)
db.session.commit()
return jsonify(new_book.__dict__), 201
@app.route('/books', methods=['GET'])
def get_books():
books = Book.query.all()
return jsonify([book.__dict__ for book in books])
if __name__ == '__main__':
app.run(debug=True)
現(xiàn)在,你可以運(yùn)行Flask應(yīng)用并訪問(wèn)API:
python app.py
訪問(wèn)http://127.0.0.1:5000/books/
,你將看到所有書籍的列表。使用POST請(qǐng)求向http://127.0.0.1:5000/books/
發(fā)送JSON數(shù)據(jù),可以創(chuàng)建新的書籍。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。