先安装flask,之后运行如下代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "hello world"
if __name__=='__main__':
app.run()
浏览器输入:
127.0.0.1:5000
非常简单的一个web项目,就运行起来了。
完整restful示例:
from flask import Flask, jsonify, request, make_response, abort
app = Flask(__name__)
MY_URL = '/everything/api/v1/'
hello = '今天天气真好呀'
not_hello = '为什么今天天气不好呀'
@app.route(MY_URL + 'tasks/get/', methods=['GET'])
def get_task():
print(request.args.to_dict()) # request.args请求参数
return str(request.args.to_dict())
# get
@app.route(MY_URL + 'tasks/get/404/', methods=['GET'])
def get_task_get():
if not 'abc' in request.args.to_dict():
abort(404)
print(request.args.to_dict())
return str(request.args.to_dict())
# post
@app.route(MY_URL + 'tasks/post/', methods=['POST'])
def post_task():
print(request.json)
if not request.json:
abort(404)
print('222222222')
global hello
hello = hello + str(request.json)
return hello
# post
@app.route(MY_URL + 'tasks/post/json/', methods=['POST'])
def post_task_json():
print(request.json)
if not request.json:
abort(404)
print('222222222')
global hello
hello = hello + str(request.json)
print(hello)
return jsonify(request.json)
# 404处理
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
app.run()
游览器输入:
https://127.0.0.1:5000/everything/api/v1/tasks/get/?abc=hello
https://127.0.0.1:5000/everything/api/v1/tasks/get/404/?abc=hello
.....
post的就不列了,自己测试