search
HomeBackend DevelopmentPython TutorialBottle source code reading notes (1): WSGI
Bottle source code reading notes (1): WSGIJun 23, 2017 pm 03:06 PM
bottleSource codenotesread

Preface

Bottle is a Python web framework. The entire framework has only one file, less than 4k lines of code, and no dependencies other than the Python standard library. However, it includes common functions of web frameworks such as routing, templates, and plug-ins. There is no better time than reading the Bottle source code to understand what a web framework is and how it works. Since Bottle is a framework that supports WSGI, before reading the source code, let's first understand what WSGI is.

Note: The Bottle version used in this article is 0.12.13.

WSGI

##General web servers can only handle static pages. If dynamic content is involved, the server needs to interact with server languages ​​such as Java/Python/Ruby and hand over the content to them for processing. Since most web servers are written in C, they cannot directly execute the server language, so a bridge is needed between the two (in practical applications, an application server is usually added between the web server and the WSGI application to support WSGI) . In Python, WSGI is such a bridge. The implementation of WSGI is divided into two parts, one is the server and the other is the application. Let’s take a look at what each of them looks like and how the two work together.

 1 class Server: 2  3     def __init__(self, server_address): 4         self.server_address = server_address 5  6     def set_app(self, application): 7         self.app = application 8  9     def serve_forever(self):10         while True:11             # socket.accept()12             if request_comein():13                 self.handle_request()14 15     def handle_request(self):16         request_data = self.get_request()17         self.parse_request(request_data)18         environ = self.get_environ()19         result = self.application(environ, self.start_response)20         self.send_response(result)21 22     def start_response(self, status, headers, exc_info):23         pass24 25     def get_environ(self):26         pass27 28     def get_request(self):29         pass30 31     def parse_request(self, text):32         pass33 34     def send_response(self, message):35         pass36 37 38 def make_server(host, port, app, server=Server):39     server = server((host, port))40     server.set_app(app)41     return server42 43 def simple_app(environ, start_response):44     status = '200 OK'45     response_headers = [('Content-type', 'text/plain')]46     start_response(status, response_headers)47     return 'Hello World!'48 49 if __name__ == '__main__':50     server = make_server('localhost', 8080, simple_app)51     server.serve_forever()

Due to space limitations, this server model omits many details. If you want a simple and operational WSGI server, you can refer to Let's Build A Web here Server.Part 2.

After receiving the request, the server parses the information in the request message and saves the result in a dictionary named environ. Then the application application (environ, start_response) is called with environ and the start_response function that processes header information as parameters. Finally, the results of the application are composed into a new response and sent back to the client.

On the application side, a WSGI application is a callable object. It can be a function, method, class, or an instance with a __call__ method. The above application is a function.

When various servers and applications/frameworks are developed in accordance with WSGI standards, we can freely combine different servers and frameworks according to our needs.

Bottle's simplest application

After briefly understanding WSGI, we return to Bottle to observe what a Bottle application looks like, how to run it, and how to follow our What is the difference between models.

1 from bottle import Bottle, run2 3 app = Bottle()4 5 @app.route('/hello')6 def hello():7     return 'Hello World!'8 9 run(app, host='localhost', port=8080, server='wsgiref')

Now run this program and use the browser to access the address 'localhost:8080/hello' and you will see 'Hello World!'.

#1. Unlike the above applications, the Bottle application is an instance. According to WSGI regulations, the Bottle object must implement the __call__ method:

1 def __call__(self, environ, start_response):2     ''' Each instance of :class:'Bottle' is a WSGI application. '''3     return self.wsgi(environ, start_response)

So this Bottle.wsgi method is the entrance for the server to call the Bottle application, and it is also the entrance for us to read Entry to the source code.

2. @app.route() This decorator binds a function to a URL. When we access 'localhost:8080/hello', the hello function will be called.

3. Bottle's default server is wsgiref (a simple implementation of WSGI in the Python standard library). Of course, Bottle has also written adapters for many servers. You only need to change the value of server, and the run() function will find the corresponding adapter based on the name of the server. No need to write additional code.

run function and adapter part code:

 1 def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, 2         interval=1, reloader=False, quiet=False, plugins=None, 3         debug=None, **kargs): 4     if server in server_names: 5         server = server_names.get(server) 6     if isinstance(server, basestring): 7         server = load(server) 8     if isinstance(server, type): 9         server = server(host=host, port=port, **kargs)10     if not isinstance(server, ServerAdapter):11         raise ValueError("Unknown or unsupported server: %r" % server)12     ...13     server.run(app)14 15 class MeinheldServer(ServerAdapter):16     def run(self, handler):17         from meinheld import server18         server.listen((self.host, self.port))19         server.run(handler)
Finally

In this article, we A brief introduction to how servers and applications interact under the WSGI standard. In the next article, we will continue to focus on this simplest application and talk about the routing functions related to @app.route().

The above is the detailed content of Bottle source code reading notes (1): WSGI. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
小红书笔记怎么删除小红书笔记怎么删除Mar 21, 2024 pm 08:12 PM

小红书笔记怎么删除?在小红书APP中是可以编辑笔记的,多数的用户不知道小红书笔记如何的删除,接下来就是小编为用户带来的小红书笔记删除方法图文教程,感兴趣的用户快来一起看看吧!小红书使用教程小红书笔记怎么删除1、首先打开小红书APP进入到主页面,选择右下角【我】进入到专区;2、之后在我的专区,点击下图所示的笔记页面,选择要删除的笔记;3、进入到笔记页面,右上角【三个点】;4、最后下方会展开功能栏,点击【删除】即可完成。

小红书删除的笔记能恢复吗小红书删除的笔记能恢复吗Oct 31, 2023 pm 05:36 PM

小红书删除的笔记不能恢复。小红书作为一款知识分享和购物平台,为用户提供了记录笔记和收藏有用信息的功能。根据小红书的官方说明,已经删除的笔记是无法恢复的。小红书平台并没有提供专门的笔记恢复功能。这意味着,一旦在小红书中删除了笔记,无论是不小心误删还是其他原因,一般情况下是无法从平台上找回被删除的内容的。如果遇到特殊情况,可以尝试联系小红书的客服团队,看是否能够协助解决问题。

小红书发布过的笔记不见了怎么办?它刚发的笔记搜不到的原因是什么?小红书发布过的笔记不见了怎么办?它刚发的笔记搜不到的原因是什么?Mar 21, 2024 pm 09:30 PM

作为一名小红书的用户,我们都曾遇到过发布过的笔记突然不见了的情况,这无疑让人感到困惑和担忧。在这种情况下,我们该怎么办呢?本文将围绕“小红书发布过的笔记不见了怎么办”这一主题,为你详细解答。一、小红书发布过的笔记不见了怎么办?首先,不要惊慌。如果你发现笔记不见了,保持冷静是关键,不要慌张。这可能是由于平台系统故障或操作失误引起的。检查发布记录很简单。只需打开小红书App,点击“我”→“发布”→“所有发布”,就可以查看自己的发布记录。在这里,你可以轻松找到之前发布的笔记。3.重新发布。如果找到了之

如何在最新的iOS 17系统中连接iPhone上的Apple Notes如何在最新的iOS 17系统中连接iPhone上的Apple NotesSep 22, 2023 pm 05:01 PM

使用添加链接功能在iPhone上链接AppleNotes。笔记:如果您已安装iOS17,则只能在iPhone上的AppleNotes之间创建链接。在iPhone上打开“备忘录”应用。现在,打开要在其中添加链接的注释。您还可以选择创建新备忘录。点击屏幕上的任意位置。这将向您显示一个菜单。点击右侧的箭头以查看“添加链接”选项。点击它。现在,您可以键入注释的名称或网页URL。然后,点击右上角的完成,添加的链接将出现在笔记中。如果要添加指向某个单词的链接,只需双击该单词即可将其选中,选择“添加链接”并按

小红书怎么在笔记中添加商品链接 小红书在笔记中添加商品链接教程小红书怎么在笔记中添加商品链接 小红书在笔记中添加商品链接教程Mar 12, 2024 am 10:40 AM

  小红书怎么在笔记中添加商品链接?在小红书这款app中用户不仅可以浏览各种内容还可以进行购物,所以这款app中关于购物推荐、好物分享的内容是非常多的,如果小伙伴在这款app也是一个达人的话,也可以分享一些购物经验,找到商家进行合作,在笔记中添加连接之类的,很多人都愿意使用这款app购物,因为不仅方便,而且有很多达人会进行一些推荐,可以一边浏览有趣内容,一边看看有没有适合自己的衣服商品。一起看看如何在笔记中添加商品链接吧!小红书笔记添加商品链接方法  在手机桌面上打开app。  在app首页点击

Python在软件源码保护中的应用实践Python在软件源码保护中的应用实践Jun 29, 2023 am 11:20 AM

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

如何在沉浸式阅读器中使用Microsoft Reader Coach如何在沉浸式阅读器中使用Microsoft Reader CoachMar 09, 2024 am 09:34 AM

在这篇文章中,我们将向你展示如何在WindowsPC上的沉浸式阅读器中使用Microsoft阅读教练。阅读指导功能帮助学生或个人练习阅读并培养他们的识字技能。你从阅读支持的应用程序中的一段或一份文档开始,基于此,你的阅读报告由阅读教练工具生成。阅读报告显示了阅读的准确性、阅读所用的时间、每分钟的正确单词数,以及你在阅读时发现最具挑战性的单词。你还将能够练习这些单词,这总体上有助于培养你的阅读技能。目前,仅有Office或Microsoft365(包括OneNoteforWeb和WordforWe

小红书发布笔记教程怎么弄?它发布笔记可以屏蔽人吗?小红书发布笔记教程怎么弄?它发布笔记可以屏蔽人吗?Mar 25, 2024 pm 03:20 PM

小红书作为一个生活方式分享平台,涵盖了美食、旅行、美妆等各个领域的笔记。许多用户希望在小红书上分享自己的笔记,但却不清楚如何操作。在这篇文章中,我们将详细介绍小红书发布笔记的流程,并探讨如何在平台上屏蔽特定用户。一、小红书发布笔记教程怎么弄?1.注册登录:首先,需要在手机上下载小红书APP,并完成注册登录。在个人中心完善个人资料是很重要的。通过上传头像、填写昵称和个人简介,可以让其他用户更容易了解你的信息,也能帮助他们更好地关注你的笔记。3.选择发布频道:在首页下方,点击“发笔记”按钮,选择你想

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),