Flask入门小项目 - 搭建极简博客(2)添加主页

目录:

完整程序点这

零、效果

往数据库中添加数据后,再刷新页面

一、修改app.py

# app.py

from flask import Flask, render_template, flash, request, session, redirect, url_for, abort
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, login_required, login_user, logout_user

app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

from models import *


@app.route('/')
def index():
    articles = Article.query.all()
    articles_dict = [dict(id=article.id, title=article.title, text=article.text) for article in articles]
    return render_template('index.html', articles=articles_dict)


@app.route('/login')
def login():
    return 'Hello World!'


@app.route('/logout')
def logout():
    return 'Hello World!'


@app.route('/signup')
def signup():
    return 'Hello World!'


@app.route('/post')
def post():
    return 'Hello World!'


@app.route('/delete')
def delete():
    return 'Hello World!'


if __name__ == '__main__':
    app.run(debug=True)

二、修改base.html和index.html

base.html

<!doctype html>
<html>
  <head>
    <title>Simple Blog</title>
    <link rel='stylesheet' type='text/css' href="{{ url_for('static', filename='style.css') }}">
  </head>

  <body>
    <div class='page'>
      <h1><a href="{{ url_for('index') }}">Simple Blog</a></h1>

      <div class='metanav'>
            <a href="{{ url_for('post') }}">post</a>
            <a href="{{ url_for('delete') }}">delete</a>
            <a href="{{ url_for('signup') }}">signup</a>
            {% if not session.login %}
                 <a href="{{ url_for('login') }}">login</a>
            {% else %}
                <a href="{{ url_for('logout') }}">logout</a>
            {% endif %}
      </div>

      {% for message in get_flashed_messages() %}
        <div class='flash'>{{ message }}</div>
      {% endfor %}

      {% block body %}{% endblock %}
    </div>
  </body>
</html>

index.html

{% extends "base.html" %}

{% block body %}

        <ul class=entries>
        {% for article in articles %}
            <li><h2>{{ article.id}}.{{ article.title }}</h2>{{ article.text|safe }}</li>
        {% else %}
            <li><em>Unbelievable, no articles here so far.</em><li>
        {% endfor %}
        </ul>

{% endblock %}

posted on 2020-04-10 12:49  HolaWorld  阅读(460)  评论(0编辑  收藏  举报

导航