Flask基本用法:一个HelloWorld,搭建服务、发起请求

1、简介

Flask是一个轻量的web服务框架,我们可以利用它快速搭建一个服务,对外提供接口,其他人可以轻松调用我们的服务。这对算法工程师来说比较关键,我们通常不擅长搞开发,这种框架十分适合将算法封装成服务的形式提供给其他人使用。

更多介绍可从搜索引擎找到,这里不过多介绍。我们直接给出一个使用示例,相信大家看了后能快速掌握Flask的基本用法。

2、Flask使用示例

首先,编写一个server.py,作为服务:

python 复制代码
from flask import Flask, request

app = Flask("Demo")


@app.route('/hello', methods=['POST', 'GET'])
def display():
    return {"message": "HelloFlask!", "status": 0}


@app.route('/send_snapshot', methods=['POST'])
def process_snapshot():
    # get post data
    data = request.get_json()
    print("got post data: {}".format(data))

    # process
    ...

    result = {
        "status": 0,
        "message": "send success!",
    }
    return result


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

然后,编写一个client.py,作为客户端,调用上面的服务进行测试:

python 复制代码
import requests
import json


def demo_hello():
    url = "http://127.0.0.1:2023/hello"
    response = requests.post(url)

    if response.status_code == 200:
        response_data = json.loads(response.content)
        print("got response: {}".format(response_data))
    else:
        print("failed!")


def demo_send():
    url = "http://127.0.0.1:2023/send_snapshot"

    data = {
        "start_timestamp": 1,
        "end_timestamp": 2,
        "img": None
    }
    response = requests.post(url, json=data)

    if response.status_code == 200:
        response_data = json.loads(response.content)
        print("send over, got response: {}".format(response_data))
    else:
        print("send failed!")


if __name__ == '__main__':
    demo_hello()
    demo_send()

先启动server,再运行client,即可得到如下结果:

python 复制代码
1. 运行server
python server.py
结果形如:
 * Serving Flask app 'Demo'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:2023
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 887-814-515


2. 运行client.py
python client.py
结果形如:
got response: {'message': 'HelloFlask!', 'status': 0}
send over, got response: {'message': 'send success!', 'status': 0}

参考

官方文档:Welcome to Flask --- Flask Documentation (3.0.x)

github:GitHub - pallets/flask: The Python micro framework for building web applications.

相关推荐
BoBoZz1916 小时前
QuadraticHexahedronDemo 非线性单元的展示与窗口交互
python·vtk·图形渲染·图形处理
Q_Q196328847516 小时前
python+django/flask+vue的个性化电影推荐系统
spring boot·python·django·flask·node.js
BD_Marathon16 小时前
【Java】集合里面的数据结构
java·数据结构·python
Rinai_R16 小时前
Golang 垃圾回收器执行链路分析
开发语言·后端·golang
ULTRA??16 小时前
JPS路径规划(python AI实现)
开发语言·人工智能·python
古城小栈16 小时前
深入解析Go泛型中的~struct{}
开发语言·后端·golang
San30.16 小时前
从 Mobile First 到 AI First:用 Python 和大模型让数据库“开口说话”
数据库·人工智能·python
计算机学姐16 小时前
基于Python的旅游数据分析及可视化系统【2026最新】
vue.js·python·数据挖掘·数据分析·django·旅游·推荐算法
红队it16 小时前
【机器学习】python旅游数据分析可视化协同过滤算法推荐系统(完整系统源码+数据库+开发笔记+详细部署教程)✅
python·mysql·算法·机器学习·数据分析·旅游
曲幽16 小时前
Flask项目结构详解:用蓝图实现优雅的模块化开发
python·web·route·blueprint·register