Wasp:Web 開發中 Django 的 JavaScript 答案

WBOY
發布: 2024-08-30 19:20:02
原創
210 人瀏覽過

Wasp vs Django:建立全端應用程式變得更加容易

嘿,我是 Sam,一位擁有豐富 Django 經驗的後端工程師。我想跳躍並學習一些全端應用程式的前端。我很快就體驗到了 React-with-Django 專案的艱鉅性,並認為痛苦只是開發過程的一部分。然而,我遇到了一個非常酷的新全端框架,名為 Wasp。

Wasp 是一款出色的全端應用程式開發工具。 Wasp 結合了 React、Node.js 和 Prisma 等技術,能夠以前所未有的方式加快開發速度。

在本文中,我將逐步介紹在 Django 和 Wasp 中創建全端應用程序,以證明 Wasp 相對於非常傳統的全端技術的簡單性。我還將製作一個連接到 Django 的 React 前端。重點是強調 Django/react 可能(並將)出現的低效率、困難和問題,這些問題透過

變得更加簡單

本文無意作為指導,但我確實提供了一些程式碼來強調 Django 應用程式的詳盡性質。

Wasp: The JavaScript Answer to Django for Web Development

第 1 部分:要有光!

讓我們創建一些項目並進行設置

這部分是 Django 和 Wasp 之間唯一有明顯重疊的部分。從終端開始,讓我們製作一個簡單的任務應用程式(我假設您已經安裝了 Django 和 Wasp,並且位於您的路徑中)。

薑戈?

雷雷

黃蜂?

雷雷

現在黃蜂一開始就很火爆。請參閱下面為您提供的菜單。 Wasp 可以為您啟動一個基本應用程序,或者您可以從大量預製模板(包括功能齊全的 SaaS 應用程式)中進行選擇,甚至可以根據您的描述使用 AI 生成的應用程式!

Wasp: The JavaScript Answer to Django for Web Development

同時,Django 作為一個專案運行,專案內有應用程式(同樣,基本上都是用於後端操作),並且一個 Django 專案可以有多個應用程式。因此,您必須在 Django 專案設定中註冊每個應用程式。

雷雷

settings.py:

雷雷

資料庫時間

所以現在我們需要一個資料庫,這是 Wasp 真正擅長的另一個領域。使用 Django,我們需要在 models.py 檔案中建立模型。同時,Wasp 使用 Prisma 作為 ORM,它允許我們清楚地定義必要的字段,並以易於理解的方式使資料庫創建變得簡單。

薑戈?

models.py:

雷雷

黃蜂?

schema.prisma:

雷雷

Django 和 Wasp 確實共享相似的資料庫遷移方法:

薑戈?

雷雷

黃蜂?

雷雷

但是使用 Wasp,您也可以做一些 Django 做不到的非常漂亮的資料庫事情。

現在我們正在使用 SQLite,但是立即設定一個開發 Posgres 資料庫怎麼樣?黃蜂可以透過以下方式做到這一點:

雷雷

就是這樣!這樣,您就有了一個執行 Postgres 實例的 docker 容器,並且它會立即連接到您的 Wasp 應用程式。 ?

或者,如果您想透過 Prisma 的資料庫工作室 UI 即時查看資料庫該怎麼辦,如果沒有 Django 的第三方擴展,這是不可能實現的。為此,只需運行:

雷雷

你現在開始明白我的意思了嗎?

路線

Django 和 Wasp 中的路由遵循某種類似的模式。然而,如果你熟悉 React,那麼 Wasp 的系統要優越得多。

  • Django 透過後端(views.py,我將在本文後面介紹)來執行所有 CRUD 操作。這些視圖函數與專案內應用程式內的特定路由相關聯(我知道很多),如果您開始使用主鍵和 ID,它可能會變得更加複雜。您需要建立一個 urls.py 檔案並將特定視圖檔案和函數定向到路由。然後,這些應用程式 URL 將連接到專案 URL。唷。

  • Wasp 的方式:定義路由並將其定向到元件。

薑戈?

todo/urls.py:

雷雷

./urls.py:

雷雷

黃蜂?

main.wasp:

雷雷

增刪改查

好吧,這就是 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?

Wasp: The JavaScript Answer to Django for Web Development

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 ( 

To-Do List

    {tasks.map(task => (
  • {editingTask && editingTask.id === task.id ? (
    ) : (
    {task.title} - {task.completed ? 'Completed' : 'Incomplete'}
    )}
  • ))}
); }; 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 ( 
wasp logo {user && user.identities.username && (

{user.identities.username.id} {`'s tasks :)`}

)} {tasks && }
); }; 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 (
  • {description}
  • ); } function TasksList({ tasks }) { if (tasks.length === 0) return

    No tasks yet.

    ; return (
      {tasks.map((task, idx) => ( ))}
    ); } function NewTaskForm() { const handleSubmit = async (event) => { event.preventDefault(); try { const description = event.currentTarget.description.value; console.log(description); event.currentTarget.reset(); await createTask({ description }); } catch (err: any) { window.alert("Error: " + err?.message); } }; return (
    ); }
    登入後複製

    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é

    Wasp: The JavaScript Answer to Django for Web Development

    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.

    Wasp: The JavaScript Answer to Django for Web Development

    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 toreallyjump 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 simplewasp newin 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.

    Wasp: The JavaScript Answer to Django for Web Development

    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!

    Wasp: The JavaScript Answer to Django for Web Development

    ? 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.

    Can you show us your support?

    Wasp: The JavaScript Answer to Django for Web Development

    Are you interested in more content like this? Sign up for our newsletter and give us a star on GitHub! We need your support to keep pushing our projects forward ?

    ⭐️ Star Wasp on GitHub ?

    Conclusion

    So there you have it. As I said in the beginning, coming from Django I was amazed how easy it was to build full-stack apps with Wasp, which is what inspired me to write this article.

    Hopefully I was able to show you why breaking away from Django in favor of Wasp can be beneficial in time, energy, and emotion.

    以上是Wasp:Web 開發中 Django 的 JavaScript 答案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    來源:dev.to
    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!