flask探索-1

  1. 安装

    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的请求

    当然也可以走一个,既可以接受POST,又可以接受GET的请求.如下

    @app.route('/double',methods=['POST','GET'])
    def double():
        if request.method == 'POST':
            return 'post something'
        elif request.method == 'GET':
            return 'get something'

    测试下
    这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值