初次使用flask

以写的一个小的例子来记录第一次使用:

from flask import Flask, render_template
import json

# 实例化,可视为固定格式
app = Flask(__name__)


# route()方法用于设定路由;类似spring路由配置
@app.route('/hello/bing')
def hello_world():
    nv = ["fengjie", "村头王大妈"]
    data = {}
    data['name'] = "Bing"
    data["justTryTry"] = "yes"
    data["girlsLike"] = nv
    return json.dumps(data, ensure_ascii=False)


@app.route('/hello/<name>')
def hello_world1(name):
    return "hello {}".format(name)


@app.route('/hello/yyy')
def hello_world2():
    nv = ["fengjie", "村头王大妈"]
    data = {}
    data['name'] = "Bing"
    data["justTryTry"] = "yes"
    data["girlsLike"] = nv
    return render_template('bing.html', data=data)


if __name__ == '__main__':
    host = "localhost"
    port = 8080
    app.run(host, port)
    # 默认值:host=127.0.0.1, port=5000, debug=false
    app.run()

1、路由(使用 route() 装饰器来把函数绑定到 URL):

@app.route('/hello/bing')

2、传递json数据

@app.route('/hello/bing')
def hello_world():
    nv = ["fengjie", "村头王大妈"]
    data = {}
    data['name'] = "Bing"
    data["justTryTry"] = "yes"
    data["girlsLike"] = nv
    return json.dumps(data, ensure_ascii=False)

字典与json间的转换

json.loads(json_str) json字符串转换成字典
json.dumps(dict) 字典转换成json字符串

为了传递过去的中文不出现乱码,在json.dumps增加参数(ensure_ascii=False

json.dumps(data, ensure_ascii=False)

3、变量规则(通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数):

@app.route('/hello/<name>')
def hello_world1(name):
    return "hello {}".format(name)

这时访问127.0.0.1:/8080/hello/xxx,则浏览器会返回内容hello xxx

 

4、渲染模板(在 Python 内部生成 HTML 不好玩,且相当笨拙。因为你必须自己负责 HTML 转义, 以确保应用的安全。因此, Flask 自动为你配置 Jinja2 模板引擎。

@app.route('/hello/yyy')
def hello_world2():
    nv = ["fengjie", "村头王大妈"]
    data = {}
    data['name'] = "Bing"
    data["justTryTry"] = "yes"
    data["girlsLike"] = nv
    return render_template('bing.html', data=data)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>女朋友</title>
</head>
<body>
    <table border = 1 align="center">
     {% for key, value in data.items() %}
        <tr>
            <td>{{key}}</td>
            <td>{{value}}</td>
        </tr>
   {% endfor %}
  </table>
</body>
</html>

使用 render_template() 方法可以渲染模板,你只要提供模板名称和需要 作为参数传递给模板的变量就行了,本例传递  字典data到bing.html,在html中取出传递过来的data数据并显示。

Flask 会在 templates 文件夹(bing.html放在改文件夹下)内寻找模板。因此,如果你的应用是一个模块, 那么模板文件夹应该在模块旁边;如果是一个包,那么就应该在包里面



原文地址:https://www.cnblogs.com/dong973711/p/11996917.html