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')
相关推荐
好家伙VCC16 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
前端玖耀里17 小时前
如何使用python的boto库和SES发送电子邮件?
python
serve the people17 小时前
python环境搭建 (十二) pydantic和pydantic-settings类型验证与解析
java·网络·python
小天源17 小时前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
喵手17 小时前
Python爬虫实战:HTTP缓存系统深度实战 — ETag、Last-Modified与requests-cache完全指南(附SQLite持久化存储)!
爬虫·python·爬虫实战·http缓存·etag·零基础python爬虫教学·requests-cache
喵手17 小时前
Python爬虫实战:容器化与定时调度实战 - Docker + Cron + 日志轮转 + 失败重试完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·容器化·零基础python爬虫教学·csv导出·定时调度
2601_9491465318 小时前
Python语音通知接口接入教程:开发者快速集成AI语音API的脚本实现
人工智能·python·语音识别
寻梦csdn18 小时前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
Java面试题总结19 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒19 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr