init repo

This commit is contained in:
2021-12-12 17:46:25 +00:00
commit a8cf23cefa
70 changed files with 3535 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
---
title: "「项目实战」校园微信小程序 03.后端技术"
categories: [ "后端技术","商业项目" ]
tags: [ ]
draft: false
slug: "yiyu-backend"
date: "2021-05-26 15:55:00"
---
### 数据库
后端最离不开的就是和数据库打交道,果断选用开源的 MySQL 社区版作为本次项目的数据库服务。
MySQL版本为 `10.3.23-MariaDB`,地域为腾讯云香港云数据库
### 建表
刚开始建表使用的都是默认参数,其中用户表中包含用户的微信昵称,好在我们有好几个测试用的微信号,发现了其中一个的问题所在。
![utf8-unicode][1]
MySQL默认建表的字符排序规则为 utf8-unicode-ci就会导致微信用户名中带有4字节的 emoji 字符无法写入数据库,从而报错。
![utf8mb4-unicode][2]
解决方案就是更改为utf8mb4该排序规则支持单字符四字节宽度的 emoji 字符。
为了统一,所有字符串都采用这个排序规则。
### Web服务框架
因为是小项目,直接使用 `Flask` 一把梭。
PS去年底开始Python 有个叫 `fastapi` 的框架火了起来,综合了 `flask``django` 的优势,而且开发效率高,运行速度快,会写一篇文章来介绍它。
```python
# 注册全局flask
app = Flask(__name__)
app.config.from_object(DevConfig)
# 初始化定时器
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# 注册数据库
db.init_app(app)
# 注册蓝图
app.register_blueprint(course_blue)
app.register_blueprint(user_blue)
app.register_blueprint(index_blue)
app.register_blueprint(admin_blueprint, url_prefix='/admin')
app.register_blueprint(order_blueprint, url_prefix='/api')
app.register_blueprint(file_blueprint, url_prefix='/file')
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s',
filename='./log/miniapp-' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.log')
```
建项目之后直接进行建立蓝图,初始化定时器(课表推送功能),连接数据库,设定日志目录等操作。
### 服务API
```python
@user_blue.before_request
def before_eq():
if request.path == '/auth/wxlogin' or request.path == '/auth/gzhlogin' or request.path == '/auth/qrcode':
pass
elif getUid() is None:
return {
'errmsg': 'token expired'
}, 401
```
在对用户和管理员后台拿到的数据进行操作时,先要拦截请求,判断是否为已经验证的请求,否则返回 HTTP 401表示为非法操作未验证的请求但是必须放行登录等请求否则无法登录。使用flask的请求拦截器做到。
### ORM 框架
在 Python 下面用的最多的ORM应该就是 `SQLAlchemy`无需写SQL即可完成强大的增删改查功能具体使用就不在此阐述网络上有许多案例和教程当然我最推荐的学习方法就是参照官方的文档来因为随着版本的跟进代码可能会略有不同官方文档永远都是最新的。
MySQL使用时不要忘记 MySQL 驱动包 `PyMySQL`
### 微信加密数据解码
微信的隐私敏感数据是用AES加密然后到服务端解密的Python 端则使用 `Crypto` 这个包,不过这个包的历史遗留问题,在不同环境的名字还不一样,简单来说就是 Linux 和 Windows 下面的包都是最原始版本的延伸。
在 Windows下使用AES时要安装的是 pycryptodome 模块
> pip install pycryptodome
在 Linux 或者 macOS 下使用AES时要安装的是 pycrypto 模块
> pip install pycrypto
例如我在 Mac 和 Windows 下面做开发,就要安装不同的包,最终上 Linux 生产环境,也是不一样的。
### 小结
[1]: https://cdn.rhyland.cn/typecho/2021/05/26/utf8-unicode.png
[2]: https://cdn.rhyland.cn/typecho/2021/05/26/utf8mb4-unicode.png
[3]: https://cdn.rhyland.cn/typecho/2021/05/26/flask-init.png
[4]: https://cdn.rhyland.cn/typecho/2021/05/26/request-intercept.png