flask 通过二级域名访问文章代码
时间: 2023-05-26 10:05:35 浏览: 66
以下是一个简单的 Flask 应用示例,它实现了通过二级域名访问文章的功能:
```python
from flask import Flask, render_template
app = Flask(__name__)
# 定义文章存储
articles = {
'apples': 'This is an article about apples.',
'bananas': 'This is an article about bananas.',
'oranges': 'This is an article about oranges.',
}
# 定义路由
@app.route('/')
def index():
return render_template('index.html')
@app.route('/<string:subdomain>.localhost:5000')
def article(subdomain):
if subdomain in articles:
return render_template('article.html', article=articles[subdomain])
else:
return 'Article not found.'
if __name__ == '__main__':
app.run(debug=True)
```
在这个示例应用中,首页可以通过访问 `http://localhost:5000/` 来获取,而文章可以通过二级域名形式的 URL 来访问,例如访问 `http://apples.localhost:5000/` 就可以获取关于苹果的文章。
要注意的是,在本地开发环境下,由于没有真正的域名解析,我们需要手动将二级域名映射到本地 IP 地址。在 Windows 操作系统下,可以通过编辑 `C:\Windows\System32\drivers\etc\hosts` 文件来实现,添加以下行:
```
127.0.0.1 apples.localhost
127.0.0.1 bananas.localhost
127.0.0.1 oranges.localhost
```
这样,访问这些二级域名时就会被解析为本机地址。当然,如果有真正的域名解析服务的话,这个步骤是不必要的。