python+flask学习

最近做项目需要将本地py代码包装成接口给别人调用,浅浅学习一下flask的用法

一、不同的请求方式

1.发送一个不带参数的get请求

2.发送一个不带参数的post请求

3.返回json格式数据

  1. get带参数

5.post带参数

6.携带参数

参数可以设置的类型

7.json格式信息获取

二、其他设备访问

当修改host为0.0.0.0时,接入到同一个局域网的设备都可以进行访问

三、页面重定向

代码

python 复制代码
from flask import Flask, render_template, request, redirect,jsonify, make_response

# 把flask类创建成app对象
app = Flask(__name__)


@app.route('/postText', methods=['POST'])
def postText():
    return "post Text: 这是获取到的文本信息"


@app.route('/jsonText', methods=['GET'])
def getJsonText():
    name = 'this is name'
    age = 'this is age'
    return jsonify({'name': name, 'age': age})

@app.route('/getByParams', methods=['GET'])
def getByParams():
    if request.method == 'GET':
        name = request.args.get('name')
        age = request.args.get('age')
        return jsonify({'name': name, 'age': age})
    else:
        return "请检查请求方式"

@app.route('/postByParams', methods=['POST'])
def postByParams():
    if request.method == 'POST':
        name = request.form.get('name')
        age = request.form.get('age')
        return jsonify({'name': name, 'age': age})
    else:
        return "请检查请求方式"


@app.route('/getText', methods=['GET'])
def getText():
    return "get Text: 这是获取到的文本信息"

@app.route('/postmsg/<int:age>', methods=['POST'])
def postmsg(age):
    newage = age *2
    return f"我的年龄是{age},{newage}"

@app.route('/csdn')
def csdn():
    return redirect("https://www.csdn.net/")

@app.route('/json', methods=['POST'])
def getJson():
    text = request.get_json()
    return text

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
相关推荐
峥嵘life9 小时前
Android 蓝牙设备连接广播详解-2026
android·python·学习
郝学胜-神的一滴10 小时前
干货版《算法导论》07:递归视角下的选择排序与归并排序
java·数据结构·c++·python·程序人生·算法·排序算法
shehuiyuelaiyuehao10 小时前
多线程入门
java·python·算法
Oo92010 小时前
Prompt工程核心与Python 字典
python·ai编程
feeday11 小时前
gpt4o 图像反推提示词
开发语言·人工智能·python
沈浩(种子思维作者)11 小时前
没有错误,正确将一文不值
人工智能·python·算法·量子计算
smith成长之旅11 小时前
06 | Mem0 框架分析:为什么要从记忆中提取实体?——Entity Store 的设计动机与工程实现
人工智能·python
smith成长之旅11 小时前
07 | Mem0 框架分析:三路信号融合——语义 + BM25 + Entity Boost 的混合检索
python·算法
荣码12 小时前
【Python知识详解】变量与数据类型:深入理解 Python 的数据世界
python
春日见12 小时前
五分钟入门 强化学习---Q-Learning算法与实现
人工智能·python·深度学习·算法·机器学习·计算机视觉