flask 添加的文章用二级域名访问代码案例
时间: 2023-05-26 16:05:24 浏览: 55
下面是一个在 Flask 中添加二级域名访问文章的代码案例:
```python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 定义文章列表
articles = {
'tech': ['Python is a Great Language', 'Flask is My Favorite Framework'],
'food': ['I Love Pizza', 'Burgers are Delicious'],
'travel': ['Traveling in Japan', 'Visiting Rome, Italy']
}
# 定义文章模板
@app.route('/', defaults={'category': 'tech'})
@app.route('/<category>/')
def index(category):
if category not in articles:
# 如果没有这个分类,重定向到默认分类
return redirect(url_for('index'))
else:
# 渲染分类页面
return render_template('index.html', category=category, articles=articles[category])
# 定义文章详情模板
@app.route('/<category>/<article>/')
def article(category, article):
if category not in articles or article not in articles[category]:
# 如果分类或文章不存在,返回 404 错误页面
return render_template('404.html'), 404
else:
# 渲染文章页面
return render_template('article.html', category=category, article=article)
if __name__ == '__main__':
app.run(debug=True)
```
在这个代码案例中,我们使用了 Flask 的路由规则以及模板引擎来实现文章的分类和详情浏览。我们使用默认分类 `tech`,并且在 URL 中添加二级域名来访问不同的文章分类。
例如,访问 `http://tech.example.com/` 会显示默认分类 `tech` 的文章列表。访问 `http://food.example.com/` 则会显示分类 `food` 的文章列表。
在文章详情页面中,我们使用 `category` 和 `article` 参数来找到对应的文章。如果分类或文章不存在,我们会返回一个 404 错误页面。