All framework request responses are based on one principle http request --> wsgi server --> wsgi interface (actually the function implemented by a custom implementation in the framework is encapsulated at the bottom) --> response You can refer to the explanation of the wsgi interface in Liao Xuefeng's tutorial
class HeaderDict(dict):''' A dictionary with case insensitive (titled) keys. You may add a list of strings to send multible headers with the same name.'''def __setitem__(self, key, value):return dict.__setitem__(self,key.title(), value) #注意这里使用title函数,它能将每个单词的开头大写def __getitem__(self, key):return dict.__getitem__(self,key.title())def __delitem__(self, key):return dict.__delitem__(self,key.title())def __contains__(self, key):return dict.__contains__(self,key.title())def items(self):""" Returns a list of (key, value) tuples """for key, values in dict.items(self):if not isinstance(values, list): values = [values]for value in values:yield (key, str(value)) def add(self, key, value):""" Adds a new header without deleting old ones """if isinstance(value, list):for v in value:self.add(key, v) #注意这里使用了递归elif key in self:if isinstance(self[key], list):self[key].append(value)else:self[key] = [self[key], value]else: self[key] = [value]
HeaderDict encapsulates the dict and capitalizes the first letter of the word in the dictionary key. And turn value into an iterable object, and turn value into a list object, that is, value=[value]. The WSGI standard defines that a string type should be converted into a list type, which will give it a better representation. The server does not need to output all at once, but can use yield to control the output to avoid outputting too much at one time. All in all, this class that encapsulates dict implements two functions:
Convert value to list, optimize the data representation form
The first letter of the word in key is capitalized
def abort(code=500, text='Unknown Error: Appliction stopped.'):""" Aborts execution and causes a HTTP error. """raise HTTPError(code, text)def redirect(url, code=307):""" Aborts execution and causes a 307 redirect """response.status = code response.header['Location'] = urlraise BreakTheBottle("")def send_file(filename, root, guessmime = True, mimetype = 'text/plain'):""" Aborts execution and sends a static files as response. """root = os.path.abspath(root) + '/'filename = os.path.normpath(filename).strip('/') filename = os.path.join(root, filename)#判断文件是否可获得if not filename.startswith(root): #主目录下的文件不可以下载abort(401, "Access denied.")if not os.path.exists(filename) or not os.path.isfile(filename): abort(404, "File does not exist.")if not os.access(filename, os.R_OK): abort(401, "You do not have permission to access this file.")# 获得文件类型if guessmime: guess = mimetypes.guess_type(filename)[0]if guess: response.content_type = guesselif mimetype: response.content_type = mimetypeelif mimetype: response.content_type = mimetype#设置Content_typestats = os.stat(filename)# TODO: HTTP_IF_MODIFIED_SINCE -> 304 (Thu, 02 Jul 2009 23:16:31 CEST)if 'Content-Length' not in response.header: response.header['Content-Length'] = stats.st_sizeif 'Last-Modified' not in response.header: ts = time.gmtime(stats.st_mtime) ts = time.strftime("%a, %d %b %Y %H:%M:%S +0000", ts) response.header['Last-Modified'] = tsraise BreakTheBottle(open(filename, 'r'))
The three functions above implement internal server errors, redirection, and file download respectively. This function of file download implements the judgment of file type, setting of Content_type, judgment of file permissions, obtaining file status, etc. This function is still very simple and can be customized.
The above is the detailed content of Detailed explanation of HeaderDict of Bottle source code. For more information, please follow other related articles on the PHP Chinese website!

Python语言作为一种高级编程语言,具有简单易学、易读易写等特点,在软件开发领域中得到了广泛的应用。然而,由于Python的开源特性,源代码很容易被他人轻易获取,这就给软件源码保护带来了一些挑战。因此,在实际应用中,我们常常需要采取一些方法来保护Python源代码,确保其安全性。在软件源码保护中,有多种针对Python的应用实践可供选择。下面将介绍几种常见

idea查看tomcat源码的步骤:1、下载Tomcat源代码;2、在IDEA中导入Tomcat源代码;3、查看Tomcat源代码;4、理解Tomcat的工作原理;5、注意事项;6、持续学习和更新;7、使用工具和插件;8、参与社区和贡献。详细介绍:1、下载Tomcat源代码,可以从Apache Tomcat的官方网站上下载源代码包,通常这些源代码包是以ZIP或TAR格式等等。

PHP代码在浏览器中如何显示源码而不被解释执行?PHP是一种服务器端脚本语言,通常用于开发动态网页。当PHP文件在服务器上被请求时,服务器会解释执行其中的PHP代码,并将最终的HTML内容发送到浏览器以供显示。然而,有时我们希望在浏览器中直接展示PHP文件的源代码,而不是被执行。本文将介绍如何在浏览器中显示PHP代码的源码,而不被解释执行。在PHP中,可以使

和它本身的轻便一样,Bottle库的使用也十分简单。相信在看到本文前,读者对python也已经有了简单的了解。那么究竟何种神秘的操作,才能用百行代码完成一个服务器的功能?让我们拭目以待。1. Bottle库安装1)使用pip安装2)下载Bottle文件https://github.com/bottlepy/bottle/blob/master/bottle.py2.“HelloWorld!”所谓万事功成先HelloWorld,从这个简单的示例中,了解Bottle的基本机制。先上代码:首先我们从b

可以使用浏览器的开发者工具来查看网站的源代码,在Google Chrome浏览器中:1、打开 Chrome 浏览器,访问要查看源代码的网站;2、右键单击网页上的任何位置,然后选择“检查”或按下快捷键 Ctrl + Shift + I打开开发者工具;3、在开发者工具的顶部菜单栏中,选择“Elements”选项卡;4、看到网站的 HTML 和 CSS 代码即可。

vue能显示源码,vue查看看源码的方法是:1、通过“git clone https://github.com/vuejs/vue.git”获取vue;2、通过“npm i”安装依赖;3、通过“npm i -g rollup”安装rollup;4、修改dev脚本;5、调试源码即可。

PHP源码错误:解决index报错问题,需要具体代码示例随着互联网的快速发展,开发人员在编写网站和应用程序时经常会遇到各种各样的问题。其中,PHP作为一种流行的服务器端脚本语言,其源码错误是开发者们经常遇到的一个问题之一。有时候,当我们尝试打开一个网站的index页面时,会出现各种不同的错误信息,例如"InternalServerError"、"Unde

通过理解Golang框架源码,开发者可以掌握语言精髓和扩展框架功能。首先,获取源码并熟悉其目录结构。其次,阅读代码、跟踪执行流和理解依赖关系。实战案例展示了如何应用这些知识:创建自定义中间件并扩展路由系统。最佳实践包括分步学习、避免盲目复制粘贴、利用工具和参考在线资源。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
