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')
相关推荐
千里码aicood7 分钟前
flask基于数字人的储粮知识问答原型系统研究与实现
后端·python·flask
E_ICEBLUE14 分钟前
Python 实现 Markdown 转 Word、PDF:从转换到页面设置
python·pdf·word·markdown·格式转换
哒咩哒咩12917 分钟前
Agent 智能体开发全攻略:从 ReAct 到企业级架构
python·langchain·fastapi
H愚公移山H25 分钟前
Tengine2.4.1 + OpenSSL1.1.1w 全平台编译踩坑手册(CentOS7 x86_64|Linux x64|ARM64|2026实战复盘)
python
码云骑士36 分钟前
120-视频理解-大模型视频分析-抽帧-自动字幕摘要-高光片段
python·音视频
xfan_me42 分钟前
手机在网状态接口-空号查询-空号过滤API
数据库·人工智能·python·智能手机
测试秃头怪1 小时前
Postman中变量的使用
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
ynchyong1 小时前
词云(Word Cloud) 使用方法
python·统计·词云
Alkaid20771 小时前
我把文件和脚本放一起了,Python 就是看不见?新手必看的绝对路径 vs 相对路径终极避坑指南
python·ai编程
SamChan901 小时前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf