Home Backend Development Python Tutorial Detailed explanation of HeaderDict of Bottle source code

Detailed explanation of HeaderDict of Bottle source code

Jul 24, 2017 am 09:20 AM
bottle Source code

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]
Copy after login

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:

  1. Convert value to list, optimize the data representation form

  2. 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'))
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Application practice of Python in software source code protection Application practice of Python in software source code protection Jun 29, 2023 am 11:20 AM

As a high-level programming language, Python language is easy to learn, easy to read and write, and has been widely used in the field of software development. However, due to the open source nature of Python, the source code is easily accessible to others, which brings some challenges to software source code protection. Therefore, in practical applications, we often need to take some methods to protect Python source code and ensure its security. In software source code protection, there are a variety of application practices for Python to choose from. Below are some common

How to view the source code of tomcat in idea How to view the source code of tomcat in idea Jan 25, 2024 pm 02:01 PM

Steps to view tomcat source code in IDEA: 1. Download Tomcat source code; 2. Import Tomcat source code in IDEA; 3. View Tomcat source code; 4. Understand the working principle of Tomcat; 5. Precautions; 6. Continuous learning and updating ; 7. Use tools and plug-ins; 8. Participate in the community and contribute. Detailed introduction: 1. Download the Tomcat source code. You can download the source code package from the official website of Apache Tomcat. Usually these source code packages are in ZIP or TAR format, etc.

How to display the source code of PHP code in the browser without being interpreted and executed? How to display the source code of PHP code in the browser without being interpreted and executed? Mar 11, 2024 am 10:54 AM

How to display the source code of PHP code in the browser without being interpreted and executed? PHP is a server-side scripting language commonly used to develop dynamic web pages. When a PHP file is requested on the server, the server interprets and executes the PHP code in it and sends the final HTML content to the browser for display. However, sometimes we want to display the source code of the PHP file directly in the browser instead of being executed. This article will introduce how to display the source code of PHP code in the browser without being interpreted and executed. In PHP, you can use

Python lightweight web framework: Bottle library! Python lightweight web framework: Bottle library! Apr 13, 2023 pm 02:10 PM

As lightweight as it is, the Bottle library is also very simple to use. I believe that before reading this article, readers already have a simple understanding of python. So what kind of mysterious operation can complete the functions of a server with hundreds of lines of code? let us wait and see. 1. Bottle library installation 1) Use pip to install 2) Download the Bottle file https://github.com/bottlepy/bottle/blob/master/bottle.py2. "HelloWorld!" As the saying goes, everything succeeds first HelloWorld, from this simple In the example, understand the basic mechanism of Bottle. Let’s start with the code: first we start with b

Website to view source code online Website to view source code online Jan 10, 2024 pm 03:31 PM

You can use the browser's developer tools to view the source code of the website. In the Google Chrome browser: 1. Open the Chrome browser and visit the website where you want to view the source code; 2. Right-click anywhere on the web page and select "Inspect" or press the shortcut key Ctrl + Shift + I to open the developer tools; 3. In the top menu bar of the developer tools, select the "Elements" tab; 4. Just see the HTML and CSS code of the website.

Can vue display source code? Can vue display source code? Jan 05, 2023 pm 03:17 PM

Vue can display the source code. The method for viewing the source code in Vue is: 1. Obtain Vue through "git clone https://github.com/vuejs/vue.git"; 2. Install dependencies through "npm i"; 3. Through " npm i -g rollup" to install rollup; 4. Modify the dev script; 5. Debug the source code.

PHP source code error: solving index error problem PHP source code error: solving index error problem Mar 10, 2024 am 11:12 AM

PHP source code error: To solve the index error problem, specific code examples are needed. With the rapid development of the Internet, developers often encounter various problems when writing websites and applications. Among them, PHP is a popular server-side scripting language, and its source code errors are one of the problems that developers often encounter. Sometimes, when we try to open the index page of a website, various error messages will appear, such as "InternalServerError", "Unde

A comprehensive guide to learning and applying golang framework source code A comprehensive guide to learning and applying golang framework source code Jun 01, 2024 pm 10:31 PM

By understanding the Golang framework source code, developers can master the essence of the language and expand the framework's functions. First, get the source code and become familiar with its directory structure. Second, read the code, trace the execution flow, and understand dependencies. Practical examples show how to apply this knowledge: create custom middleware and extend the routing system. Best practices include learning step-by-step, avoiding mindless copy-pasting, utilizing tools, and referring to online resources.

See all articles