如何用Flask搭建一个博客后台系统?

摘要:1.安装 1.1 创建虚拟环境 mkdir myproject cd myproject python3 -m venv venv 1.2 进入虚拟环境 . venvbinactivate 1.3 安装 flask pip instal
目录1.安装1.1 创建虚拟环境1.2 进入虚拟环境1.3 安装 flask2.上手2.1 最小 Demo2.2 基本知识3.解构官网指导 Demo3.1 克隆与代码架构分析3.2 入口文件 init.py3.3 数据库设置3.4 蓝图和视图4.其他5.跑起 DEMO参考链接 1.安装 1.1 创建虚拟环境 mkdir myproject cd myproject python3 -m venv venv 1.2 进入虚拟环境 . venv/bin/activate 1.3 安装 flask pip install Flask 2.上手 2.1 最小 Demo 将下列代码保存为 hello.py: from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" 运行上述代码: export FLASK_APP=hello flask run 这样访问:http://127.0.0.1:5000 会看到 Hello, World! 2.2 基本知识 这里有 flask 的基本知识(非常重要的基础,大家可以自己看:链接 HTML Escaping (利用 Jinja,参考:链接 Routing (下面几个例子) @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return f'User {escape(username)}' @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {escape(subpath)}' HTTP Methods @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': else: Static Files (url_for('static', filename='style.css')) Rendering Templates (这个参考之前的 Jinja) File Uploads、Cookies、Redirects and Errors、About Responses、APIs with JSON、Sessions、Message Flashing、Logging 这些等我们实际用到时再过来看 3.解构官网指导 Demo 第 1 节教大家如何利用 python 虚拟环境,快速构建 flask 环境;第 2 节带着大家简单熟悉了 flask 的编程规则(或风格)。 大家在着手本节时,务必将第 2 节中的基础的代码跟着官网敲一下!因为,这一节我们不是由简到难一步步搭建 flask 服务器,而是直接拿搭建好的反过来分析。
阅读全文