python-django-mysql原生sql增删改查搭建搭建web项目

先看我本地的项目结构

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 models

class 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.POST
        name = 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.POST
        name = 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.POST
        id = 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 views

urlpatterns = [
    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, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),  # 注意这里的'api/'
]

10 启动

python manage.py runserver

添加

编辑

删除

部署到linux的步骤,没有写,,。。。

相关推荐
路在脚下@15 分钟前
spring boot的配置文件属性注入到类的静态属性
java·spring boot·sql
苹果醋31 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
算法小白(真小白)2 小时前
低代码软件搭建自学第二天——构建拖拽功能
python·低代码·pyqt
唐小旭2 小时前
服务器建立-错误:pyenv环境建立后python版本不对
运维·服务器·python
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
别致的影分身3 小时前
使用C语言连接MySQL
数据库·mysql
过过过呀Glik3 小时前
在 Ubuntu 上安装 MySQL 的详细指南
mysql·ubuntu
Chinese Red Guest3 小时前
python
开发语言·python·pygame
骑个小蜗牛3 小时前
Python 标准库:string——字符串操作
python