Python 云服务器应用,Https,定时重启

Python 云服务器应用,Https,定时重启

  • 环境搭建
  • Python模块
  • 模块导入
  • 生成Flask实例
  • GET处理
  • 启动服务器
  • 打开网页验证 GET
  • 接入证书 支持https
    • 申请证书
    • 下载证书
    • 保留 xxx.crt 和 xxx.key文件就可以了 copy到python项目目录
    • ssl_context 配置
  • 宝塔面板操作
    • 在www目录下新建python工作目录
    • 在python工作目录下新建项目子目录
    • 上传本地的 .py文件到服务器项目目录下![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/ffb04f92b8d0402bb26ac61e465356a0.png)
    • 宝塔操作 添加python项目
    • 项目配置 - 具体参数如下截图 - 配置好后 提交
    • 项目添加模块
    • 开放端口 8002 你用到哪个端口就放开哪个端口
    • 入站配置
      • 打开购买云服务器的平台网站
      • 进入实例
      • 添加入站规则
      • 协议填tcp 端口8002 备注 python服务器 其他的默认 就可以了
  • 测试云端GET
  • 测试云端POST
  • 配置服务器 定时器重启
    • 脚本写好了后执行一遍验证一下
  • 详细视频教程 - bilibili
  • Python源码
    • main.py
    • LockIP.py
  • Demo 仓库

环境搭建

  • python 3.6+
  • vscode
  • centos云服务器一台
  • 宝塔Liunx面板已安装
  • SSL证书 nginx版本

Python模块

  • flask
    搭建https服务器
  • gevent.pywsgi
    支持服务器生产环境

pip install flask
pip install gevent

模块导入

from flask import Flask,request,redirect,jsonify, url_for
from LockIP import IPStatus, check

生成Flask实例

app = Flask(__name__)

GET处理

@app.route('/new')
def newHtml():
	return "lpl 加油!"

启动服务器

def openserver():
    import datetime
    timestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f'{timestr} 服务器启动中.....')
    app.run(host="0.0.0.0", port=8000,debug=True)

if __name__ == '__main__':
    openserver()

打开网页验证 GET

网页输入 http://127.0.0.1:8000/new

出现 lpl 加油! 服务器启动成功
Python 云服务器应用,Https,定时重启_第1张图片

接入证书 支持https

申请证书

以西部数据为案例
Python 云服务器应用,Https,定时重启_第2张图片

下载证书

下载支持nginx的版本
Python 云服务器应用,Https,定时重启_第3张图片

保留 xxx.crt 和 xxx.key文件就可以了 copy到python项目目录

  • .crt
  • .key

ssl_context 配置

这里填你自己申请的证书文件名 对应的crt和key文件

app.run(host="0.0.0.0", port=8002, ssl_context=('www.geek7.top.crt', 'www.geek7.top.key'))

宝塔面板操作

在www目录下新建python工作目录

Python 云服务器应用,Https,定时重启_第4张图片

在python工作目录下新建项目子目录

Python 云服务器应用,Https,定时重启_第5张图片

上传本地的 .py文件到服务器项目目录下Python 云服务器应用,Https,定时重启_第6张图片

宝塔操作 添加python项目

Python 云服务器应用,Https,定时重启_第7张图片

项目配置 - 具体参数如下截图 - 配置好后 提交

Python 云服务器应用,Https,定时重启_第8张图片

项目添加模块

在这里插入图片描述
不需要填版本好 直接填需要依赖的模块名就好了
Python 云服务器应用,Https,定时重启_第9张图片

开放端口 8002 你用到哪个端口就放开哪个端口

协议填tcp 端口8002 备注 python服务器 其他的默认 就可以了
在这里插入图片描述

入站配置

打开购买云服务器的平台网站

Python 云服务器应用,Https,定时重启_第10张图片

进入实例

Python 云服务器应用,Https,定时重启_第11张图片

添加入站规则

Python 云服务器应用,Https,定时重启_第12张图片

协议填tcp 端口8002 备注 python服务器 其他的默认 就可以了

测试云端GET

没有域名的 用ip也可以的 前面要用https
https://www.geek7.top:8002/new
Python 云服务器应用,Https,定时重启_第13张图片

测试云端POST

代码保留在案例了 自己去瞅瞅 给你一个发挥的机会 代码可以跑通 自己研究研究

配置服务器 定时器重启

  • 宝塔面板 - 计划任务 - Shell脚本
    Python 云服务器应用,Https,定时重启_第14张图片

  • 时间自填

  • 脚本内容

ps -ef|grep PYServer|grep -v grep|cut -c 9-15|xargs kill -9
cd /www/python_projs/PYServer/
/www/server/pyporject_evn/444ab1b88bd66070681fb30537aeeb8c_venv/bin/python3 -u /www/python_projs/PYServer/server.py

脚本内容 中的PYServer改成你的项目名
Python 云服务器应用,Https,定时重启_第15张图片

脚本写好了后执行一遍验证一下

怎么验证呢? 方式有很多种 最简单的一种 先关闭python项目 然后执行一次脚本 如果项目跑起来了 就表示shell脚本成功
Python 云服务器应用,Https,定时重启_第16张图片

详细视频教程 - bilibili

Python Https云服务器,定时重启

Python源码

main.py

from flask import Flask,request,redirect,jsonify, url_for
from LockIP import IPStatus, check

app = Flask(__name__)

@app.route('/new')
def newHtml():
    ip = request.remote_addr
    status = check(ip)
    if status == IPStatus.Lock:
        return "你已在黑名单中"
    elif status == IPStatus.Suspicion:
        return "频繁触发警告"  
    return "lpl 加油!"



@app.route('/form',methods=['POST'])
def form():

    #获取上传的文件
    files = request.files
    for key in files:
        file = files[key]
        file.save(f"imgs/{file.filename}")
    return "upload success"


def openserver():
    import datetime
    timestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f'{timestr} 服务器启动中.....')
    
    # 本地测试
    # app.run(host="0.0.0.0", port=8000,debug=True)

    # debug开发模式
    # app.run(host="0.0.0.0", port=8002, ssl_context=(
    #     'www.geek7.top.crt', 'www.geek7.top.key'))

    #生产环境
    from gevent import pywsgi
    server = pywsgi.WSGIServer(('0.0.0.0',8002),app,keyfile='www.geek7.top.key', certfile='www.geek7.top.crt')
    server.serve_forever()


if __name__ == '__main__':
    openserver()
 

LockIP.py

import time
from enum import Enum

request_history = {}  #请求历史信息 包含ip 最后一次请求时间戳 频繁请求计数 违规次数
blacklist = [] #黑名单 通知一次玩家已经是在黑名单了
locklist = []  #锁定列表 返回空字符串


class IPStatus(Enum):
     General = 1    
     Lock = 2
     Suspicion = 3


def check( ip ):
    # 锁定ip列表
    if ip in locklist:
        return IPStatus.Lock

    # 黑名端 会通知一次客户端
    if ip in blacklist:
        locklist.append(ip)
        return IPStatus.Suspicion

    # 1秒内请求限制5次
    if ip not in request_history.keys():
        request_history[ip] = [time.time(), 1, 0 ]  # 最近call的时间, 短时间内调用的次数, 频繁计数
    else:
        if time.time() - request_history[ip][0] < 1:
            request_history[ip][1] += 1
            # 频繁请求 违规处理
            if request_history[ip][1] >= 5:
                #违规次数统计
                request_history[ip][2] += 1
                if request_history[ip][2] >= 5:
                    blacklist.append(ip) #加入黑名端
                return IPStatus.Suspicion
        else:
            request_history[ip][1] = 1
        request_history[ip][0] = time.time()
    return IPStatus.General

Demo 仓库

github

你可能感兴趣的:(Python,Nginx,WebServer,python,服务器,https)