当前位置: 首页 > news >正文

python使用Flask框架开发API

Flask是一个基于Python的轻量级Web应用程序框架。

安装依赖库

pip install flask
pip install werkzeug

上传接口

Python

from flask import Flask, request
from werkzeug.utils import secure_filenameapp = Flask(__name__)@app.route('/upload', methods=['POST'])
def upload_file():f = request.files['file']print(request.files)f.save("image/"+secure_filename(f.filename))return 'file uploaded successfully'if __name__ == '__main__':app.run(debug = True)

Html调用示例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head><body><form action = "http://localhost:5000/upload" method = "POST" enctype = "multipart/form-data"><input type = "file" name = "file" /><input type = "submit" value="提交"/></form></body>
</html>

下载接口

Python

from flask import Flask, send_file
import osapp = Flask(__name__)base_path = '/upload/image/'@app.route('/download/<string:filename>')
def download(filename):file_path = os.path.join(base_path, filename)return send_file(file_path, as_attachment=True)if __name__ == "__main__":app.run(debug = True)

图片查看接口

 Python

from flask import Flask, request, make_response
import osapp = Flask(__name__)base_path = "/upload/image/"@app.route('/image/<string:filename>', methods=['GET'])
def show_photo(filename):if request.method == 'GET':if filename is None:passelse:image_data = open(os.path.join(upload_path, '%s' % filename), "rb").read()response = make_response(image_data)response.headers['Content-Type'] = 'image/jpeg'return responseelse:passif __name__ == '__main__':app.run(debug = True)

Form表单请求接口

Python

from flask import Flask, requestapp = Flask(__name__)@app.route('/result',methods = ['POST'])
def result():result = request.formprint("name:", result["name"])print("code:", result["code"])return 'post form successfully'if __name__ == '__main__':app.run(debug = True)

Html调用示例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head><body><form action = "http://localhost:5000/result" method = "POST"><p>姓名 <input type = "text" name = "name" /></p><p>分数: <input type = "text" name = "code" /></p><p><input type = "submit" value = "提交" /></p></form></body>
</html>

JSON请求接口

Python

from flask import Flask, requestapp = Flask(__name__)@app.route('/result',methods=['POST'])
def result():params = request.get_json()print(params)return paramsif __name__ == '__main__':app.run(debug = True)

请求示例

curl -X POST -H 'Content-Type: application/json' -d '{"name":"abc","code":123}' http://127.0.0.1:5000/result

加载模板

Python

from flask import Flask, render_templateapp = Flask(__name__)@app.route('/hello')
def hello():return render_template(‘hello.html’)@app.route('/hello/<user>')
def hello_name(user):return render_template('hello2.html', name = user)if __name__ == '__main__':app.run(debug = True)

hello2.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask HTTP请求方法处理</title>
</head><body><h1>Hello {{ name }}!</h1></body>
</html>

 配置远程访问

app.run(host="0.0.0.0",port=5000)
# host (主机IP地址,可以不传)默认localhost
# port 端口号,可以不传,默认5000

跨域支持

from flask import Flask,jsonify
from flask_cors import CORS"""
pip install flask flask-cors
"""app = Flask(__name__)
CORS(app)@app.route('/index', methods=['POST','GET'])
def index():return jsonify('Start!')if __name__ == "__main__":app.run(host="0.0.0.0",port=8000)

http://www.lryc.cn/news/339009.html

相关文章:

  • 使用hexo+gitee从零搭建个人博客
  • 绝地求生:杜卡迪来了,这些摩托车技巧不学一下吗?
  • openstack安装dashboard后登录网页显示404错误
  • c# Xml 和 Json 转换方法记录
  • OpenHarmony南向开发案例:【智能垃圾桶】
  • 每日一题---OJ题: 旋转数组
  • 基于单链表的通讯录C语言实现
  • 【深度学习】YOLO-World: Real-Time Open-Vocabulary Object Detection,目标检测
  • debian安装和基本使用
  • nvm安装详细教程(安装nvm、node、npm、cnpm、yarn及环境变量配置)
  • 优优嗨聚集团:如何优雅地解决个人债务问题,一步步走向财务自由
  • SpringCloud实用篇(四)——Nacos
  • 【嵌入式基础知识学习】AD/DA—数模/模数转换
  • Swift中的结构体
  • Selenium - java - 屏幕截图
  • 【论文阅读——SplitFed: When Federated Learning Meets Split Learning】
  • Python使用方式介绍
  • 浅述python中NumPy包
  • jvm的面试回答
  • 打不动的蓝桥杯
  • 学习笔记——C语言基本概念文件——(13)
  • 【MySQL】事务篇
  • tsconfig.json文件常用配置
  • 【Linux】tcpdump P1 - 网络过滤选项
  • 网络篇04 | 应用层 mqtt(物联网)
  • Transformer模型-decoder解码器,target mask目标掩码的简明介绍
  • All in One:Prometheus 多实例数据统一管理最佳实践
  • mysql报错-mysql服务启动停止后,某些服务在未由其他服务或程序使用时将自动停止和数据恢复
  • Java开发从入门到精通(二十):Java的面向对象编程OOP:File文件操作的增删改查
  • 10.list的模拟实现(普通迭代器和const迭代器的类模板)