做一个API吧
创建app.py
from flask import Blueprint
from flask_restful import Api
from resource import Hello
api_bp = Blueprint(‘api‘, __name__)
api = Api(api_bp)
# Route
api.add_resource(Hello, ‘/Hello‘)
在resource.py中响应请求
from flask_restful import Resource
class Hello(Resource):
def get(self):
return {"message": "Hello, World!"}
def post(self):
return {"message": "Hello, World!"}
简单配置一下config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
最后,run.py
from flask import Flask
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(config_filename)
from app import api_bp
app.register_blueprint(api_bp, url_prefix=‘/api‘)
return app
if __name__ == ‘__main__‘:
app = create_app(‘config‘)
app.run(debug=True)
启动服务
$ python3 run.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 136-695-873
最后curl
一下就行了
$ curl http://127.0.0.1:5000/api/Hello
{
"message": "Hello, World!"
}
期末了,希望??能过
最后念一句:api大法好