标签:fun handle oldboyedu -- 配置 分析 default tac **kwargs
flask配置文件
如果不明白装饰器 点击这里
@app.route("/info", methods=["GET", "POST"])
def student_info():
    stu_id = int(request.args["id"])
    return f"Hello Old boy {stu_id}"  # Python3.6的新特性 f"{变量名}"
from flask import url_for
@app.route("/info", methods=["GET", "POST"], endpoint="r_info")
def student_info():
    print(url_for("r_info"))  # /info
    stu_id = int(request.args["id"])
    return f"Hello Old boy {stu_id}"  # Python3.6的新特性 f"{变量名}"
from flask import url_for
@app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
def student_info(nid):
    print(url_for("r_info"))  # /info
    # stu_id = int(request.args["id"])
    print(nid)  # 100
    return f"Hello Old boy {nid}"  # Python3.6的新特性 f"{变量名}"
# 访问地址 : /info 
@app.route("/info", strict_slashes=True)
def student_info():
    return "Hello Old boy info"
# 访问地址 : /infos  or  /infos/
@app.route("/infos", strict_slashes=False)
def student_infos():
    return "Hello Old boy infos"
# 访问地址 : /info 浏览器跳转至 /infos
@app.route("/info", strict_slashes=True, redirect_to="/infos")
def student_info():
    return "Hello Old boy info"
@app.route("/infos", strict_slashes=False)
def student_infos():
    return "Hello Old boy infos"
app.config["SERVER_NAME"] = "oldboy.com"
@app.route("/info",subdomain="DragonFire")
def student_info():
    return "Hello Old boy info"
# 访问地址为:  DragonFire.oldboy.com/info
关于路由目前就说这么多,之后的课程中会有关于Flask路由系统的源码剖析,再详细说明Flask路由系统的工作原理
from flask import url_for
# 访问地址 : http://127.0.0.1:5000/info/1
@app.route("/info/<int:nid>", methods=["GET", "POST"], endpoint="r_info")
def student_info(nid):
    print(url_for("r_info",nid=2))  # /info/2
    return f"Hello Old boy {nid}"  # Python3.6的新特性 f"{变量名}"
但是这种动态参数路由,在url_for的时候,一定要将动态参数名+参数值添加进去,否则会抛出参数错误的异常
一般不用,如果有特殊需求,不怕麻烦的话,这个东西还是挺好用的,前提是你的正则玩儿的很6
from flask import Flask, request, current_app
import importlib
app = Flask(__name__)
# 导入配置文件
app.config.from_object('settings.DevConfig')
# flask路由系统
@app.route('/')
def hello_world():
    return 'Hello World!'
    # 以 @app.route('/index', endpoint='index', methods=['GET']) 为例
    # 函数本质是是个闭包函数
    def route(self, rule, **options):
        # self 表示的app对象的实例
        # rule 表示路由  rule='/index'
        # **options 是其他参数  这里  endpoint='index', methods=['GET']
        def decorator(f):
            # 这里是获取 endpoint的值,如果不存在则为None
            endpoint = options.pop("endpoint", None)
            # 本质上是 执行  app.add_url_rule('/index',....)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator
    
"""
第一步 执行route 后返回 decorator
第二步 执行@decorator -->decorator(index)
"""    
    
@app.route('/index', endpoint='index', methods=['GET'])  
# 参数endpoint不写 默认为函数名,用户反向生成url
def index():
    print(current_app.config['DB'])
    return "xxx"
def login():
    return 'login'
# 这是另外一种路由方式,类似于django中的path('',views.....)
app.add_url_rule('/login', 'n2',login,methods=['GET', 'POST'])
if __name__ == '__main__':
    app.run()
def _endpoint_from_view_func(view_func):
    """
    Internal helper that returns the default endpoint for a given
    function.  This always is the function name.
    """
    assert view_func is not None, "expected view func if endpoint is not provided."
    # 如果 endpoint=None的时候,返回的是 默认的endpoint view_func的名字
    return view_func.__name__
from flask import Flask, request, current_app,views
import importlib
app = Flask(__name__)
app.config.from_object('settings.DevConfig')
# 装饰器
def auth(func):
    def inner(*args,**kwargs):
        result = func(*args,**kwargs)
        return result
    return inner
class IndexView(views.MethodView):
    methods = ['GET','POST']
    decorators =[auth,]
    
    def get(self):
        return 'index.get'
    
    def post(self):
        return 'index.post'
app.add_url_rule('/index',view_func=IndexView.as_view(name='index'))  # name=endpoint
if __name__ == '__main__':
    app.run()
class MethodView(with_metaclass(MethodViewType, View)):
    """A class-based view that dispatches request methods to the corresponding
    class methods. For example, if you implement a ``get`` method, it will be
    used to handle ``GET`` requests. ::
        class CounterAPI(MethodView):
            def get(self):
                return session.get('counter', 0)
            def post(self):
                session['counter'] = session.get('counter', 0) + 1
                return 'OK'
        app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
    """
    # 类似于django中的dispatch,视图类中分发不同请求说对应的方法
    def dispatch_request(self, *args, **kwargs):
        meth = getattr(self, request.method.lower(), None)
        # If the request method is HEAD and we don't have a handler for it
        # retry with GET.
        if meth is None and request.method == "HEAD":
            meth = getattr(self, "get", None)
        assert meth is not None, "Unimplemented method %r" % request.method
        return meth(*args, **kwargs)  
        # 如果是get请求,返回的是   get(*args,**kwargs)
windows:C:\Windows\System32\drivers\etc\hosts
mac:/etc/hosts
标签:fun handle oldboyedu -- 配置 分析 default tac **kwargs
原文地址:https://www.cnblogs.com/qianzhengkai/p/11380601.html