flask创建工程

flask入门

flask更加方便把,配置也更加简单一些,首先看看目录结构吧

app
├── 001flask.py
├── static
│   └── site.css
├── templates
│   └── index.html
└── tmp

其中001flask.py文件就是 主文件

启动方式是

$ python 001flask.py

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 120-472-390

这样整个程序就运行了
通过提示我们访问http://127.0.0.1:5000/ 就可以访问我们网站了.

具体文件分析

001flask.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html',title = 'Welcome to learn Flask')

@app.route('/services')
def services():
    return 'Services'

@app.route('/about')
def about():
    return 'About'

这里的@app.route()路由函数 相当于django中的views视图函数, / 是根目录 也就是访问http://127.0.0.1:5000 会执行, 返回内容中 使用了 模板, 模板文件会自动去 templates目录中寻找不要写 全整路径.

如果访问 http://127.0.0.1:5000/services 就会返回相应的内容。

title = ‘Welcome to learn Flask’ 这是在给 模板index.html 传递一个模板变量, 会自动到html中匹配替换.


index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename = 'site.css')}}   ">
</head>
<body>
    <h1>{{title}}</h1>
    <nav>
        <a href="{{ url_for('.services') }}">Services</a>
        <a href="{{ url_for('.about') }}">About</a>
    </nav>
</body>
</html>

其中使用了{{title}} 模板变量 和 url_for函数, 外部链接的css文件放到static目录中,格式如上

href="{{ url_for('static', filename = 'site.css')}}
本文总阅读量