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')
相关推荐
free-elcmacom39 分钟前
机器学习入门<2>决策树算法
人工智能·python·机器学习
Blossom.11841 分钟前
基于多智能体协作的AIGC内容风控系统:从单点检测到可解释裁决链
人工智能·python·深度学习·机器学习·设计模式·aigc·transformer
曲幽1 小时前
Flask项目目录结构指南:从单文件到模块化
python·web·model·route·项目结构
名字不相符1 小时前
[NCTF 2018]flask真香(个人记录,思路分析,学习知识,相关工具)
python·学习·flask·ctf
闲人编程1 小时前
Flask蓝图系统:模块化应用架构设计
后端·python·flask·api·蓝图·应用工厂·codecapsul
WebGISer_白茶乌龙桃1 小时前
PyroSAR 安装后出现 “No module named _gdal_array”
python
小小测试开发1 小时前
FastAPI 完全入门指南:从环境搭建到实战部署
python·fastapi
(●—●)橘子……1 小时前
力扣344.反转字符串 练习理解
python·学习·算法·leetcode·职场和发展
本妖精不是妖精1 小时前
在 CentOS 7 上部署 Node.js 18 + Claude Code
linux·python·centos·node.js·claudecode