iT邦幫忙

0

[Flutter ] 為Flutter 建立 Django 資料庫

  • 分享至 

  • xImage
  •  

version:
python 3.8.3
django 3.2.4

建立名為 NOTES,APP名為 api 的 Django 專案
Django

Django REST framework

其安裝 rest_framework、corsheaders,程式碼設置如下:
(給Flutter資料庫為目的,分享 python 的資料滿地都是,在此不多做詳註)
NOTES/notes/settings.py

DEBUG = True
ALLOWED_HOSTS = [
    'http://127.0.0.1:8000', #
    'localhost', 
    '127.0.0.1', 
    '172.20.10.4', # 在 terminal 輸入 ipconfig 查電腦 IPv4 位址
]

INSTALLED_APPS = [
    ...
    'api.apps.ApiConfig',
    'rest_framework',
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

# 先不求甚解,全給他開通
CORS_ALLOW_ALL_ORIGINS = True

NOTES/notes/url.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # 開條路給 api APP
    path('', include('api.urls')), 
]

NOTES/api/models.py

from django.db import models

class Note(models.Model):
    title = models.TextField()
    body = models.TextField()
    updated = models.DateField(auto_now=True)
    created = models.DateField(auto_now_add=True)

    class Meta:
        ordering = ['-updated']

NOTES/api/admin.py

from django.contrib import admin
from .models import Note
#admin.site.register(Note)
@admin.register(Note)
class BlogTypeDocument(admin.ModelAdmin):
    list_per_page = 10
    list_display = ('title', 'body')

NOTES/api/serializers.py

from django.db import models
from rest_framework.serializers import ModelSerializer
from .models import Note

class NoteSerializer(ModelSerializer):
    class Meta:
        model = Note
        fields = '__all__'

NOTES/api/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.getRoutes),
    path('notes/', views.getNotes),
    path('notes/create/', views.createNote),
    path('notes/<str:pk>/update/', views.updateNote),
    path('notes/<str:pk>/delete/', views.deleteNote),
    path('notes/<str:pk>/', views.getNote),
]

NOTES/api/views.py

from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import NoteSerializer
from .models import Note

@api_view(['GET'])
def getRoutes(reqyest):
    routes = [
        {
            'Endpoint' : '/notes/',
            'mothod' : 'GET',
            'body' : None,
        },
        {
            'Endpoint' : '/notes/id',
            'mothod' : 'GET',
            'body' : None,
        },
        {
            'Endpoint' : '/notes/create/',
            'mothod' : 'POST',
            'body' : None,
        },
        {
            'Endpoint' : '/notes/update/',
            'mothod' : 'PUT',
            'body' : {'body':""},
        },
        {
            'Endpoint' : '/notes/delete/',
            'mothod' : 'DELETE',
            'body' : None,
        },
    ]

    #return JsonResponse(routes, safe=False)
    return Response(routes)

@api_view(['GET'])
def getNotes(request):
    notes = Note.objects.all()
    serializer = NoteSerializer(notes, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def getNote(request, pk):
    note = Note.objects.get(id=pk)
    serializer = NoteSerializer(note, many=False)
    return Response(serializer.data)

@api_view(['POST'])
def createNote(request):
    data = request.data

    note = Note.objects.create(
        body=data['body']
    )
    serializers = NoteSerializer(note, many=False)
    return Response(serializers.data)

@api_view(['PUT'])
def updateNote(request, pk):
    data = request.data

    note = Note.objects.get(id=pk)
    serializers = NoteSerializer(note, data=request.Post)
    if serializers.is_valid():
        serializers.save()
    return Response(serializers.data)

@api_view(['DELETE'])
def deleteNote(request, pk):

    note = Note.objects.get(id=pk)
    note.delete()
    return Response("Note was deleted")

以上完成後開啟 runserver
進入 NOTES 輸入一些資料以便 flutter 呈現

python manage.py runserver 0.0.0.0:8000

接續: Django 為資料庫,以 FutureBuilder + http 抓取

註: 小白自學,歡迎評論指導!
參考資料:
https://stackoverflow.com/questions/59700218/run-django-app-through-ip-address-allowed-host


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言