安装
pip install -U Flask
Successfully built itsdangerous MarkupSafe Installing collected packages: MarkupSafe, Jinja2, itsdangerous, Werkzeug, click, Flask Successfully installed Flask-1.0.2 Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7 itsdangerous-0.24
看起来都用了这几个包
MarkupSafe Jinja2 itsdangerous Werkzeug click Flask
是干啥的暂且不知道,接下来跟着官网第一个示例走你
from flask import Flask #创建了一个Flask的实例 app = Flask(__name__) @app.route('/') def hello(): return "hello world"
来看看route这个带参装饰器的实现
def route(self, rule, **options): def decorator(f): #key: 要删除的键/值对所对应的键 #default: 可选参数,给定键不在字典中时必须设置,否者会报错(没有默认值),此时返回default值 endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
add_url_rule的实现
@setupmethod def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options): """ :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.)""" if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint methods = options.pop('methods', None)
@app.route('/') def hello(): return "hello world" #就相当于 add_url_rule(rule='/',view_func=hello) #假如入我们把接受的请求方法改为get,应该就是这么写 #注意methods is a list of methods @app.route('/',methods=['GET']) def hello(): return "hello world" """ 不过有句注释这么说来着 By default a rulejust listens for ``GET`` 所以啊,这种情况下上面的method可以省略 那如果我想接收一个post请求呢 """ @app.route('/post',methods=['POST']) def post(): return "post method\n"
测试下
当然也可以走一个,既可以接受POST,又可以接受GET的请求.如下
@app.route('/double',methods=['POST','GET']) def double(): if request.method == 'POST': return 'post something' elif request.method == 'GET': return 'get something'
测试下