使用 Flask 2.0 开发 Web API

2022-01-09 19:23:43   Cyberbolt

文章发布时刻李辉老师的 APIFlask 还在测试阶段,这里记录我使用原生 Flask 开发 Web API 的方案,并记录本项目的目录结构。APIFlask 完成后,我的工作环境将迁移至此。

未来是 微服务 和 云原生 的时代,传统后端渲染正逐渐被 Web API 替代,传统的中心服务器网站也逐步转为以 Go / Python 为主的云原生应用,容器技术发展势不可挡。本文主要研究使用 Flask 来开发 JSON API,如需了解 Docker 部署 Flask 程序的方案,请点击此处

运行环境:Python 3.8.6, Flask 2.0.2

 

下面简要记录 Flask 2.0 配置静态页面 和 JSON API 的方法

示例项目的目录结构

app.py 该项目的入口模块(使用 python app.py 即可运行程序)

route.py 保存该项目所有页面 (HTML) 的映射路径

static 静态文件的起始目录

static/index.html 测试页面

blueprints 蓝图模块

blueprints/__init__.py 蓝图模块的构造文件

blueprints/front.py 保存网站前台的所有 API

 

源码展示

app.py

from route import app


if __name__ == '__main__':
    app.run(host='127.0.0.1', port='5000', debug=True)

 

route.py

'''
    该模块存放本站所有页面路径
'''
from flask import Flask

from blueprints import front


def creat_app():
    app = Flask(
        __name__,
        static_folder='static',  # 静态文件的目录
        static_url_path='',  # 静态文件目录在链接的起始位置 
    )
    app.register_blueprint(front) #导入home蓝本
    return app


app = creat_app()


@app.route('/')
def home():
    return app.send_static_file('index.html')

static_folder 和 static_url_path 参数将静态文件根目录 /static 替换为 / 。如,默认设置中 index.html 的地址为 127.0.0.1:5000/static/index.html ,此设置地址改为了 127.0.0.1:5000/index.html 或 127.0.0.1:5000 (访问其一均可到达该页面)

 

static/index.html

<!doctype html>
<html lang="zh-CN">
  <head>
    <!-- 必须的 meta 标签 -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap 的 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- JavaScript 文件是可选的。从以下两种建议中选择一个即可! -->

    <!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>

    <!-- 选项 2:Popper 和 Bootstrap 的 JS 插件各自独立 -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
    -->
  </body>
</html>

访问效果

 

blueprints/__init__.py

from blueprints.front import front

 

blueprints/front.py

'''
    保存网站前台 API
'''
from flask import Flask, Blueprint, jsonify

#蓝图配置
front = Blueprint(
    'front', 
    __name__
)


@front.get('/api/test')
def test():
    return jsonify({
        'code': 1,
        'content': 'api test'
    })

Flask 蓝图配置,该模块存放 front 前台的所有 API,此处加入 Flask 2.0 语法,GET 方法 和 POST 方法配置更为便捷。/api/test 的数据交互格式为 JSON,这里用到 jsonify 将字典转为 JSON。

访问效果

 

配置完成!感谢您的阅读

Milton
2022-03-23 02:54:06

It is with sad regret to inform you DataList.biz is shutting down on 25 March 2022. We have made available databases per country for all companies available.. You can view our samples and download databases instantly on our website DataList.biz


Marian
2022-03-31 15:24:27

回复 Milton: It is with sad regret to inform you that BusinessLeads101.com is shutting down. We have over 300 million records available for a one time fee of $149. Please visit our website BusinessLeads101.com Regards, Marian

Wilson
2022-04-13 00:55:03

回复 Marian: Hello. We are offering Bullet Proof SMTP servers that never get suspended. Email as much as you want. DMCA ignored, bulletproof locations, 100% uptime guaranteed, unlimited data transfer, and 24/7/365 support. 100 Spots available. BulletProofSMTP.org

Leland
2022-04-20 01:45:51

回复 Wilson: Hello. It is with sad regret to inform you TopDataList.com is shutting down. We have made all our databases available for you for a once off fee. Visit us on TopDataList.com

Rick
2022-05-06 19:19:03

回复 Leland: Hello, from CustomData.click we are a provider of unique databases that could help your business. Please visit us at CustomData.click to see if we can help you. Regards, Rick

Jim
2022-05-18 00:07:19

回复 Rick: Hi, my name is Jim from TopDataList.com We are ceasing operations on TopDataList.com and have made our leads available at a discounted price. Visit us on TopDataList.com Regards, Jim

Zita
2022-06-23 02:10:16

回复 Jim: Hello, did you know that there are 241,120 internet directories in the world. These websites are what drive traffic to YOUR business. Want more traffic? Want more Sales? We can help - today. Your website cyberlight.xyz is listed in only 96 of these directories. Get more traffic for your Global audience. Our automated system adds your website to all of the directories. You can find it here: getlisted.directory/cyberlight.xyz Act today, and we will expedite your listings and waive the processing charge!

Kristina
2022-07-06 09:22:55

回复 Zita: Convert cyberlight.xyz to an app with one click! 80% of users browse websites from their phones. Have the App send out push notifications without any extra marketing costs! MakeMySiteMobile.com

Lacey
2022-07-12 19:55:54

回复 Kristina: Hello, did you know that there are 241,120 internet directories in the world. These websites are what drive traffic to YOUR business. Want more traffic? Want more Sales? We can help - today. Your website cyberlight.xyz is listed in only 96 of these directories. Get more traffic for your Global audience. Our automated system adds your website to all of the directories. You can find it here: getlisted.directory/cyberlight.xyz Act today, and we will expedite your listings and waive the processing charge! We have a special going on. Use "FRIENDS" on checkout for a 50% discount valid today.