|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
引言
Slackware Linux作为最古老的Linux发行版之一,以其稳定性、简洁性和高度可定制性而闻名。对于追求系统控制和性能优化的高级开发者来说,Slackware提供了一个理想的平台。本文将深入探讨如何在Slackware系统上搭建一个高级编程环境,从内核级别的优化到各种开发工具的配置,帮助你充分发挥系统潜力,提升编程效率和技术能力。
1. Slackware系统安装与基础配置
1.1 系统安装准备
在开始之前,我们需要确保系统安装的准备工作就绪:
- # 下载最新Slackware ISO
- wget https://mirrors.slackware.com/slackware/slackware64-current-iso/install-dvd/slackware64-current-install-dvd.iso
- # 创建可启动USB
- dd if=slackware64-current-install-dvd.iso of=/dev/sdX bs=4M status=progress
复制代码
1.2 基础系统安装
Slackware的安装过程相对简单,但需要一定的Linux知识。安装过程中,请确保选择”full”安装模式,这样可以确保所有开发工具和库都被安装。
- # 安装完成后,首先更新系统
- slackpkg update
- slackpkg upgrade-all
复制代码
1.3 基础系统配置
安装完成后,我们需要进行一些基础配置:
- # 配置网络
- nano /etc/rc.d/rc.inet1.conf
- # 设置主机名
- nano /etc/HOSTNAME
- echo "yourhostname" > /etc/HOSTNAME
- # 配置时区
- ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
复制代码
2. 内核优化与定制
2.1 获取内核源码
Slackware默认提供内核源码包,我们可以直接安装:
- slackpkg install kernel-source
复制代码
或者从官方源下载最新内核:
- wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.15.12.tar.xz
- tar -xf linux-5.15.12.tar.xz
- cd linux-5.15.12
复制代码
2.2 内核配置与编译
优化内核是提升系统性能的关键步骤:
- # 复制当前配置
- cp /boot/config-$(uname -r) .config
- # 打开配置菜单
- make menuconfig
复制代码
在内核配置中,以下选项对开发环境特别重要:
- Processor type and features --->
- [*] Preemption Model (Voluntary Kernel Preemption (Desktop)) --->
- [*] Timer frequency (1000 HZ) --->
- Power management and ACPI options --->
- [*] CPU Frequency scaling --->
- <*> CPU frequency translation statistics
- [*] CPU frequency translation statistics details
- File systems --->
- <*> Btrfs filesystem support
- <*> XFS filesystem support
- <*> JFS filesystem support
- <*> Reiserfs filesystem support
复制代码
配置完成后,编译并安装新内核:
- # 使用多线程编译以加快速度
- make -j$(nproc)
- # 安装模块
- make modules_install
- # 安装内核
- make install
- # 更新引导配置
- lilo
复制代码
2.3 内核参数优化
通过调整内核参数,可以进一步提升系统性能:
- # 编辑sysctl配置
- nano /etc/sysctl.conf
- # 添加以下内容
- # 增加文件描述符限制
- fs.file-max = 100000
- # 优化网络栈
- net.core.rmem_max = 16777216
- net.core.wmem_max = 16777216
- net.ipv4.tcp_rmem = 4096 87380 16777216
- net.ipv4.tcp_wmem = 4096 65536 16777216
- net.ipv4.tcp_congestion_control = bbr
- # 优化虚拟内存管理
- vm.swappiness = 10
- vm.dirty_ratio = 60
- vm.dirty_background_ratio = 2
- # 应用配置
- sysctl -p
复制代码
3. 开发工具链配置
3.1 基础开发工具安装
Slackware默认已经包含了许多开发工具,但我们需要确保所有必要的工具都已安装:
- slackpkg install slackpkg install gcc g++ make cmake autoconf automake libtool
- slackpkg install git subversion mercurial
- slackpkg install python python3 perl ruby
- slackpkg install jdk openjdk
复制代码
3.2 编译器优化配置
为了获得最佳性能,我们需要优化编译器设置:
- # 创建全局编译器配置
- nano /etc/profile.d/compiler-opts.sh
- # 添加以下内容
- export CFLAGS="-march=native -O2 -pipe -fstack-protector-strong"
- export CXXFLAGS="${CFLAGS}"
- export LDFLAGS="-Wl,-O1,--sort-common,--as-needed,-z,relro"
- # 使配置生效
- source /etc/profile
复制代码
3.3 多版本编译器管理
在某些情况下,我们可能需要使用不同版本的编译器:
- # 安装编译器版本管理工具
- slackpkg install gcc-toolset
- # 安装特定版本的GCC
- slackpkg install gcc9 gcc10 gcc11
- # 使用update-alternatives管理版本
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 9
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 10
- update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 11
- # 切换GCC版本
- update-alternatives --config gcc
复制代码
4. 常用编程语言环境搭建
4.1 Python开发环境
Python是现代开发中不可或缺的语言,我们需要一个完善的Python环境:
- # 安装Python和pip
- slackpkg install python3 python3-pip
- # 升级pip
- pip install --upgrade pip
- # 安装虚拟环境工具
- pip install virtualenv virtualenvwrapper
- # 配置virtualenvwrapper
- echo "export WORKON_HOME=\$HOME/.virtualenvs" >> ~/.bashrc
- echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.bashrc
- echo "source /usr/bin/virtualenvwrapper.sh" >> ~/.bashrc
- source ~/.bashrc
- # 创建Python开发环境
- mkvirtualenv py3dev
- workon py3dev
- # 安装常用Python包
- pip install numpy scipy pandas matplotlib jupyter
- pip install django flask fastapi
- pip install pytest black pylint
复制代码
4.2 C/C++开发环境
C/C++开发需要一套完整的工具链:
- # 安装必要的开发库
- slackpkg install kernel-headers glibc glibc-devel glibc-profile
- slackpkg install zlib zlib-devel openssl openssl-devel
- slackpkg install readline readline-devel ncurses ncurses-devel
- slackpkg install gtk+3-devel qt5-devel
- # 安装构建工具
- slackpkg install ninja meson scons
- slackpkg install ccache distcc
- # 配置ccache以加速编译
- echo "export CCACHE_DIR=\$HOME/.ccache" >> ~/.bashrc
- echo "export CCACHE_MAXSIZE=5G" >> ~/.bashrc
- echo "export CCACHE_COMPRESS=1" >> ~/.bashrc
- source ~/.bashrc
- # 安装IDE支持
- slackpkg install vscode emacs vim
复制代码
4.3 Java开发环境
Java开发需要JDK和构建工具:
- # 安装OpenJDK
- slackpkg install openjdk openjdk-devel
- # 安装Maven和Gradle
- slackpkg install maven gradle
- # 配置JAVA_HOME
- echo "export JAVA_HOME=/usr/lib64/java" >> ~/.bashrc
- echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> ~/.bashrc
- source ~/.bashrc
- # 验证安装
- java -version
- mvn -version
- gradle -version
复制代码
4.4 Go语言环境
Go语言在现代开发中越来越受欢迎:
- # 下载并安装Go
- wget https://golang.org/dl/go1.17.6.linux-amd64.tar.gz
- tar -C /usr/local -xzf go1.17.6.linux-amd64.tar.gz
- # 配置环境变量
- echo "export PATH=\$PATH:/usr/local/go/bin" >> ~/.bashrc
- echo "export GOPATH=\$HOME/go" >> ~/.bashrc
- echo "export PATH=\$PATH:\$GOPATH/bin" >> ~/.bashrc
- source ~/.bashrc
- # 验证安装
- go version
复制代码
4.5 Rust语言环境
Rust是系统编程的新宠:
- # 安装Rust
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- source ~/.cargo/env
- # 配置环境
- echo "source ~/.cargo/env" >> ~/.bashrc
- source ~/.bashrc
- # 安装常用工具
- rustup component add rustfmt clippy rust-src
- cargo install racer
- # 验证安装
- rustc --version
- cargo --version
复制代码
5. 高级开发环境配置
5.1 数据库环境配置
现代开发离不开数据库支持:
- # 安装MySQL/MariaDB
- slackpkg install mariadb mariadb-client mariadb-server
- # 初始化数据库
- mysql_install_db --user=mysql --ldata=/var/lib/mysql
- # 启动服务
- chmod +x /etc/rc.d/rc.mysqld
- /etc/rc.d/rc.mysqld start
- # 安全配置
- mysql_secure_installation
- # 安装PostgreSQL
- slackpkg install postgresql postgresql-contrib
- # 初始化数据库
- su - postgres -c "initdb -D /var/lib/pgsql"
- # 启动服务
- chmod +x /etc/rc.d/rc.postgresql
- /etc/rc.d/rc.postgresql start
- # 安装Redis
- slackpkg install redis
- # 配置Redis
- cp /etc/redis.conf /etc/redis.conf.bak
- nano /etc/redis.conf
- # 启动Redis
- chmod +x /etc/rc.d/rc.redis
- /etc/rc.d/rc.redis start
复制代码
5.2 容器化环境
容器化是现代开发的重要部分:
- # 安装Docker
- slackpkg install docker docker-compose
- # 启动Docker服务
- chmod +x /etc/rc.d/rc.docker
- /etc/rc.d/rc.docker start
- # 将用户添加到docker组
- usermod -aG docker $USER
- newgrp docker
- # 验证安装
- docker run hello-world
- # 安装Kubernetes工具
- slackpkg install kubectl kubeadm kubelet
复制代码
5.3 版本控制与协作工具
高效的团队协作需要完善的版本控制工具:
- # 安装Git并配置
- slackpkg install git git-lfs
- # 配置Git
- git config --global user.name "Your Name"
- git config --global user.email "your.email@example.com"
- git config --global core.editor vim
- git config --global color.ui true
- # 生成SSH密钥
- ssh-keygen -t rsa -b 4096 -C "your.email@example.com"
- # 安装GitHub CLI
- wget https://github.com/cli/cli/releases/download/v2.14.7/gh_2.14.7_linux_amd64.tar.gz
- tar -xf gh_2.14.7_linux_amd64.tar.gz
- cp gh_2.14.7_linux_amd64/bin/gh /usr/local/bin/
- # 安装其他协作工具
- slackpkg install tig meld
复制代码
6. 性能优化与调试工具
6.1 系统监控工具
了解系统状态是优化的第一步:
- # 安装系统监控工具
- slackpkg install htop iotop iftop nethogs
- slackpkg install sysstat vmstat dstat
- slackpkg install ncdu nmap
- # 配置sysstat
- nano /etc/sysconfig/sysstat
- # 设置ENABLED="true"
- # 启动sysstat
- chmod +x /etc/rc.d/rc.sysstat
- /etc/rc.d/rc.sysstat start
复制代码
6.2 性能分析工具
深入分析程序性能需要专业工具:
- # 安装性能分析工具
- slackpkg install perf valgrind gprof
- slackpkg install strace ltrace
- # 安装火焰图工具
- git clone https://github.com/brendangregg/FlameGraph.git
- cp FlameGraph/flamegraph.pl /usr/local/bin/
- # 安装eBPF工具
- git clone https://github.com/iovisor/bcc.git
- cd bcc
- ./install.sh
复制代码
6.3 调试工具
高效的调试可以大大提高开发效率:
- # 安装调试工具
- slackpkg install gdb cgdb
- slackpkg install electric-fence duma
- # 配置GDB
- echo "set pagination off" >> ~/.gdbinit
- echo "set confirm off" >> ~/.gdbinit
- echo "set height 0" >> ~/.gdbinit
- echo "set width 0" >> ~/.gdbinit
- # 安装内存分析工具
- slackpkg install massif visualizer
复制代码
7. 实际项目案例演示
7.1 C++高性能计算项目
让我们创建一个简单的C++高性能计算项目:
- // 创建项目目录结构
- mkdir -p ~/projects/hpccalc/src ~/projects/hpccalc/include ~/projects/hpccalc/build
- // 创建头文件 include/matrix.h
- #ifndef MATRIX_H
- #define MATRIX_H
- #include <vector>
- class Matrix {
- private:
- std::vector<std::vector<double>> data;
- size_t rows;
- size_t cols;
- public:
- Matrix(size_t r, size_t c);
- Matrix(const Matrix& other);
- ~Matrix();
- double& operator()(size_t i, size_t j);
- const double& operator()(size_t i, size_t j) const;
-
- Matrix operator*(const Matrix& other) const;
-
- size_t getRows() const;
- size_t getCols() const;
-
- void randomize();
- void print() const;
- };
- #endif // MATRIX_H
复制代码- // 创建源文件 src/matrix.cpp
- #include "matrix.h"
- #include <iostream>
- #include <random>
- #include <stdexcept>
- Matrix::Matrix(size_t r, size_t c) : rows(r), cols(c) {
- data.resize(rows, std::vector<double>(cols, 0.0));
- }
- Matrix::Matrix(const Matrix& other) : rows(other.rows), cols(other.cols), data(other.data) {}
- Matrix::~Matrix() {}
- double& Matrix::operator()(size_t i, size_t j) {
- if (i >= rows || j >= cols) {
- throw std::out_of_range("Matrix index out of range");
- }
- return data[i][j];
- }
- const double& Matrix::operator()(size_t i, size_t j) const {
- if (i >= rows || j >= cols) {
- throw std::out_of_range("Matrix index out of range");
- }
- return data[i][j];
- }
- Matrix Matrix::operator*(const Matrix& other) const {
- if (cols != other.rows) {
- throw std::invalid_argument("Matrix dimensions do not match for multiplication");
- }
-
- Matrix result(rows, other.cols);
-
- #pragma omp parallel for collapse(2)
- for (size_t i = 0; i < rows; ++i) {
- for (size_t j = 0; j < other.cols; ++j) {
- double sum = 0.0;
- for (size_t k = 0; k < cols; ++k) {
- sum += data[i][k] * other.data[k][j];
- }
- result(i, j) = sum;
- }
- }
-
- return result;
- }
- size_t Matrix::getRows() const { return rows; }
- size_t Matrix::getCols() const { return cols; }
- void Matrix::randomize() {
- std::random_device rd;
- std::mt19937 gen(rd());
- std::uniform_real_distribution<> dis(0.0, 1.0);
-
- #pragma omp parallel for collapse(2)
- for (size_t i = 0; i < rows; ++i) {
- for (size_t j = 0; j < cols; ++j) {
- data[i][j] = dis(gen);
- }
- }
- }
- void Matrix::print() const {
- for (size_t i = 0; i < rows; ++i) {
- for (size_t j = 0; j < cols; ++j) {
- std::cout << data[i][j] << " ";
- }
- std::cout << std::endl;
- }
- }
复制代码- // 创建主程序 src/main.cpp
- #include <iostream>
- #include <chrono>
- #include "matrix.h"
- int main() {
- const size_t SIZE = 1000;
-
- std::cout << "Creating matrices of size " << SIZE << "x" << SIZE << std::endl;
-
- auto start = std::chrono::high_resolution_clock::now();
-
- Matrix a(SIZE, SIZE);
- Matrix b(SIZE, SIZE);
-
- a.randomize();
- b.randomize();
-
- auto end = std::chrono::high_resolution_clock::now();
- std::chrono::duration<double> elapsed = end - start;
- std::cout << "Matrix creation and randomization time: " << elapsed.count() << " seconds" << std::endl;
-
- start = std::chrono::high_resolution_clock::now();
-
- Matrix c = a * b;
-
- end = std::chrono::high_resolution_clock::now();
- elapsed = end - start;
- std::cout << "Matrix multiplication time: " << elapsed.count() << " seconds" << std::endl;
-
- // Uncomment to print a small portion of the result
- // std::cout << "Sample of result matrix:" << std::endl;
- // for (size_t i = 0; i < 5 && i < c.getRows(); ++i) {
- // for (size_t j = 0; j < 5 && j < c.getCols(); ++j) {
- // std::cout << c(i, j) << " ";
- // }
- // std::cout << std::endl;
- // }
-
- return 0;
- }
复制代码- # 创建CMakeLists.txt
- cmake_minimum_required(VERSION 3.10)
- project(hpccalc)
- set(CMAKE_CXX_STANDARD 17)
- set(CMAKE_CXX_STANDARD_REQUIRED ON)
- # 启用OpenMP
- find_package(OpenMP REQUIRED)
- if(OpenMP_CXX_FOUND)
- target_link_libraries(hpccalc PUBLIC OpenMP::OpenMP_CXX)
- endif()
- # 启用优化
- set(CMAKE_CXX_FLAGS_RELEASE "-O3 -march=native -DNDEBUG")
- # 包含目录
- include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
- # 源文件
- set(SOURCES
- src/matrix.cpp
- src/main.cpp
- )
- # 可执行文件
- add_executable(hpccalc ${SOURCES})
- # 安装规则
- install(TARGETS hpccalc DESTINATION bin)
复制代码- # 编译项目
- cd ~/projects/hpccalc/build
- cmake .. -DCMAKE_BUILD_TYPE=Release
- make -j$(nproc)
- # 运行项目
- ./hpccalc
- # 使用perf分析性能
- perf stat -e cycles,instructions,cache-references,cache-misses ./hpccalc
- # 生成火焰图
- perf record -g ./hpccalc
- perf script | ~/FlameGraph/stackcollapse-perf.pl > out.folded
- ~/FlameGraph/flamegraph.pl out.folded > perf_kernels.svg
复制代码
7.2 Python数据分析项目
创建一个Python数据分析项目,展示如何利用优化后的环境:
- # 创建项目目录
- mkdir -p ~/projects/dataanalysis
- cd ~/projects/dataanalysis
- # 创建虚拟环境
- mkvirtualenv dataanalysis
- workon dataanalysis
- # 安装必要的包
- pip install numpy pandas matplotlib seaborn scikit-learn jupyter
- # 创建数据分析脚本
- cat > analysis.py << 'EOF'
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- import seaborn as sns
- from sklearn.datasets import load_iris
- from sklearn.model_selection import train_test_split
- from sklearn.ensemble import RandomForestClassifier
- from sklearn.metrics import accuracy_score, confusion_matrix
- import time
- # 设置随机种子
- np.random.seed(42)
- # 加载数据
- iris = load_iris()
- X = iris.data
- y = iris.target
- feature_names = iris.feature_names
- target_names = iris.target_names
- # 创建DataFrame
- df = pd.DataFrame(X, columns=feature_names)
- df['species'] = [target_names[i] for i in y]
- # 数据探索
- print("数据前5行:")
- print(df.head())
- print("\n数据统计信息:")
- print(df.describe())
- print("\n各类别数量:")
- print(df['species'].value_counts())
- # 数据可视化
- plt.figure(figsize=(12, 6))
- # 特征分布
- plt.subplot(1, 2, 1)
- for feature in feature_names:
- sns.kdeplot(df[feature], label=feature)
- plt.title('特征分布')
- plt.legend()
- # 类别分布
- plt.subplot(1, 2, 2)
- df['species'].value_counts().plot.pie(autopct='%1.1f%%')
- plt.title('类别分布')
- plt.ylabel('')
- plt.tight_layout()
- plt.savefig('data_exploration.png')
- plt.close()
- # 特征相关性
- plt.figure(figsize=(10, 8))
- correlation = df.drop('species', axis=1).corr()
- sns.heatmap(correlation, annot=True, cmap='coolwarm')
- plt.title('特征相关性')
- plt.tight_layout()
- plt.savefig('correlation.png')
- plt.close()
- # 数据准备
- X_train, X_test, y_train, y_test = train_test_split(
- X, y, test_size=0.3, random_state=42, stratify=y
- )
- # 模型训练
- start_time = time.time()
- model = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
- model.fit(X_train, y_train)
- training_time = time.time() - start_time
- # 模型评估
- y_pred = model.predict(X_test)
- accuracy = accuracy_score(y_test, y_pred)
- conf_mat = confusion_matrix(y_test, y_pred)
- print(f"\n训练时间: {training_time:.4f}秒")
- print(f"准确率: {accuracy:.4f}")
- # 可视化混淆矩阵
- plt.figure(figsize=(8, 6))
- sns.heatmap(conf_mat, annot=True, fmt='d', cmap='Blues',
- xticklabels=target_names, yticklabels=target_names)
- plt.title('混淆矩阵')
- plt.xlabel('预测类别')
- plt.ylabel('真实类别')
- plt.tight_layout()
- plt.savefig('confusion_matrix.png')
- plt.close()
- # 特征重要性
- importances = model.feature_importances_
- indices = np.argsort(importances)[::-1]
- plt.figure(figsize=(10, 6))
- plt.title('特征重要性')
- plt.bar(range(X.shape[1]), importances[indices], align='center')
- plt.xticks(range(X.shape[1]), [feature_names[i] for i in indices])
- plt.tight_layout()
- plt.savefig('feature_importance.png')
- plt.close()
- print("\n分析完成,图表已保存。")
- EOF
- # 运行分析脚本
- python analysis.py
- # 创建Jupyter notebook
- jupyter notebook
复制代码
7.3 Web应用开发项目
创建一个基于Flask的Web应用:
- # 创建项目目录
- mkdir -p ~/projects/webapp/{app,templates,static/{css,js,images}}
- cd ~/projects/webapp
- # 创建虚拟环境
- mkvirtualenv webapp
- workon webapp
- # 安装必要的包
- pip install flask flask-sqlalchemy flask-login flask-wtf flask-migrate
- pip install gunicorn psycopg2-binary
- # 创建应用结构
- cat > app/__init__.py << 'EOF'
- from flask import Flask
- from flask_sqlalchemy import SQLAlchemy
- from flask_login import LoginManager
- from flask_migrate import Migrate
- db = SQLAlchemy()
- login_manager = LoginManager()
- migrate = Migrate()
- def create_app():
- app = Flask(__name__)
-
- app.config['SECRET_KEY'] = 'your-secret-key'
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///webapp.db'
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
-
- db.init_app(app)
- login_manager.init_app(app)
- migrate.init_app(app, db)
-
- login_manager.login_view = 'auth.login'
- login_manager.login_message = '请登录以访问此页面。'
-
- from .auth import auth as auth_blueprint
- app.register_blueprint(auth_blueprint)
-
- from .main import main as main_blueprint
- app.register_blueprint(main_blueprint)
-
- return app
- EOF
- cat > app/models.py << 'EOF'
- from flask_sqlalchemy import SQLAlchemy
- from flask_login import UserMixin
- from werkzeug.security import generate_password_hash, check_password_hash
- from datetime import datetime
- db = SQLAlchemy()
- class User(UserMixin, db.Model):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(64), index=True, unique=True)
- email = db.Column(db.String(120), index=True, unique=True)
- password_hash = db.Column(db.String(128))
- posts = db.relationship('Post', backref='author', lazy='dynamic')
-
- def set_password(self, password):
- self.password_hash = generate_password_hash(password)
-
- def check_password(self, password):
- return check_password_hash(self.password_hash, password)
-
- def __repr__(self):
- return f'<User {self.username}>'
-
- class Post(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- title = db.Column(db.String(140))
- body = db.Column(db.Text)
- timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
-
- def __repr__(self):
- return f'<Post {self.title}>'
- EOF
- cat > app/auth.py << 'EOF'
- from flask import Blueprint, render_template, redirect, url_for, request, flash
- from werkzeug.security import generate_password_hash, check_password_hash
- from flask_login import login_user, logout_user, login_required, current_user
- from .models import User
- from . import db
- auth = Blueprint('auth', __name__)
- @auth.route('/login')
- def login():
- return render_template('login.html')
- @auth.route('/login', methods=['POST'])
- def login_post():
- username = request.form.get('username')
- password = request.form.get('password')
- remember = True if request.form.get('remember') else False
-
- user = User.query.filter_by(username=username).first()
-
- if not user or not user.check_password(password):
- flash('请检查您的登录信息并重试。')
- return redirect(url_for('auth.login'))
-
- login_user(user, remember=remember)
- return redirect(url_for('main.profile'))
- @auth.route('/signup')
- def signup():
- return render_template('signup.html')
- @auth.route('/signup', methods=['POST'])
- def signup_post():
- username = request.form.get('username')
- email = request.form.get('email')
- password = request.form.get('password')
-
- user = User.query.filter_by(email=email).first()
-
- if user:
- flash('该邮箱地址已存在。')
- return redirect(url_for('auth.signup'))
-
- new_user = User(username=username, email=email)
- new_user.set_password(password)
-
- db.session.add(new_user)
- db.session.commit()
-
- return redirect(url_for('auth.login'))
- @auth.route('/logout')
- @login_required
- def logout():
- logout_user()
- return redirect(url_for('main.index'))
- EOF
- cat > app/main.py << 'EOF'
- from flask import Blueprint, render_template, request
- from flask_login import login_required, current_user
- from .models import Post
- from . import db
- main = Blueprint('main', __name__)
- @main.route('/')
- def index():
- posts = Post.query.all()
- return render_template('index.html', posts=posts)
- @main.route('/profile')
- @login_required
- def profile():
- return render_template('profile.html', name=current_user.username)
- @main.route('/create', methods=['GET', 'POST'])
- @login_required
- def create():
- if request.method == 'POST':
- title = request.form.get('title')
- body = request.form.get('body')
-
- post = Post(title=title, body=body, user_id=current_user.id)
- db.session.add(post)
- db.session.commit()
-
- return redirect(url_for('main.index'))
-
- return render_template('create.html')
- EOF
- cat > run.py << 'EOF'
- from app import create_app, db
- from app.models import User, Post
- app = create_app()
- @app.shell_context_processor
- def make_shell_context():
- return {'db': db, 'User': User, 'Post': Post}
- if __name__ == '__main__':
- app.run(debug=True)
- EOF
- # 创建模板
- cat > templates/base.html << 'EOF'
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>{% block title %}WebApp{% endblock %}</title>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
- </head>
- <body>
- <nav class="navbar is-dark" role="navigation" aria-label="main navigation">
- <div class="navbar-brand">
- <a class="navbar-item" href="{{ url_for('main.index') }}">
- <strong>WebApp</strong>
- </a>
- </div>
- <div id="navbarBasicExample" class="navbar-menu">
- <div class="navbar-start">
- <a class="navbar-item" href="{{ url_for('main.index') }}">
- 首页
- </a>
-
- {% if current_user.is_authenticated %}
- <a class="navbar-item" href="{{ url_for('main.create') }}">
- 创建文章
- </a>
- {% endif %}
- </div>
- <div class="navbar-end">
- <div class="navbar-item">
- <div class="buttons">
- {% if current_user.is_authenticated %}
- <a class="button is-light" href="{{ url_for('main.profile') }}">
- 个人资料
- </a>
- <a class="button is-light" href="{{ url_for('auth.logout') }}">
- 退出
- </a>
- {% else %}
- <a class="button is-primary" href="{{ url_for('auth.signup') }}">
- <strong>注册</strong>
- </a>
- <a class="button is-light" href="{{ url_for('auth.login') }}">
- 登录
- </a>
- {% endif %}
- </div>
- </div>
- </div>
- </div>
- </nav>
- <section class="section">
- <div class="container">
- {% with messages = get_flashed_messages() %}
- {% if messages %}
- <div class="notification is-info">
- {{ messages[0] }}
- </div>
- {% endif %}
- {% endwith %}
- {% block content %}{% endblock %}
- </div>
- </section>
- <footer class="footer">
- <div class="content has-text-centered">
- <p>
- <strong>WebApp</strong> by <a href="https://example.com">Your Name</a>.
- </p>
- </div>
- </footer>
- </body>
- </html>
- EOF
- cat > templates/index.html << 'EOF'
- {% extends "base.html" %}
- {% block title %}首页 - WebApp{% endblock %}
- {% block content %}
- <h1 class="title">文章列表</h1>
- {% if posts %}
- <div class="columns is-multiline">
- {% for post in posts %}
- <div class="column is-half">
- <div class="card">
- <header class="card-header">
- <p class="card-header-title">
- {{ post.title }}
- </p>
- <span class="card-header-icon">
- <span class="icon">
- <i class="fas fa-angle-down" aria-hidden="true"></i>
- </span>
- </span>
- </header>
- <div class="card-content">
- <div class="content">
- {{ post.body[:200] }}...
- <br>
- <time datetime="{{ post.timestamp }}">{{ post.timestamp.strftime('%Y-%m-%d %H:%M') }}</time>
- </div>
- </div>
- <footer class="card-footer">
- <a href="#" class="card-footer-item">阅读更多</a>
- </footer>
- </div>
- </div>
- {% endfor %}
- </div>
- {% else %}
- <div class="notification is-warning">
- 暂无文章。
- </div>
- {% endif %}
- {% endblock %}
- EOF
- cat > templates/login.html << 'EOF'
- {% extends "base.html" %}
- {% block title %}登录 - WebApp{% endblock %}
- {% block content %}
- <div class="columns is-centered">
- <div class="column is-one-third">
- <h1 class="title">登录</h1>
- <form action="{{ url_for('auth.login') }}" method="post">
- <div class="field">
- <label class="label">用户名</label>
- <div class="control">
- <input class="input" type="text" name="username" placeholder="用户名" required>
- </div>
- </div>
- <div class="field">
- <label class="label">密码</label>
- <div class="control">
- <input class="input" type="password" name="password" placeholder="密码" required>
- </div>
- </div>
- <div class="field">
- <div class="control">
- <label class="checkbox">
- <input type="checkbox" name="remember">
- 记住我
- </label>
- </div>
- </div>
- <div class="field is-grouped">
- <div class="control">
- <button class="button is-link">登录</button>
- </div>
- <div class="control">
- <a href="{{ url_for('auth.signup') }}" class="button is-text">注册新账户</a>
- </div>
- </div>
- </form>
- </div>
- </div>
- {% endblock %}
- EOF
- cat > templates/signup.html << 'EOF'
- {% extends "base.html" %}
- {% block title %}注册 - WebApp{% endblock %}
- {% block content %}
- <div class="columns is-centered">
- <div class="column is-one-third">
- <h1 class="title">注册</h1>
- <form action="{{ url_for('auth.signup') }}" method="post">
- <div class="field">
- <label class="label">用户名</label>
- <div class="control">
- <input class="input" type="text" name="username" placeholder="用户名" required>
- </div>
- </div>
- <div class="field">
- <label class="label">邮箱</label>
- <div class="control">
- <input class="input" type="email" name="email" placeholder="邮箱" required>
- </div>
- </div>
- <div class="field">
- <label class="label">密码</label>
- <div class="control">
- <input class="input" type="password" name="password" placeholder="密码" required>
- </div>
- </div>
- <div class="field is-grouped">
- <div class="control">
- <button class="button is-link">注册</button>
- </div>
- <div class="control">
- <a href="{{ url_for('auth.login') }}" class="button is-text">已有账户?登录</a>
- </div>
- </div>
- </form>
- </div>
- </div>
- {% endblock %}
- EOF
- cat > templates/profile.html << 'EOF'
- {% extends "base.html" %}
- {% block title %}个人资料 - WebApp{% endblock %}
- {% block content %}
- <h1 class="title">个人资料</h1>
- <div class="box">
- <p class="subtitle">欢迎回来, <strong>{{ name }}</strong>!</p>
- <p>这是您的个人资料页面。</p>
- </div>
- {% endblock %}
- EOF
- cat > templates/create.html << 'EOF'
- {% extends "base.html" %}
- {% block title %}创建文章 - WebApp{% endblock %}
- {% block content %}
- <div class="columns is-centered">
- <div class="column is-two-thirds">
- <h1 class="title">创建新文章</h1>
- <form action="{{ url_for('main.create') }}" method="post">
- <div class="field">
- <label class="label">标题</label>
- <div class="control">
- <input class="input" type="text" name="title" placeholder="文章标题" required>
- </div>
- </div>
- <div class="field">
- <label class="label">内容</label>
- <div class="control">
- <textarea class="textarea" name="body" placeholder="文章内容" rows="10" required></textarea>
- </div>
- </div>
- <div class="field is-grouped">
- <div class="control">
- <button class="button is-link">发布</button>
- </div>
- <div class="control">
- <a href="{{ url_for('main.index') }}" class="button is-text">取消</a>
- </div>
- </div>
- </form>
- </div>
- </div>
- {% endblock %}
- EOF
- # 初始化数据库
- export FLASK_APP=run.py
- flask db init
- flask db migrate -m "Initial migration"
- flask db upgrade
- # 运行应用
- python run.py
- # 使用Gunicorn部署
- gunicorn -w 4 -b 0.0.0.0:8000 run:app
复制代码
8. 总结与进阶学习路径
8.1 环境优化总结
通过本文的详细指导,我们已经成功搭建了一个高度优化的Slackware高级编程环境。这个环境包括:
1. 经过优化的Linux内核,提供了更好的性能和稳定性
2. 完整的开发工具链,支持多种编程语言
3. 高效的调试和性能分析工具
4. 实际项目案例,展示了如何利用这个环境进行开发
8.2 进阶学习建议
要进一步提升技术能力,建议从以下几个方面深入:
1. 内核开发:深入学习Linux内核,尝试编写内核模块
2. 系统性能调优:学习更高级的系统调优技术,如NUMA架构优化、I/O调度器优化等
3. 分布式系统:搭建分布式开发环境,学习分布式计算和存储技术
4. 容器编排:深入学习Kubernetes,搭建容器化开发平台
5. DevOps实践:学习CI/CD流程,搭建自动化开发、测试和部署环境
8.3 持续优化
技术环境搭建是一个持续优化的过程。建议定期:
1. 更新系统和软件包
2. 重新评估和调整内核参数
3. 关注新的开发工具和技术
4. 参与开源社区,分享经验和学习最佳实践
通过不断学习和实践,你将能够充分利用Slackware的强大功能,成为一名真正的编程高手。 |
|