Python+Django+LeanCloud+腾讯云函数学习记录(第一周学习记录)

第一周学习记录

开始从事微信小程序云开发和后台搭建的实习工作,这半年来会一直定期更新学习记录

1、微信爬虫模块

1、Itchat包

​ 使用itchat包的初衷是为了通过该包的login端口直接通过扫描二维码登录用户信息,但是由于API接口的限制,导致无法通过itchat的登录接口获取用户信息。

相关代码链接:https://www.jianshu.com/p/911a3be7ef6c

运行代码示例片段如下

import itchat
from itchat.content import TEXT
@itchat.msg_register
def simple_reply(msg):
    if msg['Type'] == TEXT:
        return 'I received: %s' % msg['Content']
itchat.auto_login()
itchat.run()

运行结果报错如下

在这里插入图片描述

通过查询论坛的相关信息发现:itchat、wxpy都可以结合机器学习自动化聊天的,但微信从19年7月份已经逐渐关闭微信网页版了,同时将于20年1月1日彻底关闭网页版,我们所有的微信自动化工具,聊天机器人、网页爬虫等都将失效。具体知乎专栏链接:https://zhuanlan.zhihu.com/p/76180564

最后舍弃了能够帮我们实现对用户的好友进行分析统计的强大包库itchat,试图寻找其他方案。

2、echart包

echart包本身是应用于微信小程序的画图包,但想要通过echart包实现对用户好友的定制相关词条统计作图首先需要wxpy或者itchat的微信登录接口,然而wxpy的获取信息接口无法使用。

代码链接:https://blog.csdn.net/yaoyefengchen/article/details/79427475

代码示例片段如下

from wxpy import *

# 初始化机器人,扫码登陆
bot = Bot()

# 获取所有好友
my_friends = bot.friends()
print(type(my_friends))

运行结果如下

在这里插入图片描述

事实证明通过该系列方法登入微信获取用户信息的渠道被限制。

2、制作朋友圈九宫格

该功能将一张图片直接切割成9张原图的对应部分图片,在发送朋友圈时可以自动生成九宫格图片发送。

代码链接:jb51.net/article/173442.htm

具体代码如下

# -*- coding: UTF-8 -*-
from PIL import Image
import sys
import os

__author__ = 'kandy'

# 当前文件所在文件夹
DIR_NAME = os.path.dirname(os.path.abspath(__file__))


# 填充新的image
def fill_image(image):
    width, height = image.size
    print('width:{%d}, height:{%d}' % (width, height))

    _length = width
    if height > width:
        _length = height

    new_image = Image.new(image.mode, (_length, _length), color='white')

    if width > height:
        new_image.paste(image, (0, int((_length - height) / 2)))
    else:
        new_image.paste(image, (int((_length - width) / 2), 0))
    return new_image


# 裁剪image
def cut_image(image):
    width, height = image.size
    _width = int(width / 3)
    print('_width:{%d}' % _width)

    box_list = []

    # (left, top, right, bottom)
    for i in range(0, 3):
        for j in range(0, 3):
            print('i:{%d}, j:{%d}' % (i, j))
            box = (j * _width, i * _width, (j + 1) * _width, (i + 1) * _width)
            box_list.append(box)
            image_list = [image.crop(box) for box in box_list]
    return image_list


# 将image列表的里面的图片保存
def save_images(image_list):
    index = 1
    # 创建result文件夹
    res_dir = os.path.join(DIR_NAME, 'result')
    if not os.path.exists(res_dir):
        os.mkdir(res_dir)

    for image in image_list:
        new_name = os.path.join(res_dir, str(index) + '.png')
        image.save(new_name, 'PNG')
        index += 1
    print('图片保存完毕!')


if __name__ == '__main__':
    file_path = os.path.join(DIR_NAME, '123.jpg')
    image = Image.open(file_path)
    # image.show()
    image = fill_image(image)
    #
    image_list = cut_image(image)
    #
    save_images(image_list)
    print('程序结束!')

程序会自动在代码目录下找到待处理图片并生成result文件夹,将九张图片存在该路径下。

在这里插入图片描述

3、证件照底色更改

代码源:https://blog.csdn.net/weixin_43881394/article/details/105728909?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param%E3%80%81https://blog.csdn.net/weixin_44803791/article/details/103205017?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

Django后端学习

1、计算器小程序的实现

1、添加简单交互界面

<!--index.wxml-->
<view class="container">
  <input type="text" class="input" bindinput='input'/>
  <button bindtap="calculate">cal</button>
  <view>{{ result }}</view>
</view>

为页面添加一个文本输入框和计算按钮,大括号内为页面显示结果(从后台传出)

2、样式添加

/**index.wxss**/
.input {
  border: 1px solid black;
  margin-bottom: 5px;
}

3、js处理

const app = getApp()

Page({
  data: {
    result: "暂无结果",
    formula: ''
  },
  //事件处理函数
  calculate: function () {
    wx.request({
      url: 'https://shatter.xin/calculate',
      data: {
        formula: this.data.formula
      },
      success: res => {
        if (res.statusCode == 200) {
          this.setData({
            result: res.data
          })
        }
      }
    })
  },
  input: function (e) {
    this.setData({
      formula: e.detail.value
    })
  }
})

4、Django配置

django-admin startproject calculator
cd calculator
//修改calculator/settings.py中的ALLOWED_HOSTS = []为ALLOWED_HOSTS = ['*']
python manage.py runserver 0.0.0.0:8000
//访问http://服务器ip:8000

5、创建Django app

python manage.py startapp CalculateApi

在calculator/settings.py的INSTALLED_APPS中添加CalculateApi如下

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CalculateApi'
]

在calculator/urls.py中将url转发给CalculateApi处理。

from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from CalculateApi import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('CalculateApi.urls')),
]

在CalculateApi中新建urls.py文件,处理/calculate接口。

from django.urls import path
from . import views

urlpatterns = [
    path('calculate', views.calculate)
]

在CalculateApi/views.py文件中添加calculate函数用于计算求值并返回。

from django.http import HttpResponse


def calculate(request):
    formula = request.GET['formula']
    try:
        result = eval(formula, {})
    except:
        result = 'Error formula'
    return HttpResponse(result)

再次运行服务器,访问http://服务器ip:8000/calculate?formula=2*3-5即可得到结果1

在这里插入图片描述

6、nginx配置

对于这块的知识暂且为0,经过好几个小时的折腾也没能把nginx配置好,还需要加深对nginx的了解和熟悉,才能进一步开发小程序后台。

nginx资源配置信息

brew install nginx
==> Installing dependencies for nginx: pcre
==> Installing nginx dependency: pcre
==> Downloading https://mirrors.ustc.edu.cn/homebrew-bottles/bottles/pcre-8.44.m
Already downloaded: /Users/shall/Library/Caches/Homebrew/downloads/c08fa7928ebb9ce0604771a462d0f5e09b07cd4ece4065a59cb76fd6c94ffdd3--pcre-8.44.mojave.bottle.tar.gz
==> Pouring pcre-8.44.mojave.bottle.tar.gz
🍺  /usr/local/Cellar/pcre/8.44: 204 files, 5.5MB
==> Installing nginx
==> Downloading https://mirrors.ustc.edu.cn/homebrew-bottles/bottles/nginx-1.17.
Already downloaded: /Users/shall/Library/Caches/Homebrew/downloads/d37049593dec260c3856b4844abc3498b1338d90821908b7663a936f99372555--nginx-1.17.9.mojave.bottle.tar.gz
==> Pouring nginx-1.17.9.mojave.bottle.tar.gz
==> Caveats
Docroot is: /usr/local/var/www

The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
nginx can run without sudo.

nginx will load all files in /usr/local/etc/nginx/servers/.

To have launchd start nginx now and restart at login:
  brew services start nginx
Or, if you don't want/need a background service you can just run:
  nginx
==> Summary
🍺  /usr/local/Cellar/nginx/1.17.9: 25 files, 2MB
==> Caveats
==> nginx
Docroot is: /usr/local/var/www

The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
nginx can run without sudo.

nginx will load all files in /usr/local/etc/nginx/servers/.

To have launchd start nginx now and restart at login:
  brew services start nginx
Or, if you don't want/need a background service you can just run:
  nginx

2、Django实战项目:切图

1、项目搭建

仿照计算器案例,将calculate函数更改为处理图片函数,url请求中formula传入本地图片的文件名,也就是意味着该项目只能处理项目文件内已经存储了的图片,虽然能够成功处理并进行HTTP响应,但仍然无法从用户提交的文件进行处理并上传处理后的文件。

更改后的views.py

def cut_main(request):
    formula = request.GET['formula']
    # 当前文件所在文件夹

    DIR_NAME = os.path.dirname(os.path.abspath(__file__))
    # file_path = os.path.join(DIR_NAME, '123.jpg')
    try:
        file_path = os.path.join(DIR_NAME, formula)
        image = Image.open(file_path)
        # image.show()
        image = fill_image(image)
        #
        image_list = cut_image(image)
        #
        save_images(DIR_NAME, image_list)
        result = 'Handled already'
    except:
        result = 'Error formula'

    return HttpResponse(result)

通过http://0.0.0.0:8000/calculate?formula=123.jpg请求处理存在项目文件中的123.jpg并在应用下生成result目录存入9张剪切后的图片。

在这里插入图片描述

处理完成,网页生成响应语句。

后续工作受阻,开始研究官方Django文档

3、官方Django文档学习

1、mysite搭建

在官方文档中学习第一个项目polls,其中polls/views.py如下

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

其他urls配置省略同上

2、数据库配置

1、数据迁移

默认数据库为sqlite,首先进行数据库迁移

python manage.py migrate

这个 migrate 命令检查 INSTALLED_APPS 设置,为其中的每个应用创建需要的数据表,至于具体会创建什么,这取决于你的 mysite/settings.py 设置文件和每个应用的数据库迁移文件(我们稍后会介绍这个)。

2、创建模型

在这个投票应用中,需要创建两个模型:问题 Question 和选项 ChoiceQuestion 模型包括问题描述和发布时间。Choice 模型有两个字段,选项描述和当前得票数。每个选项属于一个问题。

这些概念可以通过一个 Python 类来描述。按照下面的例子来编辑 polls/models.py 文件:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
//字段名=字段类型实例(参数)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
3、激活模型

上面的一小段用于创建模型的代码给了 Django 很多信息,通过这些信息,Django 可以:

  • 为这个应用创建数据库 schema(生成 CREATE TABLE 语句)。
  • 创建可以与 QuestionChoice 对象进行交互的 Python 数据库 API。

但是首先得把 polls 应用安装到我们的项目里。

在settings文件中添加'polls.apps.PollsConfig'

python manage.py makemigrations polls

通过运行 makemigrations 命令,Django 会检测你对模型文件的修改(在这种情况下,你已经取得了新的),并且把修改的部分储存为一次 迁移

python manage.py sqlmigrate polls 0001

会看到sql语出输出

现在,再次运行 migrate 命令,在数据库里创建新定义的模型的数据表:

python manage.py migrate
4、API使用
python manage.py shell

具体操作见https://docs.djangoproject.com/zh-hans/3.0/intro/tutorial02/

5、Django管理页面
python manage.py createsuperuser

然后输入用户名密码

python manage.py runserver

启动开发服务器,访问并登录

在这里插入图片描述

加入投票应用

polls/admin.py更改

from django.contrib import admin

from .models import Question

admin.site.register(Question)

再次进入可以进行对数据的管理

后续Django学习将在之后进行

6、Django模板

主要是在views.py中利用render进行对templates目录下的html文件进行模板赋值,这样页面的显示并不是一成不变的。

同样模板中可以使用if和for等进行有条件的显示,for可以实现反向迭代。

字典遍历等的演示:

{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}

微信小程序云开发学习

微信云开发功能很好地解决了服务器的问题,选择进行云开发了解寻找能够解决问题的途径首先在miniprogram文件下打开终端进行初始化,在这里使用node.js中的vant-weapp作为模板文件

npm init

然后下载vant-weapp

npm i vant-weapp -S --production

云开发官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/userinfo.html

vant-weapp官方文档:https://vant-contrib.gitee.io/vant-weapp/#/button

建立云函数文件后,在终端打开输入npm install --production即可成功上传

1、核心功能

1、图片上传

根据微信开发文档中有相关API编写代码

首先需要导入数据库

const db = wx.cloud.database()
const photos = db.collection('photos')

云端建立photos数据库

wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success :res=> {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        // let randString = Math.floor(Math.random()*100000).toString()+'.png'
        //选择成功后执行上传
        wx.cloud.uploadFile({
          //随机生成图片名
          cloudPath: new Date().getTime()+ '.png', // 上传至云端的路径
          filePath: tempFilePaths[0], // 小程序临时文件路径
          success: res => {
            //photos数据库进行图片添加
            photos.add({
              data:{
                image:res.fileID
              }
            }).then(res=>{
              //添加成功执行
              wx.showToast({
                title: '上传成功',
                icon:'success'
              })
            })
            // 返回文件 ID
            console.log(res.fileID)
          },
          fail: console.error
        })

      },
      fail:err=>{
        console.error(err)
      }
    })

2、图片下载

同样导入database

const db = wx.cloud.database()
const photos = db.collection('photos')

然后绑定按钮点击事件,执行下载命令,调用API

downloadPhoto:function(event){
    wx.cloud.downloadFile({
      //先找到图片的ID
      fileID: this.data.photo, // 文件 ID
      success: res => {
        // 返回临时文件路径
        console.log(res.tempFilePath)
        //保存图片到本地相册
        wx.saveImageToPhotosAlbum({
          filePath:res.tempFilePath,
          
          // success:res=>{
          
          //     wx.showToast({
          //     title: '下载已完成',
          //     icon:'success'
          //   })
          //   console.log("保存成功")
            
          // }
        }).then(res=>{
          wx.showToast({
            title: '下载已完成',
            icon:'success'
          })
        })
      },
      fail: res=>{
        console.error(err)
      }
    })
    // console.log(this.data.photo)
  }

2、python后端API

1、云函数初始化

helloworld部署:https://cloud.tencent.com/document/product/583/37509

仿照helloworld部署本地函数

//1、创建目录
mkdir pillowtest && cd pillowtest
//2、创建index
vim index.py
//3、导入代码
import PIL
//4、获得需要的依赖包
pipreqs ./
//5、生成requirement.txt
cat requirements.txt
//6、安装requirements
sudo pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt -t `项目绝对路径`
//7、本地测试
python index.py
//8、压缩文档
zip -r index.zip .

然后再云函数中测试的时候按照要求写main_handler

我将本地实现代码打包上传至云函数平台,在本地成功执行但是在云平台上只要遇到from package import class就会出现错误,目前不知道具体的原因是什么,简单的云函数部署特备好用,但是单纯地函数没有接口是无法实现具体功能的。

在这里插入图片描述

报错如下

在这里插入图片描述

根据之前的部署经验,不能从一个包导入一个具体类

2、LeanCloud云引擎本地部署

lean创建项目

lean init

本地运行,进入项目目录

pip install -Ur requirements.txt
lean up

访问站点

打开浏览器访问 http://localhost:3000 会显示如下内容:

LeanEngine

这是 LeanEngine 的示例应用

一个简单的动态路由示例

一个简单的「TODO 列表」示例	

接着就是云函数开发指南:https://leancloud.cn/docs/leanengine_cloudfunction_guide-python.html

网站托管开发指南:https://leancloud.cn/docs/leanengine_webhosting_guide-python.html

按照以上文档逐步配置发现了许多问题,有点蒙圈…

3、微信与leancloud的接口

微信小程序白名单
前往 LeanCloud 控制台 > 设置 > 应用 Keys > 域名白名单,获取域名白名单(不同应用对应不同的域名)。
+
登录微信公众平台,前往 设置 > 开发设置 > 服务器配置 > 「修改」 链接,增加上述域名白名单中的域名。

但是在mac版的微信上并没有发现相关配置,很疑惑。

本周总结

这周的工作收到了许多的阻碍,单纯的python功能在本地实现确实好实现,但是如何发布成应用并与用户通过前端的传入参数而进行实时处理调用,并返回到前段显示,用户可以选择下载,这个过程是很复杂的。

这周虽然意识到项目开发的难度,但也学习到了后端实现的基本不仅要有底层逻辑,同样需要与后台服务器搭建,前段接口,甚至微信小程序云开发的相结合,因为在自己学习云开发的过程中了解到云存储和云数据库的便利性,可以直接获得图片下载的链接,这一点十分方便。

对于两个新的云环境:leancloud和腾讯云函数,这两个都并不是轻轻松松就能将整个后端搭建起来的,特别是leancloud的官方文档目前看得挺吃力的,需要后需继续学习,后续将继续更新学习记录。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值