有了简单方便的服务器,(在我的理解下还是个电脑主机,只不过连着网,实际就像个内网的AGV小车,可以ssh到他而已),
ssh远程控制和scp远程传输文件之后,就可以准备代码了,
没做过网页编码,也没了解过什么前后台。
也不知道刚开始要干嘛,就在百度AI搜了一下:
“想自己搭建一个服务器,建立一个微型信息收发服务器”
结果给出的结果是
硬件准备
建议使用闲置电脑或树莓派作为基础设备,配置至少双核CPU(如i5)、8GB内存和500GB SSD+HDD混合存储,确保千兆网卡支持23。若追求低功耗,树莓派是理想选择,其功耗仅5W左右2。
操作系统选择
推荐Ubuntu Server或CentOS等Linux系统,它们免费且稳定性高,适合运行轻量级服务23。若习惯Windows环境,可选用Windows Server 2016及以上版本,但需注意驱动兼容性问题4。
就光看到很高的配置,下面的也没仔细看。
然后AI搜索了一下:
“如何在免费云平台上搭建服务器”
习惯的往下拽看内容,结果上面可选项里最后一条吸引了我的注意力:
阿贝云:国内免备案服务,免费虚拟主机+域名,适合个人博客或测试环境
也不懂什么是备案,什么是域名,就记住名字了,
接着AI搜:
”阿贝云上搭建微型服务器“
给出一段稍微能看懂的代码,是python写的,喜出望外,这个比较熟,还省事,就这么干了
(上面还有一段关键的,就是防火墙放行端口那命令,又被习惯的略过了,导致后来折腾了一天时间)
不过经过上面的搜索,看到了几个关键词,flask看出是个py库,还有系统名字是CentOS,应该是就是Ubantu的马甲,
还有一个不知道是什么的Gunicorn
都扔给AI,继续AI搜索:
“阿贝云的使用方式,比如想要用python+flask做一个最简单的博客应用,使用CentOS,Gunicorn”
这次有详细操作过程和两端代码,全拷贝下来,照着做。
在CentOS系统上使用Python+Flask部署博客应用,可通过Gunicorn作为WSGI服务器实现生产环境运行。以下是关键步骤和配置方法:
环境准备与依赖安装
需安装Python 3、pip及Flask框架,通过pip install flask gunicorn
命令安装核心依赖12。对于数据库支持,可添加SQLAlchemy或直接使用SQLite3。
应用代码结构
基础Flask应用需包含路由定义和模板渲染功能。例如主文件app.py
需定义首页路由和文章展示逻辑,使用render_template
加载HTML模板34。
Gunicorn部署配置
通过命令gunicorn --bind 0.0.0.0:5000 app:app
启动服务,其中app:app
表示模块名与应用实例名12。若需后台运行,可结合nohup或Supervisor管理进程2。
完整项目示例
以下为博客应用的完整代码结构和部署文件:
代码说明:
app.py
定义基础路由和文章数据模拟;index.html
使用Jinja2模板引擎渲染动态内容;requirements.txt
列出运行所需的Python包及版本。
部署时需将整个项目上传至CentOS服务器,通过虚拟环境安装依赖后,使用Gunicorn命令启动服务12。对于持久化存储,可扩展SQLAlchemy实现数据库集成3。
中途和前面还有点AI搜索内容,主打就是一个哪里不懂问哪里,在代码量不大的情况下,AI给出的回答还是挺丰富的,要自己取舍理解
记得他最先给的一个创建文章的html文件,使用的命令和整体博客系统给的不一样,我还追问了
@app.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': title = request.form['title'] content = request.form['content'] new_post = Post(title=title, content=content) db.session.add(new_post) db.session.commit() return redirect(url_for('index')) return render_template('create.html') 使用了这种数据库创建函数,请修改index.html与之对应
之后又给了我一个40多行的更新后的网页文件。
在本地拿pycharm运行他给的三个文件之一的main.py,各种提示命令找不到,然后接着搜,按回答,安装各种pip包,最后运行起来,pycharm下面的输出栏里就会出现本机地址:5000 这么一个链接,点开就自动打开浏览器,结果一个空白还是个404没记住,pycharm下面信息也报错了,提示找不到index.html.
老规矩接着搜,原来是没把网页文件放到合适的文件夹里,我还好奇百度给的代码里,网页文件名前面带着路径。。。。按他给的结构,建立好文件夹,放到对应位置。再运行!
横空出世
然后自己新建了好多,一个个便利贴样子的帖子就出来啦,不过排布方式和显示方式我也控制不了,不过也挺满意的,后续的代码修改,也可以进行了
结构中,index.html 代码如下:
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>我的博客</title> 7 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> 8 </head> 9 <body class="bg-light"> 10 <div class="container py-5"> 11 <div class="d-flex justify-content-between align-items-center mb-4"> 12 <h1 class="display-4">文章列表</h1> 13 <a href="/create" class="btn btn-primary">新建文章</a> 14 </div> 15 16 <div class="row g-4"> 17 {% for post in posts %} 18 <div class="col-md-6 col-lg-4"> 19 <div class="card shadow-sm h-100"> 20 <div class="card-body"> 21 <h5 class="card-title">{{ post.title }}</h5> 22 <p class="card-text text-muted">{{ post.content|truncate(100) }}</p> 23 </div> 24 <div class="card-footer bg-transparent"> 25 <small class="text-muted">发布于 {{ post.created_at.strftime('%Y-%m-%d') }}</small> 26 </div> 27 </div> 28 </div> 29 {% else %} 30 <div class="col-12"> 31 <div class="alert alert-info">暂无文章,点击上方按钮创建第一篇</div> 32 </div> 33 {% endfor %} 34 </div> 35 </div> 36 37 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> 38 </body> 39 </html>
Create.html如下
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>新建文章 - 我的博客</title> 7 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> 8 <style> 9 .form-container { 10 max-width: 800px; 11 margin: 2rem auto; 12 padding: 2rem; 13 background: white; 14 border-radius: 10px; 15 box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1); 16 } 17 .form-title { 18 margin-bottom: 1.5rem; 19 padding-bottom: 0.5rem; 20 border-bottom: 1px solid #eee; 21 } 22 .form-control:focus { 23 border-color: #86b7fe; 24 box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25); 25 } 26 </style> 27 </head> 28 <body class="bg-light"> 29 <div class="container py-5"> 30 <div class="form-container"> 31 <h2 class="form-title">撰写新文章</h2> 32 <form method="POST" action="/create"> 33 <div class="mb-3"> 34 <label for="title" class="form-label">文章标题</label> 35 <input type="text" class="form-control" id="title" name="title" required> 36 </div> 37 <div class="mb-4"> 38 <label for="content" class="form-label">文章内容</label> 39 <textarea class="form-control" id="content" name="content" rows="10" required></textarea> 40 </div> 41 <div class="d-flex justify-content-between"> 42 <a href="/" class="btn btn-outline-secondary">取消</a> 43 <button type="submit" class="btn btn-primary">发布文章</button> 44 </div> 45 </form> 46 </div> 47 </div> 48 49 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> 50 <script> 51 // 自动聚焦标题输入框 52 document.addEventListener('DOMContentLoaded', function() { 53 document.getElementById('title').focus(); 54 }); 55 </script> 56 </body> 57 </html>
main.py代码如下
1 # This is a sample Python script. 2 from flask import Flask, render_template, request, redirect, url_for, jsonify 3 from flask_sqlalchemy import SQLAlchemy 4 from datetime import datetime 5 import sqlite3 6 import bcrypt 7 from functools import wraps 8 import os 9 10 11 # Press Shift+F10 to execute it or replace it with your code. 12 # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. 13 14 15 def print_hi(name): 16 # Use a breakpoint in the code line below to debug your script. 17 print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. 18 post_created_at = datetime.now() # 实际应用中这里是从数据库获取的时间 19 20 21 def init_database(): 22 # 连接数据库(不存在则自动创建) 23 conn = sqlite3.connect('blog.db') 24 cursor = conn.cursor() 25 26 cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='users'") 27 if cursor.fetchone(): 28 conn.close() 29 print("数据库已存在,跳过初始化") 30 return 31 32 # 创建用户表 33 cursor.execute('''CREATE TABLE IF NOT EXISTS users( 34 id INTEGER PRIMARY KEY AUTOINCREMENT, 35 username TEXT UNIQUE NOT NULL, 36 password TEXT NOT NULL, 37 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 38 )''') 39 40 # 创建文章表 41 cursor.execute('''CREATE TABLE IF NOT EXISTS posts( 42 id INTEGER PRIMARY KEY AUTOINCREMENT, 43 title TEXT NOT NULL, 44 content TEXT NOT NULL, 45 author_id INTEGER NOT NULL, 46 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 47 FOREIGN KEY(author_id) REFERENCES users(id) 48 )''') 49 50 # 插入初始用户 51 cursor.execute("INSERT OR IGNORE INTO users(username, password) VALUES (?,?)", 52 ('user1', 'securepassword123')) 53 54 # 插入示例文章 55 cursor.execute("INSERT INTO posts(title, content, author_id) VALUES (?,?,?)", 56 ('欢迎使用博客', '这是第一篇示例文章', 1)) 57 58 conn.commit() 59 conn.close() 60 print("数据库初始化完成") 61 62 63 app = Flask(__name__) 64 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 65 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 66 db = SQLAlchemy(app) 67 68 69 class Post(db.Model): 70 id = db.Column(db.Integer, primary_key=True) 71 title = db.Column(db.String(100), nullable=False) 72 content = db.Column(db.Text, nullable=False) 73 created_at = db.Column(db.DateTime, default=datetime.now, nullable=False) 74 75 76 @app.route('/') 77 def index(): 78 posts = Post.query.order_by(Post.created_at.desc()).all() 79 return render_template('index.html', posts=posts) 80 81 82 @app.route('/create', methods=['GET', 'POST']) 83 def create(): 84 if request.method == 'POST': 85 title = request.form['title'] 86 content = request.form['content'] 87 new_post = Post(title=title, content=content) 88 db.session.add(new_post) 89 db.session.commit() 90 return redirect(url_for('index')) 91 return render_template('create.html') 92 93 # Press the green button in the gutter to run the script. 94 if __name__ == '__main__': 95 print_hi('PyCharm') 96 init_database() 97 with app.app_context(): 98 db.create_all() 99 app.run(host='0.0.0.0', port=5000) 100 101 # See PyCharm help at https://www.jetbrains.com/help/pycharm/ 102 # sudo apt-get update 103 # sudo apt-get install python3-pip 104 # sudo pip3 install virtualenv 105 # mkdir /var/www/flaskapp && cd /var/www/flaskapp 106 # virtualenv -p python3 venv 107 # source venv/bin/activate 108 # pip install flask gunicorn