当前位置:   article > 正文

python使用Flask框架开发API

python使用Flask框架开发API

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

安装依赖库

  1. pip install flask
  2. pip install werkzeug

上传接口

Python

  1. from flask import Flask, request
  2. from werkzeug.utils import secure_filename
  3. app = Flask(__name__)
  4. @app.route('/upload', methods=['POST'])
  5. def upload_file():
  6. f = request.files['file']
  7. print(request.files)
  8. f.save("image/"+secure_filename(f.filename))
  9. return 'file uploaded successfully'
  10. if __name__ == '__main__':
  11. app.run(debug = True)

Html调用示例

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Flask示例</title>
  5. </head>
  6. <body>
  7. <form action = "http://localhost:5000/upload" method = "POST"
  8. enctype = "multipart/form-data">
  9. <input type = "file" name = "file" />
  10. <input type = "submit" value="提交"/>
  11. </form>
  12. </body>
  13. </html>

下载接口

Python

  1. from flask import Flask, send_file
  2. import os
  3. app = Flask(__name__)
  4. base_path = '/upload/image/'
  5. @app.route('/download/<string:filename>')
  6. def download(filename):
  7. file_path = os.path.join(base_path, filename)
  8. return send_file(file_path, as_attachment=True)
  9. if __name__ == "__main__":
  10. app.run(debug = True)

图片查看接口

 Python

  1. from flask import Flask, request, make_response
  2. import os
  3. app = Flask(__name__)
  4. base_path = "/upload/image/"
  5. @app.route('/image/<string:filename>', methods=['GET'])
  6. def show_photo(filename):
  7. if request.method == 'GET':
  8. if filename is None:
  9. pass
  10. else:
  11. image_data = open(os.path.join(upload_path, '%s' % filename), "rb").read()
  12. response = make_response(image_data)
  13. response.headers['Content-Type'] = 'image/jpeg'
  14. return response
  15. else:
  16. pass
  17. if __name__ == '__main__':
  18. app.run(debug = True)

Form表单请求接口

Python

  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route('/result',methods = ['POST'])
  4. def result():
  5. result = request.form
  6. print("name:", result["name"])
  7. print("code:", result["code"])
  8. return 'post form successfully'
  9. if __name__ == '__main__':
  10. app.run(debug = True)

Html调用示例

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Flask示例</title>
  5. </head>
  6. <body>
  7. <form action = "http://localhost:5000/result" method = "POST">
  8. <p>姓名 <input type = "text" name = "name" /></p>
  9. <p>分数: <input type = "text" name = "code" /></p>
  10. <p><input type = "submit" value = "提交" /></p>
  11. </form>
  12. </body>
  13. </html>

JSON请求接口

Python

  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. @app.route('/result',methods=['POST'])
  4. def result():
  5. params = request.get_json()
  6. print(params)
  7. return params
  8. if __name__ == '__main__':
  9. 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

  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. @app.route('/hello')
  4. def hello():
  5. return render_template(‘hello.html’)
  6. @app.route('/hello/<user>')
  7. def hello_name(user):
  8. return render_template('hello2.html', name = user)
  9. if __name__ == '__main__':
  10. app.run(debug = True)

hello2.html

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Flask HTTP请求方法处理</title>
  5. </head>
  6. <body>
  7. <h1>Hello {{ name }}!</h1>
  8. </body>
  9. </html>

 配置远程访问

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

跨域支持

  1. from flask import Flask,jsonify
  2. from flask_cors import CORS
  3. """
  4. pip install flask flask-cors
  5. """
  6. app = Flask(__name__)
  7. CORS(app)
  8. @app.route('/index', methods=['POST','GET'])
  9. def index():
  10. return jsonify('Start!')
  11. if __name__ == "__main__":
  12. app.run(host="0.0.0.0",port=8000)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/411946
推荐阅读
相关标签
  

闽ICP备14008679号