初始化后端和微信小程序

master
barney 2 years ago
commit 7d27d891f1
  1. 185
      .gitignore
  2. 6
      README.md
  3. BIN
      db.sqlite3
  4. 0
      django_weixinapp/__init__.py
  5. 16
      django_weixinapp/asgi.py
  6. 126
      django_weixinapp/settings.py
  7. 23
      django_weixinapp/urls.py
  8. 16
      django_weixinapp/wsgi.py
  9. 31
      frontend/.eslintrc.js
  10. 19
      frontend/app.js
  11. 17
      frontend/app.json
  12. 0
      frontend/app.wxss
  13. 124
      frontend/pages/index/index.js
  14. 3
      frontend/pages/index/index.json
  15. 25
      frontend/pages/index/index.wxml
  16. 6
      frontend/pages/index/index.wxss
  17. 18
      frontend/pages/logs/logs.js
  18. 4
      frontend/pages/logs/logs.json
  19. 6
      frontend/pages/logs/logs.wxml
  20. 8
      frontend/pages/logs/logs.wxss
  21. 51
      frontend/project.config.json
  22. 8
      frontend/project.private.config.json
  23. 7
      frontend/sitemap.json
  24. 19
      frontend/utils/util.js
  25. 22
      manage.py
  26. 0
      weixin/__init__.py
  27. 3
      weixin/admin.py
  28. 6
      weixin/apps.py
  29. 0
      weixin/migrations/__init__.py
  30. 3
      weixin/models.py
  31. 3
      weixin/tests.py
  32. 7
      weixin/urls.py
  33. 10
      weixin/views.py

185
.gitignore vendored

@ -0,0 +1,185 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
### VirtualEnv template
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# idea folder, uncomment if you don't need it
.idea

@ -0,0 +1,6 @@
### 基于Django4.0+微信小程序开发的待办清单
##### 参考链接:[Django+微信小程序开发待办清单](https://www.dusaiphoto.com/article/167/)

Binary file not shown.

@ -0,0 +1,16 @@
"""
ASGI config for django_weixinapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_weixinapp.settings')
application = get_asgi_application()

@ -0,0 +1,126 @@
"""
Django settings for django_weixinapp project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-gpkscwp1ofoqtk$m34few$y+yvukj61l42*_av@4+rkhd9eeg6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'weixin',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_weixinapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_weixinapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,23 @@
"""django_weixinapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api/weixin/', include('weixin.urls', namespace='weixin')),
]

@ -0,0 +1,16 @@
"""
WSGI config for django_weixinapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_weixinapp.settings')
application = get_wsgi_application()

@ -0,0 +1,31 @@
/*
* Eslint config file
* Documentation: https://eslint.org/docs/user-guide/configuring/
* Install the Eslint extension before using this feature.
*/
module.exports = {
env: {
es6: true,
browser: true,
node: true,
},
ecmaFeatures: {
modules: true,
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
globals: {
wx: true,
App: true,
Page: true,
getCurrentPages: true,
getApp: true,
Component: true,
requirePlugin: true,
requireMiniProgram: true,
},
// extends: 'eslint:recommended',
rules: {},
}

@ -0,0 +1,19 @@
// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
globalData: {
userInfo: null
}
})

@ -0,0 +1,17 @@
{
"pages":[
"pages/index/index",
"pages/logs/logs"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#6495ED",
"navigationBarTitleText": "Todo-List",
"navigationBarTextStyle":"black"
},
"style": "v2",
"sitemapLocation": "sitemap.json",
"useExtendedLib": {
"weui": true
}
}

@ -0,0 +1,124 @@
Component({
data: {
// 数据
items: [{
id: 3,
content: '打游戏',
checked: false
}, {
id: 2,
content: '吃饭',
checked: false,
}, {
id: 1,
content: '睡觉',
checked: false,
}],
// 输入框当前内容
inputedValue: "",
},
methods: {
// 监听多选框的状态改变事件
checkboxChange(e) {
// 页面特有的数据
// 获取本地数据的写法为this.data.xxx
const items = JSON.parse(JSON.stringify(this.data.items));
// checkbox的value
const values = e.detail.value;
// 将items和values进行对比
// 根据values的值更新页面数据(即data.items)
for (let i = 0, lenI = items.length; i < lenI; i++) {
items[i].checked = false;
for (let j = 0, lenJ = values.length; j < lenJ; j++) {
if (items[i].id === parseInt(values[j])) {
// 如果当前条目被选中则将items中对应的条目设置为已选中
items[i].checked = true;
break;
}
}
}
// 更新页面数据
this.setData({
items: items,
});
// 将items存储到缓存
wx.setStorage({
key: "items",
data: items,
})
// 打印的内容会展现在调试器中
// console.log(this.data.items)
},
// 监听键盘输入事件
keyInput(e) {
this.setData({
inputedValue: e.detail.value
})
},
// 监听提交按钮
inputSubmit() {
// 读取数据
let items = JSON.parse(JSON.stringify(this.data.items));
// 设置新条目的id
let newId = 1;
if (this.data.inputedValue === "") {
console.log("待办事项不能为空!");
return;
}
for (let value of items) {
if (value.content === this.data.inputedValue) {
console.log("该待办事件已存在!");
return;
}
}
if (items[0] !== undefined) {
newId = items[0].id + 1; // 注意第一个item的id最大
}
// 将新条目更新到items中
items.unshift({ // unshift表示将数据插到第一个位置
id: newId,
content: this.data.inputedValue,
checked: false
});
console.log(items[0]);
// 更新data
this.setData({
items: items,
inputedValue: "", //将输入框中的值清空
});
// 将items本地存储
wx.setStorage({
key: "items",
data: items
});
}
},
//生命周期函数
lifetimes: {
// 在组件实例进入页面节点树时执行
attached() {
// const that = this;
// 从缓存中读取items
wx.getStorage({
key: 'items',
success: res => {
this.setData({
items: res.data.filter(v=>v.checked===false)
})
}
});
// 请求后端数据
wx.request({
url: 'http://127.0.0.1:8000/api/weixin/login/',
success: res => {
console.log(res.data);
}
})
}
}
})

@ -0,0 +1,3 @@
{
"usingComponents": {}
}

@ -0,0 +1,25 @@
<view class="container">
<view>
<view class="weui-cell weui-check_input">
<input value="{{inputedValue}}" bind:input="keyInput" class="weui-input" maxlength="50" placeholder="请输入待办事项" />
</view>
<view class="line"></view>
<button bind:tap="inputSubmit" class="weui-btn" type="default" style="color: gray;">提交</button>
</view>
<view class="weui-cells weui-cells_after-title">
<checkbox-group bind:change="checkboxChange">
<label class="weui-cell weui-check__label" wx:for="{{items}}" wx:key="id">
<view class="weui-cell__hd">
<checkbox value="{{item.id}}" checked="{{item.checked}}" />
</view>
<view class="weui-cell__hd">
{{item.content}}
</view>
</label>
</checkbox-group>
</view>
</view>

@ -0,0 +1,6 @@
.line {
width: 100%;
height: 3rpx;
background: #ddd;
margin-bottom: 20rpx;
}

@ -0,0 +1,18 @@
// logs.js
const util = require('../../utils/util.js')
Page({
data: {
logs: []
},
onLoad() {
this.setData({
logs: (wx.getStorageSync('logs') || []).map(log => {
return {
date: util.formatTime(new Date(log)),
timeStamp: log
}
})
})
}
})

@ -0,0 +1,4 @@
{
"navigationBarTitleText": "查看启动日志",
"usingComponents": {}
}

@ -0,0 +1,6 @@
<!--logs.wxml-->
<view class="container log-list">
<block wx:for="{{logs}}" wx:key="timeStamp" wx:for-item="log">
<text class="log-item">{{index + 1}}. {{log.date}}</text>
</block>
</view>

@ -0,0 +1,8 @@
.log-list {
display: flex;
flex-direction: column;
padding: 40rpx;
}
.log-item {
margin: 10rpx;
}

@ -0,0 +1,51 @@
{
"description": "项目配置文件",
"packOptions": {
"ignore": [],
"include": []
},
"setting": {
"bundle": false,
"userConfirmedBundleSwitch": false,
"urlCheck": true,
"scopeDataCheck": false,
"coverView": true,
"es6": true,
"postcss": true,
"compileHotReLoad": false,
"lazyloadPlaceholderEnable": false,
"preloadBackgroundData": false,
"minified": true,
"autoAudits": false,
"newFeature": false,
"uglifyFileName": false,
"uploadWithSourceMap": true,
"useIsolateContext": true,
"nodeModules": false,
"enhance": true,
"useMultiFrameRuntime": true,
"useApiHook": true,
"useApiHostProcess": true,
"showShadowRootInWxmlPanel": true,
"packNpmManually": false,
"enableEngineNative": false,
"packNpmRelationList": [],
"minifyWXSS": true,
"showES6CompileOption": false,
"minifyWXML": true,
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
}
},
"compileType": "miniprogram",
"libVersion": "2.19.4",
"appid": "wxe35222de7aa53383",
"projectname": "miniprogram-92",
"condition": {},
"editorSetting": {
"tabIndent": "insertSpaces",
"tabSize": 2
}
}

@ -0,0 +1,8 @@
{
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"projectname": "frontend",
"setting": {
"compileHotReLoad": true,
"urlCheck": false
}
}

@ -0,0 +1,7 @@
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}

@ -0,0 +1,19 @@
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
module.exports = {
formatTime
}

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_weixinapp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,6 @@
from django.apps import AppConfig
class WeixinConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'weixin'

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,7 @@
from django.urls import path
from weixin.views import WeixinLogin
app_name = 'weixin'
urlpatterns = [
path('login/', WeixinLogin.as_view(), name='login')
]

@ -0,0 +1,10 @@
from rest_framework.views import APIView
from rest_framework.response import Response
class WeixinLogin(APIView):
def get(self, request, format=None):
"""
提供get请求
"""
return Response({"data": "Hello World!"})
Loading…
Cancel
Save