python conda实践 sanic框架gitee webhook实践

news/2024/5/17 15:54:19 标签: python, conda, gitee
import subprocess
import hmac
import hashlib
import base64
from sanic.response import text
from sanic import Blueprint
from git import Repo

# 路由蓝图
hook_blue = Blueprint('hook_blue')


@hook_blue.route('/hook/kaifa', methods=["POST"])
async def kaifa(request):
    timestamp = request.headers.get('X-Gitee-Timestamp')
    # 秘钥
    secret = '**********'
    secret_enc = bytes(secret.encode('utf-8'))
    # 把 timestamp+"\n"+密钥 当做签名字符串 string_to_sign
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign.encode('utf-8'))
    # 使用HmacSHA256算法计算签名,得到 hmac_code
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,digestmod=hashlib.sha256).digest()
    # 将hmac_code进行Base64 encode
    my_sign = base64.b64encode(hmac_code).decode('utf-8')

    gitee_sign = request.json.get('sign')
    if my_sign == gitee_sign:
        gitrepo = Repo("/www/wwwroot/********/")
        remote = gitrepo.remote()
        info = remote.pull()
        return text(str(info))
    else:
        return text('签名错误')


@hook_blue.route('/hook/ceshi', methods=["POST"])
async def ceshi(request):
    timestamp = request.headers.get('X-Gitee-Timestamp')
    # 秘钥
    secret = '*******'
    secret_enc = bytes(secret.encode('utf-8'))
    # 把 timestamp+"\n"+密钥 当做签名字符串 string_to_sign
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign.encode('utf-8'))
    # 使用HmacSHA256算法计算签名,得到 hmac_code
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,digestmod=hashlib.sha256).digest()
    # 将hmac_code进行Base64 encode
    my_sign = base64.b64encode(hmac_code).decode('utf-8')

    gitee_sign = request.json.get('sign')
    if my_sign == gitee_sign:
        # 执行的命令
        cmd = r'git pull'
        # cwd指的是某个进程运行时所在的目录;cwd是“current working directory”的缩写
        cwd_path = r'/www/wwwroot/********/'
        process = subprocess.Popen(cmd, shell=True, cwd=cwd_path, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE)
        process.wait()
        result = process.returncode
        if result == 0:
            return text("git 的拉取:成功")
        else:
            return text("git 的拉取:失败")
    else:
        return text('签名错误')

/******************************************************************/

conda后台运行python脚本shell脚本run.sh:

想以www用户运行脚本,记的切换到www用户,再启动脚本,

./run.sh start

#!/bin/bash

#应用入口文件
APP_NAME=/www/wwwroot/python-webhook/main.py
#进程关键字
PROCESS_KEYWORD=python-webhook

#使用说明,用来提示输入参数
usage(){
    echo "Usage: sh run.sh [start|stop|restart|status]"
}

#检查程序是否在运行
is_exist(){
    pid=`ps -ef|grep $PROCESS_KEYWORD|grep -v grep|awk '{print $2}'`
    if [ -z "${pid}" ];then
        return 1
    else
        return 0
    fi
}

#启动方法
start(){
    is_exist
    if [ $? -eq 0 ];then
        echo "${APP_NAME} is already running. pid=${pid}"
    else
        conda run --name python-webhook nohup python ${APP_NAME} >nohup.out 2>&1 &
    fi    
}

#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    ps -ef|grep $PROCESS_KEYWORD|grep -v grep|awk '{print $2}'|xargs kill -9
  else
    echo "${APP_NAME} is not running"
  fi  
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启方法
restart(){
  stop
  sleep 5
  start
}
 
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac

/*****************************************************************/

需要以哪个用户来运行python代码,就切换到哪个用户下进行安装:

1. 使用grep www /etc/passwd查看用户权限
$ grep www /etc/passwd
www:x:1001:1001::/home/www:/sbin/nologin
可以看出,www是/sbin/nologin禁止登录的。只要修改这个模式就可以了

2. 修改模式
$ usermod -s /bin/bash www
3. 再次查看状态
$ grep www /etc/passwd
www:x:997:995:www user:/var/cache/www:/bin/bash
4. 然后就可以用su - www切换了
$ su - www
1
5. 恢复的话改为/sbin/nologin即可
$ usermod -s /sbin/nologin www

开始安装:

miniconda和anaconda下载地址

https://docs.conda.io/en/latest/miniconda.html

Free Download | Anaconda

Centos7.9安装miniconda
Miniconda是一个 免费的 轻量级的 conda安装程序
conda是一个开源的包、环境管理器,能在同一个机器上安装不同Python版本的软件包及其依赖,以及在不同Python环境之间切换
Miniconda只包含conda、Python、pip、zlib等基础的文件和依赖包
Anaconda不仅包含conda、Python等基础文件,还包含很多装好的包,如:numpy、pandas
使用conda install命令可从Anaconda存储库中安装额外的conda
下载Miniconda3-latest-Linux-x86_64.sh

wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh
运行.sh

sudo sh Miniconda3-latest-Linux-x86_64.sh
输入安装的路径,如/usr/anconda3

添加/usr/anconda3到系统环境变量文件/etc/profile文件

sudo vi  /etc/profile
添加

export PATH=/usr/anconda3/bin:$PATH
激活生效,或重启

source /etc/profile
检测安装是否成功

conda -V
2、配置conda镜像源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/

# optional
conda config --add channels http://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/

conda config --set show_channel_urls yes

/****************************************/

要卸载 Miniconda,请按照以下步骤进行操作:

打开终端或命令提示符窗口,确保以管理员权限运行。

根据你的操作系统,执行以下命令卸载 Miniconda

在 Windows 上:

conda install anaconda-clean
anaconda-clean --yes

在 macOS 或 Linux 上:

conda install anaconda-clean
anaconda-clean --yes
在某些 Linux 发行版中,可能需要在命令前加上 sudo。

确认卸载操作。执行上述命令后,你将被要求确认卸载。请仔细阅读提示信息,然后输入 y 或 yes 确认卸载。

删除 Miniconda 安装目录:在终端中执行以下命令,将 <miniconda_install_dir> 替换为你的 Miniconda 安装目录:

rm -rf <miniconda_install_dir>
注意:请谨慎执行此命令,确保你删除的是正确的安装目录。

检查环境变量:卸载 Miniconda 后,你可能还需要手动删除与 Miniconda 相关的环境变量。在 Windows 上,可以通过 “控制面板” -> “系统和安全” -> “系统” -> “高级系统设置” -> “环境变量” 打开环境变量设置界面,然后检查并删除相关的环境变量。在 macOS 或 Linux 上,可以编辑 ~/.bashrc 或 ~/.bash_profile 文件,并删除相关的路径配置。

完成上述步骤后,你的系统应该已成功卸载 Miniconda。请确保在卸载之前备份你的数据,以防万一。

/**************************************************/

创建虚拟环境:

conda create -n python-webhook python=3.11

后台运行python脚本:

conda run --name python311-venv nohup python main.py >nohup.out 2>&1 &

/*************************************************************/

conda可以配合其他python包管理工具一起使用,比如pipenv或者poetry,

conda安装好某个python版本的虚拟环境后,就在这个虚拟环境运行其他包管理工具即可,

比如poetry包管理的项目,虚拟环境安装好poetry工具后,运行poetry install即可安装好项目需要的依赖包,然后启动项目即可


http://www.niftyadmin.cn/n/4979763.html

相关文章

OpenCV 开启O3优化

opencv默认没有开启O3优化选项&#xff0c;需要进行手动设置&#xff0c;下面是一种优化方法&#xff1a; 方法一 在 /opencv-4.5.5/cmake/OpenCVCompilerOptions.cmake 中的第 269 行做出以下修改&#xff1a; # 修改前 set(OPENCV_EXTRA_FLAGS_RELEASE "${OPENCV_EXT…

Java实现根据商品ID获取1688商品详情跨境属性数据,1688商品重量数据接口,1688API接口封装方法

要通过1688的API获取商品详情跨境属性数据&#xff0c;您可以使用1688开放平台提供的接口来实现。以下是一种使用Java编程语言实现的示例&#xff0c;展示如何通过1688开放平台API获取商品详情属性数据接口&#xff1a; 首先&#xff0c;确保您已注册成为1688开放平台的开发者…

“华为杯”研究生数学建模竞赛2018年-【华为杯】A题:跳台跳水体型校正系数的建模分析

目录 摘要: 1 问题重述与分析 2 模型建立与求解 2.1 问题一的建模与求解

py 项目上线 日志输出 logging

1 指定文件 example.log import logging logging.basicConfig(levellogging.INFO, format%(asctime)s %(levelname)s %(message)s, datefmt%Y-%m-%d %H:%M:%S,handlers[logging.FileHandler("example.log"),logging.StreamHandler()]) 2 把print(sql)换成 logging…

Prompt2Model: Generating Deployable Models from Natural Language Instructions

本文是LLM系列文章&#xff0c;针对《 Prompt2Model: Generating Deployable Models from Natural Language Instructions》的翻译。 Prompt2Model&#xff1a;从自然语言指令生成可部署模型 摘要1 引言2 Prompt2Model框架3 参考实现4 实验设置5 实验结果6 讨论与结论不足道德…

【高精度减法】

高精度减法 #include<iostream> #include<vector> using namespace std;vector<int> sub(vector<int>& A,vector<int>& B){vector<int> C;int t 0;for(int i0;i<A.size();i){t A[i] - t;if(i<B.size()) t-B[i];C.push_b…

nginx通过实现rtmp服务及使用flv.js播放

目录 参考配置文件推流测试推流通过拉流rtsp然后推流到rtmp flv.js播放 参考 基于Nginx服务FFmpeg-RTMP/HTTP/FLV推拉流使用方法 使用flv.js实现视频直播 配置文件 worker_processes 10; events {worker_connections 10240; } rtmp_auto_push on; rtmp_auto_push_reconnec…

微信小程序活动报名管理系统设计与实现

摘 要 随着当下的移动互联网技术的不断发展壮大&#xff0c;现在人们对于手机的应用已经非常的成熟&#xff0c;当下的时代基本上达到了人手一部手机&#xff0c;数字化、信息化已经成为了人们的主流生活。有数据统计&#xff0c;截止到2020年末我国的手机网民人数已经接近10亿…