先看我本地的项目结构
1 设置虚拟环境
python -m venv venv
.\venv\Scripts\activate
2 在虚拟环境中安装Django
执行 pip install -r requirements.txt
asgiref==3.8.1
backports.zoneinfo==0.2.1
Django==3.2
mysqlclient==2.2.4
pytz==2024.2
sqlparse==0.5.1
typing-extensions==4.12.2
tzdata==2024.2
3 在虚拟环境中创建一个新的Django项目:
django-admin startproject myproject
cd myproject
4 在项目中创建一个应用,例如myapp:
python manage.py startapp myapp
5 定义模型,提前建好表
在myapp/models.py中定义Book模型,但不需要使用makemigrations和migrate,因为数据库表已经提前创建好了.
CREATE TABLE `book` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`remark` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
from django.db import modelsclass Book(models.Model):name = models.CharField(max_length=255)remark = models.CharField(max_length=255)class Meta:db_table = 'book' # 确保这与你的数据库表名匹配
6 在myproject/settings.py中配置MySQL数据库连接
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'test','USER': 'root','PASSWORD': 'root','HOST': 'localhost', # Or an IP Address that your DB is hosted on'PORT': '3306',}
}
文件里面的CsrfViewMiddleware要注释掉
7 在myapp/views.py中,使用原生SQL实现增删改查,并返回JSON结果
from django.shortcuts import render# Create your views here.
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import connection# Create a new book
# @csrf_exempt
def create_book(request):if request.method == 'POST':data = request.POSTname = data.get('name')print(12312)print(name)remark = data.get('remark')with connection.cursor() as cursor:cursor.execute("INSERT INTO book (name, remark) VALUES (%s, %s)", [name, remark])return JsonResponse({'message': 'Book created successfully', 'status': 200})else:return JsonResponse({'error': 'Invalid request', 'status': 201})# Update an existing book
# @csrf_exempt
def update_book(request):if request.method == 'POST':data = request.POSTname = data.get('name')remark = data.get('remark')id = data.get('id')with connection.cursor() as cursor:cursor.execute("UPDATE book SET name = %s, remark = %s WHERE id = %s", [name, remark, id])if cursor.rowcount == 0:return JsonResponse({'error': 'Book not found', 'status': 201})return JsonResponse({'message': 'Book updated successfully', 'status': 200})else:return JsonResponse({'error': 'Invalid request', 'status': 201})# Delete a book
# @csrf_exempt
def delete_book(request):if request.method == 'POST':data = request.POSTid = data.get('id')with connection.cursor() as cursor:cursor.execute("DELETE FROM book WHERE id = %s", [id])if cursor.rowcount == 0:return JsonResponse({'error': 'Book not found', 'status': 201})return JsonResponse({'message': 'Book deleted successfully', 'status': 200})else:return JsonResponse({'error': 'Invalid request', 'status': 201})# List all books
def list_books(request):with connection.cursor() as cursor:cursor.execute("SELECT id, name, remark FROM book")books = cursor.fetchall()return JsonResponse({'books': books, 'status': 200}, safe=False)
8 在myapp/urls.py中配置URL路径:
from django.urls import path
from . import viewsurlpatterns = [path('books', views.list_books, name='list_books'),path('books/create', views.create_book, name='create_book'),path('books/update', views.update_book, name='update_book'),path('books/delete', views.delete_book, name='delete_book'),# 添加其他URL路径
]
9 在myproject/urls.py中包含myapp的URL
from django.contrib import admin
from django.urls import include, pathurlpatterns = [path('admin/', admin.site.urls),path('api/', include('myapp.urls')), # 注意这里的'api/'
]
10 启动
python manage.py runserver
查
添加
编辑
删除
部署到linux的步骤,没有写,,。。。