学习httpbin源代码记录(二)

来源:互联网 发布:java中service的作用 编辑:程序博客网 时间:2024/05/20 12:22

httpbin源码中关于重定向的实现:


@app.route('/redirect-to', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'TRACE'])def redirect_to():    """302/3XX Redirects to the given URL."""    args = CaseInsensitiveDict(request.args.items())    # We need to build the response manually and convert to UTF-8 to prevent    # werkzeug from "fixing" the URL. This endpoint should set the Location    # header to the exact string supplied.    response = app.make_response('')    response.status_code = 302    if 'status_code' in args:        status_code = int(args['status_code'])        if status_code >= 300 and status_code < 400:            response.status_code = status_code    response.headers['Location'] = args['url'].encode('utf-8')    return response
这里主要涉及以下几点:

(1)request对象;

(2)args 这个内容已经在上一篇中讲解


(3)最重要的就是对response中的headers的Location进行设置

在flask框架中,每一个请求发送到服务器端,请求的所有相关信息都是保存在request中,

request.args就是其中的一个;

然后使用类CaseInsensitiveDict构造一个对象args,并使用request.args作为参数传入;

最后就是使用headers的Location设置目标url;


这里我有一个想法,如果能够很方便的将httpbin中的一段代码复制出来,单独调试,岂不是能够帮助我们快速的学习

只是我暂时没有想到切实可行的方法,也仅仅是修改源代码,添加一个log功能,然后运行能够httpbin;


这样真的是不太方便啊,大家有什么建议没?





原创粉丝点击