Wasp vs Django:构建全栈应用程序变得更加容易
嘿,我是 Sam,一位拥有丰富 Django 经验的后端工程师。我想跳跃并学习一些全栈应用程序的前端。我很快就体验到了 React-with-Django 项目的艰巨性,并认为痛苦只是开发过程的一部分。然而,我遇到了一个非常酷的新全栈框架,名为 Wasp。
Wasp 是一款出色的全栈应用程序开发工具。 Wasp 结合了 React、Node.js 和 Prisma 等技术,能够以前所未有的方式加快开发速度。
在本文中,我将介绍在 Django 和 Wasp 中创建全栈应用程序,以证明 Wasp 相对于非常传统的全栈技术的简单性。我还将制作一个连接到 Django 的 React 前端。重点是强调 Django/react 可能(并将)出现的低效率、困难和问题,这些问题通过
变得更加简单本文无意作为指导,但我确实提供了一些代码来强调 Django 应用程序的详尽性质。
第 1 部分:要有光!
让我们创建一些项目并进行设置
这部分是 Django 和 Wasp 之间唯一有明显重叠的部分。从终端开始,让我们制作一个简单的任务应用程序(我假设您已经安装了 Django 和 Wasp,并且位于您的路径中)。
姜戈 ?
django-admin startproject python manage.py starapp Todo
黄蜂 ?
wasp new Todo wasp start
现在黄蜂一开始就很火爆。查看下面为您提供的菜单。 Wasp 可以为您启动一个基本应用程序,或者您可以从大量预制模板(包括功能齐全的 SaaS 应用程序)中进行选择,甚至可以根据您的描述使用 AI 生成的应用程序!
同时,Django 作为一个项目运行,项目内有应用程序(同样,这基本上都是用于后端操作),并且一个 Django 项目可以有多个应用程序。因此,您必须在 Django 项目设置中注册每个应用程序。
python `manage.py` startapp todo
settings.py:
INSTALLED_APPS [ ... 'Todo' ]
数据库时间
所以现在我们需要一个数据库,这是 Wasp 真正擅长的另一个领域。使用 Django,我们需要在 models.py 文件中创建模型。与此同时,Wasp 使用 Prisma 作为 ORM,它允许我们清楚地定义必要的字段,并以易于理解的方式使数据库创建变得简单。
姜戈 ?
models.py:
from django.db import models class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) def __str__(self): return self.title
黄蜂 ?
schema.prisma:
model Task { id Int @id @default(autoincrement()) description String isDone Boolean @default(false) }
Django 和 Wasp 确实共享相似的数据库迁移方法:
姜戈 ?
python manage.py makemigrations python manage.py migrate
黄蜂 ?
wasp db migrate-dev
但是使用 Wasp,您还可以做一些 Django 做不到的非常漂亮的数据库事情。
现在我们正在使用 SQLite,但是立即设置一个开发 Posgres 数据库怎么样?黄蜂可以通过以下方式做到这一点:
wasp db start
就是这样!这样您就拥有了一个运行 Postgres 实例的 docker 容器,并且它会立即连接到您的 Wasp 应用程序。 ?
或者,如果您想通过 Prisma 的数据库工作室 UI 实时查看数据库该怎么办,如果没有 Django 的第三方扩展,这是不可能实现的。为此,只需运行:
wasp db studio
你现在开始明白我的意思了吗?
路线
Django 和 Wasp 中的路由遵循某种类似的模式。然而,如果你熟悉 React,那么 Wasp 的系统要优越得多。
Django 通过后端(views.py,我将在本文后面介绍)来执行所有 CRUD 操作。这些视图函数与项目内应用程序内的特定路由相关联(我知道很多),如果您开始使用主键和 ID,它可能会变得更加复杂。您需要创建一个 urls.py 文件并将特定视图文件和函数定向到路由。然后,这些应用程序 URL 将连接到项目 URL。唷。
Wasp 的方式:定义一个路由并将其定向到组件。
姜戈 ?
todo/urls.py:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('update/<pk>/', views.updateTask, name='update_task'), path('delete/<pk>/', views.deleteTask, name='delete_task'), ] </pk></pk>
./urls.py:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('todo.urls')), ]
黄蜂 ?
main.wasp:
route TaskRoute { path: "/", to: TaskPage } page TaskPage { component: import { TaskPage } from "@src/TaskPage" }
增删改查
好吧,这就是 Wasp 的好处将变得更加明显的地方。
Firstly, I am going to revisit the views.py file. This is where magic is going to happen for Django backend. Here is a simple version of what the create, update, and delete functions could look like for our Task/Todo example:
Django ?
todo/views.py:
from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks': tasks, 'form': form} return render(request, 'todo/index.html', context) def updateTask(request, pk): task = Task.objects.get(id=pk) form = TaskForm(instance=task) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'todo/update_task.html', context) def deleteTask(request, pk): task = Task.objects.get(id=pk) if request.method == 'POST': task.delete() return redirect('/') context = {'task': task} return render(request, 'todo/delete.html', context)
app/forms.py:
from django import forms from .models import Task class TaskForm(forms.ModelForm): class Meta: model = Task fields = ['title', 'completed']
Wasp ?
main.wasp:
query getTasks { fn: import { getTasks } from "@src/operations", // Tell Wasp that this operation affects the `Task` entity. Wasp will automatically // refresh the client (cache) with the results of the operation when tasks are modified. entities: [Task] } action updateTask { fn: import { updateTask } from "@src/operations", entities: [Task] } action deleteTask { fn: import { deleteTask } from "@src/operations", entities: [Task] }
operations.js:
export const getTasks = async (args, context) => { return context.entities.Task.findMany({ orderBy: { id: 'asc' }, }) } export const updateTask = async ({ id, data }, context) => { return context.entities.Task.update({ where: { id }, data }) } export const deleteTask = async ({ id }, context) => { return context.entities.Task.delete({ where: { id } }) }
So right now, Wasp has a fully functioning backend with middleware configured for you. At this point we can create some React components, and then import and call these operations from the client. That is not the case with Django, unfortunately there is still a lot we need to do to configure React in our app and get things working together, which we will look at below.
Part 2: So you want to use React with Django?
At this point we could just create a simple client with HTML and CSS to go with our Django app, but then this wouldn't be a fair comparison, as Wasp is a true full-stack framework and gives you a managed React-NodeJS-Prisma app out-of-the-box. So let's see what we'd have to do to get the same thing set up with Django.
Note that this section is going to highlight Django, so keep in mind that you can skip all the following steps if you just use Wasp. :)
Django ?
First thing’s first. Django needs a REST framework and CORS (Cross Origin Resource Sharing):
pip install djangorestframework pip install django-cors-headers
Include Rest Framework and Cors Header as installed apps, CORS headers as middleware, and then also set a local host for the react frontend to be able to communicate with the backend (Django) server (again, there is no need to do any of this initial setup in Wasp as it's all handled for you).
settings.py:
INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ]
And now a very important step, which is to serialize all the data from Django to be able to work in json format for React frontend.
app/serializers.py:
from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__'
Now, since we are handling CRUD on the React side, we can change the views.py file:
from rest_framework import viewsets from .models import Task from .serializers import TaskSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer
And now we need to change both app and project URLS since we have a frontend application on a different url than our backend.
urls.py:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('todo.urls')), # Add this line ]
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import TaskViewSet router = DefaultRouter() router.register(r'tasks', TaskViewSet) urlpatterns = [ path('', include(router.urls)), ]
By now you should be understanding why I've made the switch to using Wasp when building full-stack apps. Anyways, now we are actually able to make a react component with a Django backend ?
React time
Ok, so now we can actually get back to comparing Wasp and Django.
Django ?
To start, lets create our React app in our Django project:
npx create-react-app frontend
Finally, we can make a component in React. A few things:
I am using axios in the Django project here. Wasp comes bundled with React-Query (aka Tanstack Query), so the execution of (CRUD) operations is a lot more elegant and powerful.
The api call is to my local server, obviously this will change in development.
You can make this many different ways, I tried to keep it simple.
main.jsx:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const TaskList = () => { const [tasks, setTasks] = useState([]); const [newTask, setNewTask] = useState(''); const [editingTask, setEditingTask] = useState(null); useEffect(() => { fetchTasks(); }, []); const fetchTasks = () => { axios.get('http://127.0.0.1:8000/api/tasks/') .then(response => { setTasks(response.data); }) .catch(error => { console.error('There was an error fetching the tasks!', error); }); }; const handleAddTask = () => { if (newTask.trim()) { axios.post('http://127.0.0.1:8000/api/tasks/', { title: newTask, completed: false }) .then(() => { setNewTask(''); fetchTasks(); }) .catch(error => { console.error('There was an error adding the task!', error); }); } }; const handleUpdateTask = (task) => { axios.put(`http://127.0.0.1:8000/api/tasks/${task.id}/`, task) .then(() => { fetchTasks(); setEditingTask(null); }) .catch(error => { console.error('There was an error updating the task!', error); }); }; const handleDeleteTask = (taskId) => { axios.delete(`http://127.0.0.1:8000/api/tasks/${taskId}/`) .then(() => { fetchTasks(); }) .catch(error => { console.error('There was an error deleting the task!', error); }); }; const handleEditTask = (task) => { setEditingTask(task); }; const handleChange = (e) => { setNewTask(e.target.value); }; const handleEditChange = (e) => { setEditingTask({ ...editingTask, title: e.target.value }); }; const handleEditCompleteToggle = () => { setEditingTask({ ...editingTask, completed: !editingTask.completed }); }; return ( <div> <h1 id="To-Do-List">To-Do List</h1> <input type="text" value="{newTask}" onchange="{handleChange}" placeholder="Add new task"> <button onclick="{handleAddTask}">Add Task</button> <ul> {tasks.map(task => ( <li key="{task.id}"> {editingTask && editingTask.id === task.id ? ( <div> <input type="text" value="{editingTask.title}" onchange="{handleEditChange}"> <button onclick="{()"> handleUpdateTask(editingTask)}>Save</button> <button onclick="{()"> setEditingTask(null)}>Cancel</button> <button onclick="{handleEditCompleteToggle}"> {editingTask.completed ? 'Mark Incomplete' : 'Mark Complete'} </button> </div> ) : ( <div> {task.title} - {task.completed ? 'Completed' : 'Incomplete'} <button onclick="{()"> handleEditTask(task)}>Edit</button> <button onclick="{()"> handleDeleteTask(task.id)}>Delete</button> </div> )} </li> ))} </ul> </div> ); }; export default TaskList;
Wasp ?
And here's the Wasp React client for comparison. Take note how we're able to import the operations we defined earlier and call them here easily on the client with less configuration than the Django app. We also get the built-in caching power of the useQuery hook, as well as the ability to pass in our authenticated user as a prop (we'll get into this more below).
Main.jsx:
import React, { FormEventHandler, FormEvent } from "react"; import { type Task } from "wasp/entities"; import { type AuthUser, getUsername } from "wasp/auth"; import { logout } from "wasp/client/auth"; import { createTask, updateTask, deleteTasks, useQuery, getTasks } from "wasp/client/operations"; import waspLogo from "./waspLogo.png"; import "./Main.css"; export const MainPage = ({ user }) => { const { data: tasks, isLoading, error } = useQuery(getTasks); if (isLoading) return "Loading..."; if (error) return "Error: " + error; const completed = tasks?.filter((task) => task.isDone).map((task) => task.id); return ( <main> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172501684470367.gif?x-oss-process=image/resize,p_40" class="lazy" alt="wasp logo"> {user && user.identities.username && ( <h1> {user.identities.username.id} {`'s tasks :)`} </h1> )} <newtaskform></newtaskform> {tasks && <taskslist tasks="{tasks}"></taskslist>} <div classname="buttons"> <button classname="logout" onclick="{()"> deleteTasks(completed ?? [])} > Delete completed </button> <button classname="logout" onclick="{logout}"> Logout </button> </div> </main> ); }; function Todo({ id, isDone, description }) { const handleIsDoneChange = async ( event ) => { try { await updateTask({ id, isDone: event.currentTarget.checked, }); } catch (err: any) { window.alert("Error while updating task " + err?.message); } }; return (
No tasks yet.
; return (-
{tasks.map((task, idx) => (
Very nice! In the Wasp app you can see how much easier it is to call the server-side code via Wasp operations. Plus, Wasp gives you the added benefit of refreshing the client-side cache for the Entity that's referenced in the operation definition (in this case Task). And the cherry on top is how easy it is to pass the authenticated user to the component, something we haven't even touched on in the Django app, and which we will talk about more below.
Part 3: Auth with Django? No way, José
So we already started to get a feel in the above code for how simple it is to pass an authenticated user around in Wasp. But how do we actually go about implementing full-stack Authentication in Wasp and Django.
This is one of Wasp’s biggest advantages. It couldn't be easier or more intuitive. On the other hand, the Django implementation is so long and complicated I'm not going to even bother showing you the code and I'll just list out the stps instead;
Wasp ?
main.wasp:
app TodoApp { wasp: { version: "^0.14.0" }, title: "Todo App", auth: { userEntity: User, methods: { usernameAndPassword: {} } } //...
And that's all it takes to implement full-stack Auth with Wasp! But that's just one example, you can also add other auth methods easily, like google: {}, gitHub: {} and discord: {} social auth, after configuring the apps and adding your environment variables.
Wasp allows you to get building without worrying about so many things. I don’t need to worry about password hashing, multiple projects and apps, CORS headers, etc. I just need to add a couple lines of code.
Wasp just makes sense.
Django ?
Let's check out what it takes to add a simple username and password auth implementation to a Django app (remember, this isn't even the code, just a checklist!):
Install Necessary Packages:
- Use pip to install djangorestframework, djoser, and djangorestframework-simplejwt for Django.
- Use npm to install axios and jwt-decode for React.
Update Django Settings:
- Add required apps (rest_framework, djoser, corsheaders, and your Django app) to INSTALLED_APPS.
- Configure middleware to include CorsMiddleware.
- Set up Django REST Framework settings for authentication and permissions.
- Configure SimpleJWT settings for token expiration and authorization header types.
Set Up URL Routing:
- Include the djoser URLs for authentication and JWT endpoints in Django’s urls.py.
Implement Authentication Context in React:
- Create an authentication context in React to manage login state and tokens.
- Provide methods for logging in and out, and store tokens in local storage.
Create Login Component in React:
- Build a login form component in React that allows users to enter their credentials and authenticate using the Django backend.
Protect React Routes and Components:
- Use React Router to protect routes that require authentication.
- Ensure that API requests include the JWT token for authenticated endpoints.
Implement Task Update and Delete Functionality:
- Add methods in the React components to handle updating and deleting tasks.
- Use axios to make PUT and DELETE requests to the Django API.
Add Authentication to Django Views:
- Ensure that Django views and endpoints require authentication.
- Use Django REST Framework permissions to protect API endpoints.
One Final Thing
I just want to highlight one more aspect of Wasp that I really love. In Django, we're completely responsible for dealing with all the boilerplate code when setting up a new app. In other words, we have to set up new apps from scratch every time (even if it's been done before a million times by us and other devs). But with Wasp we can scaffold a new app template in a number of ways to really jump start the development process.
Let's check out these other ways to get a full-stack app started in Wasp.
Way #1: Straight Outta Terminal
A simple wasp new in the terminal shows numerous starting options and app templates. If I really want to make a todo app for example, well there you have it, option 2.
Right out of the box you have a to-do application with authentication, CRUD functionality, and some basic styling. All of this is ready to be amended for your specific use case.
Or what if you want to turn code into money? Well, you can also get a fully functioning SaaS app. Interested in the latest AI offereings? You also have a vector embeddings template, or an AI full-stack app protoyper! 5 options that save you from having to write a ton of boilerplate code.
Way #2: Mage.ai (Free!)
Just throw a name, prompt, and select a few of your desired settings and boom, you get a fully functioning prototype app. From here you can use other other AI tools, like Cursor's AI code editor, to generate new features and help you debug!
? Note that the Mage functionality is also achievable via the terminal ("ai-generated"), but you need to provide your own open-ai api key for it to work.
您能向我们表示您的支持吗?
您对更多这样的内容感兴趣吗?订阅我们的时事通讯并在 GitHub 上给我们一颗星!我们需要您的支持来继续推动我们的项目?
⭐️ GitHub 上的星黄蜂?
结论
所以你已经得到它了。正如我在一开始所说的,来自 Django 的我很惊讶使用 Wasp 构建全栈应用程序是多么容易,这也是我写这篇文章的动力。
希望我能够向您展示为什么脱离 Django 而转而使用 Wasp 在时间、精力和情感上都大有裨益。
以上是Wasp:Web 开发中 Django 的 JavaScript 答案的详细内容。更多信息请关注PHP中文网其他相关文章!

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

Node.js擅长于高效I/O,这在很大程度上要归功于流。 流媒体汇总处理数据,避免内存过载 - 大型文件,网络任务和实时应用程序的理想。将流与打字稿的类型安全结合起来创建POWE

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

JavaScript起源于1995年,由布兰登·艾克创造,实现语言为C语言。1.C语言为JavaScript提供了高性能和系统级编程能力。2.JavaScript的内存管理和性能优化依赖于C语言。3.C语言的跨平台特性帮助JavaScript在不同操作系统上高效运行。

JavaScript在浏览器和Node.js环境中运行,依赖JavaScript引擎解析和执行代码。1)解析阶段生成抽象语法树(AST);2)编译阶段将AST转换为字节码或机器码;3)执行阶段执行编译后的代码。

Python和JavaScript的未来趋势包括:1.Python将巩固在科学计算和AI领域的地位,2.JavaScript将推动Web技术发展,3.跨平台开发将成为热门,4.性能优化将是重点。两者都将继续在各自领域扩展应用场景,并在性能上有更多突破。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。