Flask 基础知识

发布于 2022-12-15 21:03:54 字数 7604 浏览 69 评论 0

安装 flask

pip install flask

Hello world

from flask import Flask 
app = Flask(__name__)

@app.route("/")
def index():
    return "Hello,World"
if __name__ == '__main__':
    app.run()

运行后,默认启动 5000 端口

路由与反向路由

路由

@app.route("/users/<id>", methods=["GET"])
def hello_user(id):
    return "Hello,User:{0}".format(id)

Methods 可以是 GET 或 POST;

反向路由 url_for

from flask import Flask, request, url_for
@app.route("/antiRoute/<funcName>")
def anti_route(funcName):
    request_id = request.args.get("request_id")
    # 对于hello_user,url_for需要加入其他参数,如values是id
    return "{0} url is: {1}".format(funcName, url_for(funcName))

模板

初识 render_template

render_template 用以实现模板的渲染,后台接口可以给模板传递参数,下面给出示例感受一下。

创建 templates 目录,在该目录下创建 index.html,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h1>{{content}}</h1>
</body>
</html>

实现 restful 接口,代码为:

@app.route("/")
def template_hello():
    content = "Hello,World!!!!"
    return render_template("index.html",content=content)

模板中以 {{ 变量名称 }} 的方式获取后台对象,这里的变量就是 content, render_template 方法中的参数定义为可变参数 **values,故而可以输入多个变量;

IF 语句

定义 User

class User(object):
    __slots__=('id', 'name')

    def __init__(self, id, name):
        self.id = id
        self.name = name

实现 restful 接口

@app.route("/user /<id>")
def show_user(id):
    if int(id) == 1:
        user = User(1,"Xiao Hong")
    else:
        user = None
    return render_template("user_info.html",user=user)

实现模板 user_info.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Info</title>
</head>
<body>
    {% if user %}
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>{{ user.id }}</td>
                <td>{{ user.name }}</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2">end</td>
            </tr>
        </tfoot>
    </table>
    {% else %}
    <h1> no user !!!</h1>
    {% endif %}
</body>
</html>

For 语句

@app.route("/users")
def show_users():
    users = []
    users.append(User(1,"xiao ming"))
    users.append(User(2, "xiao hong"))
    users.append(User(3, "xiao wang"))
    return render_template("user_list.html", users=users)

实现模板 user_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User List</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            {% for user in users %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                </tr>

            {% endfor %}
         </tbody>
        <tfoot>
            <tr>
                <td colspan="2">--------foot--------</td>
            </tr>
        </tfoot>
    </table>
</body>
</html>

模板的继承

我们可以设置母版,保持页面的头部或底部样式不变,如同 PPT 一样

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <h1>Header</h1>
    </div>
    <div>
        {% block content %}
        {% endblock %}
    </div>
    <div>
        <h1>Footer</h1>
    </div>
</body>
</html>

one.html

{% extends "base.html" %}
{% block content %}
    <h2>This is one.html</h2>
{% endblock %}
two.html
{% extends "base.html" %}
{% block content %}
    <h2>This is two.html</h2>
{% endblock %}
接口实现
@app.route("/one")
def one():
    return render_template("one.html")

@app.route("/two")
def two():
    return render_template("two.html")

消息提示

模板 msg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flash Demo</title>
</head>
<body>
    <h1> Flash Demo</h1>
    <h2>{{ get_flashed_messages()[0] }}</h2>
</body>
</html>

使用 get_flashed_messages() 获取 flash 闪存的消息内容,该方法返回的是一个数组

Restful 接口

from flask import flash
app.secret_key="ssss"
@app.route("/msg")
def msg():
    flash("I'm a message.")
    return render_template("msg.html")

在使用 flash 的时候需要配置 app.secret_key 用以给 flash 的消息内容加密

errorhandler

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>你要的页面去火星了</h1>
</body>
</html>

接口定义:

from flask import abort
@app.route("/error")
def abort_error():
    abort(404)

@app.errorhandler(404)
def not_found(e):
    return render_template("404.html")

Flask Web 开发

CGI 通用网关接口
Python Web 服务器
python 自带 web 服务器

web 服务器模块有以下三种:

  • SimpleHTTPServer: 包含执行 GET 和 HEAD 请求的 SimpleHTTPRequestHandler类。
  • BaseHTTPServer: 提供基本的Web服务和处理器类,分别是 HTTPServer和 aseHTTPRequestHandler。
  • CGIHTTPServer: 包含处理 POST 请求和执行 CGIHTTPRequestHandler 类

在 DOS 里进入服务器根目录的路径下,输入命令 python -m SimpleHTTPServer 8080 即可启动一个服务器,创建目录 cgi-bin 必须这个名字,在其中新建 main.py

#!/usr/bin/env python
# -*-coding:UTF-8-*-
# @Time: 2019/1/22 14:56
# @Author: en:zhu jin
# @File: main.py
# Description: None

print("Content-type:text/html \n\n")
print("Hello Web Development")

Cmd 定位到 cgi-bin 所在的目录,执行命令 python -m CGIHTTPServer 8080,输入地址 http://127.0.0.1:8080/cgi-bin/main.py 访问,返回结果如图:

引用 cgi 模块,获取链接参数

#!/usr/bin/env python
# -*-coding:UTF-8-*-
# @Time: 2019/1/22 15:10
# @Author: en:zhu jin
# @File: main.py
# Description: None

import cgi, cgitb

form1 = cgi.FieldStorage()
name=form1.getvalue("name")

print("Content-type:text/html \n\n")
if name:
    print("Hello, " + name)
else:
    print("Hello, CGI")

Python Web 框架

  • Django:文档多,全套的解决方案,强大的 URL 路由配置,自助管理后台;系统耦合高,自带的 ORM 不够强大,Template 比较弱;
  • Web.py
  • Tornado
  • Flask 微框架,自主选择模块,便于扩展;
  • Bottle 微框架

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

情绪少女

暂无简介

文章
评论
29 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文