python使用Flask框架开发API

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

安装依赖库

pip install flask
pip install werkzeug

上传接口

Python

from flask import Flask, request
from werkzeug.utils import secure_filename

app = 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 os
 
app = 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 os

app = 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:
            pass
        else:
            image_data = open(os.path.join(upload_path, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/jpeg'
            return response
    else:
        pass

if __name__ == '__main__':
    app.run(debug = True)

Form表单请求接口

Python

from flask import Flask, request

app = Flask(__name__)

@app.route('/result',methods = ['POST'])
def result():
    result = request.form
    print("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, request

app = Flask(__name__)

@app.route('/result',methods=['POST'])
def result():
    params = request.get_json()
    print(params)
    return params

if __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_template

app = 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值