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 小时前
从一段 WebSocket 代码聊开:bytes 不是 zlib、binaryType 决定一切,15MB 大消息的零拷贝优化
javascript·python·websocket·性能优化·blob·zlib·arraybuffer
这个DBA有点耶16 小时前
函数索引的“完全一致”有多苛刻:写法、字符集、类型,差一处就失效
数据库·mysql·代码规范
星恒随风16 小时前
MySQL 从零入门(三):表的约束详解
linux·服务器·数据库·笔记·mysql
卷无止境17 小时前
mathmodel-figure-templates 以及两个上手案例
后端·python
锋行天下17 小时前
服务器 Python 2.7 装不了 langgraph-cli?用本地生成 Dockerfile 曲线救国
人工智能·后端·python
一条大祥脚17 小时前
深入理解 PyTorch FlexAttention:从 Score Mod 到 Mask Mod 的稀疏加速之道
人工智能·pytorch·python·注意力机制·flex attention·可编程注意力
2601_9679801118 小时前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
长沙三为智能科技19 小时前
GEO与传统SEO的5个关键差异:排名与被引用、关键词与答案型的全维度对比
python·aigc·seo·ai搜索·geo优化
量化分析码农20 小时前
【Python量化趋势跟踪实战 02】突破买入总被假突破坑:通道系统与入场时机
python
Agent世界20 小时前
多平台登录态巡检:cookie 判据为什么会撒谎
python