Flask web开发 简单介绍

Flask是一个基于python的轻量级web框架。当安装好后Flask后 (pip install flask),就可以开始使用了。

一、最简单的例子

1、新建目录,作为web应用的目录,如:

mkdir myapp

2、编写 hello.py文件,放在上面的myapp目录下

from flask import Flask
app = Flask(__name__)

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

@app.route('/name')
def hello_name():
    return 'my name is hello
'

if __name__ == '__main__':
    app.run('0.0.0.0',80)

3、启动flask服务:python hello.py
这时提示

* Running on http://0.0.0.0:80/

然后在浏览器中就可以访问了,如:

http://192.168.142.138     //页面显示Hello World!

http://192.168.142.138/name   //页面显示 my name is hello

说明: 如果希望修改py文件后,不用再重启服务,可以加上 如下语句。注意这主要用来调试,不能用于生产环境。

app.debug = True

二、静态资源

可以在应用目录(如上面的myapp目录)下创建目录名为static的目录。

这样就可以把各种静态的资源(如 html, css, js,jpeg等)放在static目录下。

访问静态资源的方式如:

 http://192.168.142.138/static/资源名称

三、使用模板

所谓模板,就是在一个html文件中可以加上一些标识,由web引擎传入一些动态信息(来自html请求和服务器的处理),替换html文件中的标记,这样html页面就可以动态变化。在flask中,这样使用模板。举例如下:

1、在应用目录(如上面的myapp目录)下创建目录名为templates的目录。

2、创建 index.html文件放入templates目录下,文件内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <link rel="stylesheet" href="/static/demo.css"/>
</head>

<body>
    <div> hello</div>
</body>
</html>

这个例子html文件中全是静态信息,没有动态信息。上面文件引用了demo.css文件,位于static目录下(见下面说明)。


3、创建一个demo.css文件,放入应用目录(如上面的myapp目录)下的static目录下。这些静态资源(主要是js,css,图片等)可以被模板文件引用。如上面的index.html文件。demo.css的内容如:

div{
    border:1px solid red;
}

4、修改hello.py文件
在文件的前面引入render_template包,可以放在第2行,代码如:

from flask import render_template

增加路由代码

@app.route('/index/')
@app.route('/index/<name>')
def hello(name=None):
    return render_template('index.html', name=name)

上面的代码 render_template('index.html', name=name)  ,其中render_template方法第一个参数是模板文件,第二个参数是传入到模板中的信息(对上面例子没有意义)。传到模板中的name值可以是来源于url的部分。当然也可以是hello函数中处理的结果。

5、请求
在浏览器输入如

http://192.168.142.138:32768/index

http://192.168.142.138:32768/index/xxx

都会定位到index.html文件

6、动态模板

修改index.html的文件如下:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

访问:http://192.168.142.138:32768/index/
输出信息为:Hello World!

访问:http://192.168.142.138:32768/index/test

输出信息为:Hello test!

原文地址:https://www.cnblogs.com/51kata/p/5282998.html