Develop WeChat applet step by step (Django+Mysql)

Prerequisite: Assume that you have installed Anaconda, WeChat developer tools, MySQL database, IDE and other tools

Tool download address:

Anaconda:https://www.anaconda.com/download

MySQL:https://dev.mysql.com/downloads/mysql/

WeChat developer tools: https://developers.weixin.qq.com/miniprogram/dev/devtools/stable.html

CodeIDE:VSCode:https://code.visualstudio.com/Download

​ Pycharm: https://www.jetbrains.com/pycharm/download/?section=windows (you may need to install the learning version)

Postman:https://www.postman.com/downloads/

Configure related environments:

# 创建环境
conda create --name SEClass(替换成自己想设置的名称) python=3.9

# 激活环境
conda activate SEClass

# 安装库
pip install Django
pip install djangorestframework(API接口开发库)
pip install mysqlclient

MySQL:

Assume that the mysql client has been installed at this time

# 登录mysql
mysql -u root -p

# 创建项目所使用的数据库(注意名字要符合要求,如不能使用-)
CREATE DATABASE your_database_name;

# 进入刚刚创建的数据库
USE your_database_name;

# 查看当前所在数据库:
SELECT DATABASE();

Connect to the database: (use a database management tool to connect, such as Navicat Premium)

(Navicat Premium official download address: https://www.navicat.com/en/download/navicat-premium)

Connection settings:

Localhost: localhost (or remote database host address)

Port: 3306 (default port number)

Username: root (or other created username)

Password: (enter the password you set when installing mysql)

Django:

Django official website: https://www.djangoproject.com

Official tutorial: https://docs.djangoproject.com/zh-hans/4.2/intro/ (if the wall is cracked, it is recommended to follow it again)

Create project:

$ django-admin startproject mysite(项目名称,自行设置)

Project structure (basic files will be automatically generated when creating a project):

  • The outermost mysite/root directory is just the container for your project. The name of the root directory has no effect on Django. You can rename it to anything you like.

  • manage.py: A command line tool that lets you manage Django projects in various ways. You can read django-admin and manage.py for all manage.pythe details.

  • The directory inside mysite/contains your project, which is a pure Python package. Its name is the Python package name you use when referencing anything inside it. (for example mysite.urls).

  • mysite/__init__.py: An empty file telling Python that this directory should be considered a Python package. If you are new to Python, read more about packages in the official documentation .

  • mysite/settings.py: The configuration file of the Django project. If you want to know how this file works, check out Django configuration for details.

  • mysite/urls.py: The URL declaration of the Django project, like the "directory" of your website. Read the URL dispatcher documentation to learn more about URLs.

  • mysite/asgi.py: Serves as the entry point for your project to run on an ASGI-compatible web server. Read How to deploy using ASGI for more details.

  • mysite/wsgi.py: Serves as the entry point for your project to run on a WSGI-compatible web server. Read How to deploy with WSGI for more details.

(Use IDE to configure the environment of Django project)

Project configuration: (configure in settings.py in the root directory)

Database configuration:
DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'class-0912(你创建的mysql数据库名称)',
        'USER': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
        'PASSWORD': '',
        'OPTIONS': {
    
    'charset': 'utf8mb4'},
    }
}
API interface library configuration:
INSTALLED_APPS = [
    ...
    'rest_framework',
    "rest_framework.authtoken",
]
# 此项需要单独添加在settings.py文件末尾额外增加
REST_FRAMEWORK = {
    
    
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
  	'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
url path configuration:
from django.urls import include

urlpatterns = [
  	# 配置后台管理页面
    path('admin/', admin.site.urls),
    # 包含应用的URL配置(此时你可能还没有创建your_app)
    path('your_app_name/', include('your_app_name.urls')),
]

Startup project:

# 默认端口
$ python manage.py runserver (默认端口为8000)

# 更换其它端口
$ python manage.py runserver 8080

Create App modules (each module implements a certain task, and the module design is based on actual needs):

$ python manage.py startapp your_app_name

Design model: (After you create the App, a new App folder will appear in the project folder, and model.py is the place to design the model)

from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)
    
    def __str__(self):
        return self.full_name
      
class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

Activate the model:

#根项目setting.py中修改
INSTALLED_APPS = [
  	...,
    'your_app_name.apps.TestappConfig',
]

Application data model: (After designing the model, database migration is required. At this time, Django will automatically create a database based on the design in the model you activated)

# 每次进行数据库迁移请按顺序执行下列代码
$ python manage.py makemigrations
$ python manage.py migrate

Create an administrator account: (enter and follow the prompts to create)

python manage.py createsuperuser

Register the model on the admin site:

your_app_name/admin.py:

from django.contrib import admin

# Register your models here.
from .models import Reporter, Article


admin.site.register(Reporter)
admin.site.register(Article)

Write the view:

There are only two possible execution results of the view function: returning a [ ] object containing the requested page elements HttpResponse, or throwing Http404an exception such as [ ]. As for the other actions in the execution process, it is up to you.

from django.shortcuts import render
from .models import Article


def year_archive(request, year):
    a_list = Article.objects.filter(pub_date__year=year)
    context = {
    
    "year": year, "article_list": a_list}
    return render(request, "news/year_archive.html", context)

Planning URLs:

your_app_name/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path("articles/<int:year>/", views.year_archive),
]

Design template (optional, not very useful for WeChat applet development):

The above code loads your_app_name/year_archive.html` template, which can be customized

your_app_name/year_archive.html:

{
    
    % extends "base.html" %}

{
    
    % block title %}Articles for {
    
    {
    
     year }}{
    
    % endblock %}

{
    
    % block content %}
<h1>Articles for {
    
    {
    
     year }}</h1>

{
    
    % for article in article_list %}
    <p>{
    
    {
    
     article.headline }}</p>
    <p>By {
    
    {
    
     article.reporter.full_name }}</p>
    <p>Published {
    
    {
    
     article.pub_date|date:"F j, Y" }}</p>
{
    
    % endfor %}
{
    
    % endblock %}

Write API interface:

The development of the API interface involves the three most basic files: serializers.py (you need to create this file yourself), views.py and urls.py

serializers.py: This file creates the model fields you want to serialize
views.py: This file creates the view logic of the API interface you want to develop. You can design it according to your business needs, such as receiving GET/POST/PATCH and other requests, parsing the request request data, and designing the business logic based on the request data. The response field to be returned is serialized according to the serialization function defined in serializers.py, and the status code of the API interface is returned.
urls.py: Register the url path for the API interface you developed.
your_app_name/serializers.py:

from rest_framework import serializers
from your_app_name.models import yourModel

# 此Serializer返回yourModel模型的指定或全部序列化字段
class myModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = yourModel
        fields = '__all__'  # 返回全部或者指定您想要序列化的字段
        # fields = ['phone_number', 'avatar', 'resume']
        
# 此Serializer返回需要自定义处理的字段,无需被模型字段限制
class customFieldSerializer(serializers.Serializer):
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)
your_app_name/views.py:
 
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from .serializers import mySerializer
from .models import Reporter, Article

# 通用View
class myGeneralListView(generics.ListAPIView):
    queryset = Reporter.objects.all()
    serializer_class = mySerializer

# 自定义View
class articleCustomListView(APIView):
  	# 未做异常处理,请自行完成
    def get(self, request):
        articles = Article.objects.all()
        articles_serializer = ArticleSerializer(articles, many=True)
        
        return Response({
    
    
            'articles': articles_serializer.data
        }, status=status.HTTP_200_OK)
your_app_name/urls.py:
  
from django.urls import path
from .views import CustomListView

urlpatterns = [
    # path('userlogin/', UserLoginView.as_view(), name='user-login'),
    # ...其他URL配置...
    path('article-info/', articleCustomListView.as_view(), name='customlist'),
]

WeChat mini program:

Official website documentation: https://developers.weixin.qq.com/miniprogram/dev/framework/

Official tutorial: https://developers.weixin.qq.com/ebook?action=get_post_info&docid=0008aeea9a8978ab0086a685851c0a (If you don’t understand the wall crack, it is recommended to follow it)

Recommended component library: Vant Weapp (other component libraries can also be used, search WeChat Mini Program Component Library for details)

Official address: https://youzan.github.io/vant-weapp/#/home (you can open the website and scan the code to view the preview applet)

#注意:组件库推荐使用npm命令进行构建,使用npm命令需要在环境安装node

# 安装 node
Macos端:
# 使用brew命令安装 或 去官网地址下载软件包(同windows端)进行安装
# brew命令的使用需要提前安装,见网址:https://brew.sh
# 终端输入:/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

终端输入:brew install node

Windows端:
# 官网地址下载软件包进行安装:https://nodejs.org/en/download

# 检查npm是否安装
npm -v

# 通过 npm 安装 
npm i @vant/weapp -S --production

# 修改 app.json
将创建的微信小程序中的 app.json 中的 "style": "v2" 去除,因为小程序的新版基础组件强行加上了许多样式,难以覆盖,不关闭将造成部分组件样式混乱

#构建npm项目
npm install

# 构建 npm 包
打开微信开发者工具,点击 工具 -> 构建 npm,并勾选 使用 npm 模块 选项,构建完成后,即可引入组件

# 引入组件
以 Button 组件为例,只需要在app.json或index.json中配置 Button 对应的路径即可

// app.json
"usingComponents": {
  "van-button": "@vant/weapp/button/index"
}

# 使用组件
引入组件后,可以在 wxml 中直接使用组件
<van-button type="primary">按钮</van-button>

おすすめ

転載: blog.csdn.net/perfectzxiny/article/details/134300793