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-elcmacom8 小时前
深度学习<4>高效模型架构与优化器的“效率革命”
人工智能·python·深度学习·机器学习·架构
liliangcsdn9 小时前
python模拟beam search优化LLM输出过程
人工智能·python
王琦031810 小时前
Python 函数详解
开发语言·python
胡伯来了10 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…10 小时前
Python 中的多层继承
开发语言·python
中國移动丶移不动10 小时前
Python MySQL 数据库操作完整示例
数据库·python·mysql
落叶,听雪10 小时前
AI建站推荐
大数据·人工智能·python
ZAz_10 小时前
DAY 45 预训练模型
python
呆萌很11 小时前
python 项目迁移
python
清水白石00811 小时前
《requests vs httpx:Python 网络请求库的全面对比与实战指南》
网络·python·httpx