将Python程序上传到WordPress博客

1. 创建一个基于Flack的Web应用程序

首先,确保已安装Python环境。然后在命令提示符中运行一下命令以安装所需的库:

pip isntall Flask Pillow

创建一个新的Python文件(例如:flask_grayscale_converter.py),在文中输入一下代码:

import os
from flask import Flask, request, send_file
from PIL import Image
import io

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        file = request.files["image"]
        image = Image.open(file.stream).convert("L")  # 转换为灰度图像
        output = io.BytesIO()
        image.save(output, format="JPEG")
        output.seek(0)

        # 清理缓存
        file.close()
        image.close()

        return send_file(output, as_attachment=True, download_name="gray_image.jpg", mimetype="image/jpeg")

    return '''
    <!doctype html>
    <html>
    <head>
        <style>
            /* 上传表单的样式 */
            form {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              max-width: 500px;
              margin: 0 auto;
              padding: 20px;
              background-color: #f9f9f9;
              border-radius: 5px;
              box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }

            /* 输入框样式 */
            input[type="file"] {
              margin-bottom: 20px;
            }

            /* 提交按钮样式 */
            input[type="submit"] {
              padding: 10px 20px;
              background-color: #4CAF50;
              color: white;
              font-weight: bold;
              border: none;
              border-radius: 3px;
              cursor: pointer;
            }

            input[type="submit"]:hover {
              background-color: #45a049;
            }
        </style>
    </head>
    <body>
    <form method=post enctype=multipart/form-data>
        <input type=file name=image>
        <input type=submit value="上传并转换">
    </form>
    </body>
    </html>
    '''

if __name__ == "__main__":
    app.run(debug=True, port=int(os.environ.get("PORT", 8000)))

保存并运行此Python文件。这将启动一个简单的Flash Web应用程序,可以通过访问http://locakhost:8000在浏览器中查看它,确保在本地环境中此应用程序正常工作。

2. 部署Flask应用程序

  • 确保已在服务器中安装了Python环境。可以通过ssh连接到自己的服务器,然后使用python --version命令检查python是否已安装。

  • 将步骤1中创建的Flask应用程序(flask_grayscale_converter.py)上传到服务器。可以使用FTP工具(如FileZilla)或通过SCP命令将文件传输到服务器。

    • 使用SCP命令上传文件:
      • 打开命令行,输入以下命令:
        scp flask_grayscale_converter.py your_username@your_server_ip:/path/to/destination_folder

        请将your_username、your_server_ip和/path/to/destination_folder替换为实际值.

      • 输入服务器密码进行身份验证。文件将开始上传到服务器。
      • 上传完成后,可以通过SSH连接到服务器并使用ls /path/to/destination_folder命令确认文件已成功上传。
  • 在服务器上安装必要的Python库。通过ssh连接到服务器并运行一下命令:

    pip install Flask Pillow
  • 安装并配置Gunicorn作为应用程序服务器。在服务器上运行以下命令安装Gunicorn:

    pip install gunicorn
  • 使用Gunicorn启动Flask应用程序。在应用程序所在目录中运行以下命令(请确保将flask_grayscale_converter替换为实际应用程序文件名,不带.py扩展名):

    gunicorn -w 4 -b 0.0.0.0:8000 flask_grayscale_converter:app

    这将在服务器的8000端口上启动Flask应用程序。可以通过访问http://your_server_ip:8000来查看应用程序。

  • 配置Nginx反向代理以提高安全性和性能。如果服务器上没有Nginx,可以通过以下命令安装:

    • 对于Ubuntu/Debian:
      sudo apt-get install nginx
    • 对于CentOS/RHEL:

      sudo yum install nginx

      配置Nginx,创建一个新的配置文件,例如/etc/nginx/sites-available/your_app,并添加以下内容:

      server {
      listen 80;
      server_name your_domain_name;
      
      location / {
          proxy_pass http://127.0.0.1:8000;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
      }
      }

      your_domain_name替换为自己实际使用的域名。然后,创建一个符号链接:

      sudo ln -s /etc/nginx/sites-available/your_app /etc/nginx/sites-enabled/

    重启Nginx以应用更改:

    sudo service nginx restart

    现在,Flask应用程序将通过http://your_domain_name访问,而不是直接使用IP地址和端口。

3. 在WordPress中嵌入Flask应用程序

  • 登录WordPress博客后台。
  • 从左侧菜单栏中,选择“插件”>“安装插件”。
  • 搜索“Iframe”插件,并点击“安装现在”,在安装Iframe插件后,点击“启用”按钮以启用该插件。
  • 转到要嵌入应用程序的页面或文章的编辑器,然后在适当的位置添加以下短代码,将下列语句放在[]中:

    iframe src="http://your_domain_name" width="100%" height="500"

    your_domain_name替换为在步骤2中为Flask应用程序设置的域名。

  • 保存页面或文章,然后在前端查看。Flask应用程序现已嵌入到WordPress博客中,访客可以直接在博客上使用图片灰度转换功能。

4. 确保Gunicorn应用程序在后台持续运行

为了确保Gunicorn应用程序在后台持续运行,并在系统启动时自动启动,可以使用systemd创建一个服务单元。systemd服务单元的创建步骤:

  • 创建一个名为flask_grayscale_converter.service的新文件,并将其放在/etc/systemd/system目录中。
    sudo touch /etc/systemd/system/flask_grayscale_converter.service
    sudo nano /etc/systemd/system/flask_grayscale_converter.service
  • 将以下内容粘贴到刚刚创建的服务文件中。确保将/path/to/your/app替换为Flask应用程序实际所在的路径,以及将your_username替换为运行应用程序的用户。

    [Unit]
    Description=Gunicorn instance to serve Flask Grayscale Converter
    After=network.target
    
    [Service]
    User=your_username
    Group=your_username
    WorkingDirectory=/path/to/your/app
    Environment="PATH=/path/to/your/app/venv/bin"
    ExecStart=/path/to/your/app/venv/bin/gunicorn --workers 4 --bind 0.0.0.0:8000 flask_grayscale_converter:app
    
    [Install]
    WantedBy=multi-user.target
  • 保存并退出文件。
  • 重新加载systemd以识别新服务:
    sudo systemctl daemon-reload
  • 启动Flask Grayscale Converter服务:
    sudo systemctl start flask_grayscale_converter.service
  • 确保服务没有错误,并且一切正常:
    sudo systemctl status flask_grayscale_converter.service
  • 如果一切正常,启用服务以在系统启动时自动运行:
    sudo systemctl enable flask_grayscale_converter.service

    这样应用程序将在后台持续运行,并在服务器启动时自动启动。不再需要手动运行Gunicorn命令来启动应用程序。

5. 创建虚拟环境

  • 确保已安装 Python 和 virtualenv。如果没有,安装:
    sudo apt-get update
    sudo apt-get install python3 python3-pip
    pip3 install --user virtualenv
  • 创建一个新的虚拟环境:
    mkdir -p /opt/myapp
    cd /opt/myapp
    python3 -m venv venv
  • 激活虚拟环境:
    source /opt/myapp/venv/bin/activate
  • 在虚拟环境中安装您的应用程序所需的依赖项(确保已激活虚拟环境):
    pip install -r requirements.txt

    这里的requirements.txt文件应包含您的应用程序需要的所有库及其版本。例如:

    Flask==x.x.x
    gunicorn==y.y.y
  • 安装 Gunicorn:
    pip install gunicorn
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇

© 2025 dgwr

京ICP备2021028536号