Python Web Development Libraries 简明教程
Python Web Development Libraries - Introduction
每当用户打开任何网页浏览器(如 Google Chrome 或 Mozilla)并搜索“Web 开发”时,就会在短时间内出现数千个结果。是什么让这一切成为可能?Web 开发!它广泛涉及到通过 Intranet 或 Internet 为托管构建、创建和维护网站相关的工作。与网站设计相关的工包括多个领域:Web 编程、数据库管理、Web 设计、Web 发布等。
Whenever a user opens any web browser like Google Chrome or Mozilla and search for ‘Web development’, thousands of results appear in no time. What makes this possible? Web development! It broadly refers to the work associated with building, creating and maintaining websites for hosting via intranet or internet. The work associated in website design contain multiple areas: web programming, database management, web design, web publishing, etc.
Web 开发包括让网站能够运行的所有代码。我们可以将整个 Web 开发过程分为两类:
Web development includes all the codes that influence a website to run. We can separate the whole process of web development into two categories −
-
Front-end
-
Back-end
尽管前端和后端 Web 开发肯定彼此不同,但它们也像同一枚硬币的两面。一个完整的网站依靠每一方与另一方有效地进行通信和操作,作为一个单一单元。前端和后端在 Web 开发中都同样重要。
Though frontend and backend web development are certainly distinct from each other, they are also like two sides of the same coin. A complete website relies on each side communicating and operating effectively with the other as a single unit. Both front-end and back-end are equally important in web development.
应用程序的前端或客户端是代码,负责用户在屏幕上直接体验的一切,从文本颜色到按钮、图像和导航菜单。前端开发人员使用的一些常见技能和工具如下所示:
The front-end or client-side of an application is the code responsible for everything the user directly experiences on screen from text colors to buttons, images and navigation menus. Some of the common skills and tools which are used by front-end developers are listed below −
-
HTML/CSS/JavaScript
-
CSS preprocessors
-
Frameworks
-
Libraries
-
Git and Github
通常,应用程序的后端/服务器端负责管理数据库中的信息并将该信息提供给前端。网站的后端包括服务器、应用程序和数据库。通常,它包括在进入浏览器之前发生的所有事情。后端 Web 开发中必需的工具包括:
Generally, the back-end/server-side of an application is responsible for managing information within the database and serving that information to the front-end. The back-end of a website consists of a server, application, and database. In general, it involves everything that happens before hitting your browser. The tools required in back-end web development are −
-
Programming language − Ruby, PHP, Python, etc.
-
Database − MySQL, PostgreSQL, MongoDB, Oracle, etc.
Why Web Development?
在当今世界,有多种选择可以宣传您的业务或技能并分享您的想法。其中一些是通过网站、应用商店中的原生应用程序等进行推广。创建新网站作为业务开发工具的趋势正在世界范围内迅速 gaining momentum 。但是,我们当中的一些人可能不知道网站在业务发展中的重要性。
In today’s world, there are multiple choices to promote your business or skills and share your ideas. Some of them are promotion through websites, native applications in marketplaces, etc. The trend of creating new website as a tool of business development is rapidly gaining momentum around the world. But, some of us may be unaware of the importance a website holds in the growth of a business.
当前,有许多初创企业正在努力在公开市场上确立自己的地位。然而,事实也总是如此,其中大多数未能获得他们想要的特定观众。导致他们失败的一个主要原因是,他们低估了一个功能齐全的开发网站为他们赢取业务的潜力。用于业务或任何其他目的的网站开发可能会很有用。
Currently there are numerous start-ups struggling to establish their presence in the open market. However, it is also true that most of them fail to gain as much targeted audience as they want. One primary reason which is bringing them down is that they underestimate the potential of a full feature developed website to earn business for them. Website development for business or any other purpose can prove quite fruitful.
让我们来看看网站开发对业务增长很重要的原因:
Let us look at some of the important reasons why website development is important for business growth −
Reaching out to your audiences
在线网站可以覆盖最广泛的受众,而不受限制于约束原生应用程序的平台。观看者或客户可以轻松访问,即从台式机/笔记本电脑到移动设备,因为网站有能力通过网络浏览器显示内容。
Online websites can reach to broadest audience and are not restricted to a platform that constrain native applications. The viewers or customers can have easy access i.e. from a desktop/laptop to a mobile device, as websites have the capability to display the content through web browser.
与原生应用程序相比,网络浏览要简单得多,因为它不需要用户访问设备上的应用商店或下载他们的应用程序(这可能包括一个或多个访问您内容的过程)。基于 Web 的应用程序比原生应用程序更灵活且敏捷,因为没有严格的应用商店要求和内容限制需要遵守。
In comparison to native application, web browsing is much simpler because it does not require users to access the app store on their devices or download their app (which may include one or more processes in accessing to your contents). Distribution of your data is much more flexible and agile with web-based application than native ones as there are no stringent app store requirements and content restrictions to follow.
另一个对 Web 开发非常有用的工具是利用 SEO 技术来定位您的受众。
Another tool which is very helpful for web development is the power of utilizing SEO techniques to target your audiences.
24/7 Accessible
如果企业主将网站开发为在线论坛或类似论坛,而不是为公司建立一个实体店面,那么有很大的机会在线获得更大的受众进行链接。这是因为大多数人整天都与互联网相连。
Instead of establishing a physical outlet for the company, if the business owner develops a website as an online forum or similar, there will be good chance of gaining larger audience online to link up. This is because, most of the people are wired up with the Internet all day.
通常,人们倾向于选择最明智的方式先进行在线检查,然后再做出决定。因此,如果企业主填写产品的所有基本详细信息并制定一种安全的方式及时将产品送到客户手中,那么人们宁愿在线购买,也不愿亲自访问店面。这也允许人们即使在一天中最奇怪的时间也能访问它。
Generally, people prefer to go for the smartest way to check online first and then take a decision. So if the business owner fills all the basic details of the product and make a secure way to get the product to the customer in timely manner, then people will prefer buying online instead of visiting the outlet physically. This also allows people to access it even in the oddest hour of the day.
Convenience
一个功能齐全的网站为用户提供了更大的优势,他们可以随时收听并寻找他们需要的东西。通常,如果用户可以选择在线获得产品,他们就会避免亲自去商店。因此,如果你是聪明的商人,你宁愿只在网站上提供所有产品或商店的详细信息来赢取业务,否则你可能无法获得业务。
A fully functional website provides greater advantage for users where they can always tune in and look for what they need. Generally, users avoid going to stores physically if they have an option to get it online. So, if you are a smart businessman, you would prefer to have all the details of your products or your stores on the website only to earn business, which you otherwise might not.
Global Marketing
通过在线网站,你可以链接到社交论坛并向全球各地的庞大受众宣传你的产品/服务。通过此操作,你可以定期在社交论坛上宣传和分享你的作品,以获得更多目标受众的关注。
With an online website, you can link up to social forums and market your product/service to a huge audience all around the globe. With this, you can regularly advertise and share your work on social forums to gain much higher footprints of targeted audience.
Credible Source
在线门户是任何公司/组织最值得信赖的平台。有时,官方网站甚至可以作为其唯一办事处。考虑一种情况,即无法轻松访问公司的物理位置。在这种情况下,你可以专注于他们的网站来克服这种担忧。
An online portal is the most trustworthy platform for any company/organization. Sometimes official websites can even function as their sole office. Consider a scenario, where it is not easy to get access to a company’s physical location. In such case, you can overcome this worry by focusing on their website.
简而言之,通过开发一个网站,你可以通过几次点击来宣传你的服务,并且你可以吸引来自世界各地的消费者的注意力。公司的网站可以证明在短期内不仅可以获得业务,而且还可以获得更大的受众。
In short, by developing a website, you can promote your services by a few clicks and you can grab the attention of consumers from various parts of the world. The website of a company can prove remarkable to gain business not only in a shorter time but also with a much bigger audience.
Python Frameworks
Python 是一种网络和应用程序开发者最可接受的语言之一,因为它注重效率和可读性。有许多杰出的 Python Web 框架,每个框架都有自己的专长和功能。
Python is one of the most acceptable languages among web and application developers because of its strong emphasis on efficiency and readability. There are numerous outstanding Python web frameworks, each with their own specialities and features.
Django
在这里,我们将概述 Django 框架的一些必要的详细信息和功能。
Here, we will outline some necessary details and features of Django framework.
Category - Django 属于全栈 Python 框架。
Category − Django belongs to the full-stack Python framework.
Release - 最新版本 – 2.1 版本,常用版本 – 1.8、1.6 版本。
Release − Latest release – 2.1 version, commonly used release – 1.8, 1.6 version.
About - Django 是由经验丰富的开发者构建的高级 Python Web 框架,它允许进行快速、干净和实用设计开发。Django 处理了网络开发的许多复杂性,因此你可以专注于编写应用,而无需发明轮子。Django 是免费且开源的。
About − Built by experienced developers, Django is a high level Python web framework which allows rapid, clean and pragmatic design development. Django handles much of the complexities of web development, so you can focus on writing your app without a need to reinvent the wheel. It’s free and open source.
为了将对象映射到数据库表,Django 使用 ORM,并且同样的方法用于在数据库之间转移数据。
To map objects to database table, Django uses ORM and the same is used to transfer from one database to other.
它与大多数所有重要数据库(如 Oracle、MySQL、PostgreSQL、SQLite 等)配合使用。
It works with mostly all important databases like Oracle, MySQL, PostgreSQL, SQLite, etc.
业界中有众多网站使用 Django 作为其后端开发的主要框架。
There are numerous websites in the industry which uses Django as their primary framework for backend development.
Features of Django
此 Python Web 框架的一些优秀特性是 −
Some of the exemplary features of this Python web framework are −
-
URL routing
-
Authentication
-
Database schema migrations
-
ORM (Object-relational mapper)
-
Template engine
Django 框架的官方网站是 − https://www.djangoproject.com/
The Official Website for Django framework is −https://www.djangoproject.com/

Flask
Category − Flask 属于非全栈框架。
Category − Flask belongs to Non Full-stack frameworks.
Release − 1.0.2 于 2018 年 5 月 2 日发布
Release − 1.0.2 released on 2018-05-02
About − 我们将其归类为微型框架,因为我们不需要任何特定的库或工具。它没有表单验证或数据库抽象层,或任何预先存在的第三方库提供通用函数的其他组件。但是,flask 支持多个扩展,这些扩展扩展了应用程序功能,就好像它们是在 Flask 本身中实现的一样。存在用于对象关系映射、表单验证、上传处理、各种开放身份验证技术和几个常见框架相关工具的扩展。
About − It is classified as a micro-framework as we don’t require any particular libraries or tools. It has no form validation or database abstraction layer or any other components where pre-existing third party libraries provide common functions. However, flask support multiple extensions which extended the application features as if they were implemented in Flask itself. Extensions exist for object-relational mappers, form validation, upload handling, various open authentication technologies and several common frameworks related tools.
Features of Flask
-
Integrated support for unit testing
-
Restful request dispatching
-
Contains development server and debugger
-
Uses Jinja2 templating
-
Support for secure cookies
-
Unicode-based
-
100% WSGI 1.0 compliant
-
Extensive documentation
-
Google App Engine compatibility
-
Extensions available to enhance features desired

Web2py
Category − Web2py 属于全栈框架系列。
Category − Web2py belongs to Full-stack framework family.
Release − 2.17.1,已于 2018 年 8 月 6 日发布
Release − 2.17.1, released on 2018-08-06
About − Python 2.6、2.7 至 Python 3.x 版本。无进一步依赖,它本身就是一个完整软件包。应用程序的开发、数据库管理、调试、部署、测试和维护都可以通过 Web 界面来完成,但通常不需要。这是一种可扩展的开源框架,配有它自己的基于 Web 的 IDE,以及代码编辑器、一键式部署和调试器。
About − Python 2.6, 2.7 to Python 3.x version. With no further dependencies, it’s a complete package in itself. Development, database administration, debugging, deployment, testing, and maintenance of applications all can be done through web interface, but generally not required. It is a scalable open source framework that comes with its own web-based IDE alongside a code editor, one-click deployment and debugger.
Features of Web2py
此框架附带了许多开发工具和内置功能,消除了开发者的复杂化繁琐过程。
This framework comes with many developing tools and built-in features that eliminate the hassle of complexity to the developers.
-
With no installation and configuration, it is easy to run.
-
Supports almost all major operating system, like Windows, Unix/Linux, Mac, Google App Engine and almost all web hosting platform through Python 2.7/3.5/3.6/ version.
-
Easy to communicate with MySQL, MSSQL, IBM DB2, Informix, Ingres, MongoDB, SQLite, PostgreSQL, Sybase, Oracle and Google App Engine.
-
It prevents the most common types of vulnerabilities including Cross Site Scripting, Injection Flaws, and Malicious File Execution.
-
Supports error tracking and internationalization.
-
Multiple protocols readability.
-
Employs successful software engineering practices that makes code easy to read and maintain.
-
Ensure user-oriented advancements through backward compatibility.

Pyramid
Category −Pyramid 是一个非全栈框架
Category − Pyramid is a non-Full Stack Frameworks
Release - 1.9.2,发布于 2018-04-23
Release − 1.9.2, released on 2018-04-23
About - Pyramid 是一个紧凑、快速、务实的 Python Web 框架。它作为 Pylons 项目的一部分而开发。它在类 BSD 许可下获得许可。它使得现实世界的 Web 应用程序开发和部署变得更加有趣、更可预测,更高效。
About − Pyramid is a small, fast, down-to-earth Python web framework. It is developed as part of the Pylons Project. It is licensed under a BSD-like license. It makes real-world web application development and deployment more fun, more predictable and more productive.
Features of Pyramid
Python Pyramid 是开源的框架,有以下特色 -
Python Pyramid is an open sourced framework with the following features −
-
Simplicity − Anyone can start to work with it without any prior knowledge about it.
-
Minimalism − Quite out of the box, Pyramid comes with only some important tools, which are needed for almost every web application, may it be security or serving static assets like JavaScript and CSS or attaching URLs to code.
-
Documentation − Includes exclusive and up to date documentation.
-
Speed − Very fast and accurate.
-
Reliability − It is developed, keeping in mind that it is conservative and tested exhaustively. If not tested properly, it will be considered as broke.
-
Openness − It’s sold with a permissive and open license.

Dash
Category - Dash 框架属于“其他”Python web 框架。
Category − The Dash framework belongs to “other” Python web frameworks.
Release - 0.24.1,Dash 核心后端。
Release − 0.24.1, core dash backend.
About - Dash 是一个用于创建交互式 Web 可视化的开源库。Plotly 团队创建了 Dash,这是一种利用 Flask、React.js 和 plotly.js 来构建自定义数据可视化应用程序的开源框架。该库的关键亮点是,您可以只通过 Python 代码构建高度交互的 Web 应用程序。数据科学家喜欢 Dash 框架,尤其是那些不太熟悉 Web 开发的人员。
About − Dash as an open source library for creating interactive web-based visualizations. The plotly team created Dash – an open source framework that leverages Flask, React.js and plotly.js to build custom data visualization apps. Key highlight of this library is that you can build highly interactive web application only through Python code. Data scientists love dash framework, specially all those who are less familiar with web development.
利用 Dash,开发人员可以访问所有可配置属性和底层 Flask 实例。利用 Dash 框架开发的应用程序可以部署到服务器中,而且最终呈现到 Web 浏览器中。
With Dash, developers get access to all the configurable properties and underlying Flask instance. The applications developed using Dash framework can be deployed to servers and are eventually rendered in the web browser.
Dash 应用程序天生跨平台(Linux/Win/Mac),且对移动设备友好,而且 Flash 插件的丰富集可以扩展应用程序的功能。
Dash applications are inherently cross-platform (Linux/Win/Mac) and mobile friendly and the capabilities of applications can be extended by the rich set of Flask Plugins.

Django Framework
在本章中,我们将详细讨论 Django 框架。
In this chapter, we will discuss about Django Framework in detail.
Django 是一个用于构建 Web 应用程序的 MVT Web 框架。巨大的 Django Web 框架包含很多“内置信息”,开发者常常惊叹于所有这些是如何协同工作的。添加这么多内置信息的原理是将通用 Web 功能放入框架本身,而不是作为单独的库添加。
Django is an MVT web framework that is used to build web applications. The huge Django web-framework comes with so many “batteries included” that developers often get amazed as to how everything manages to work together. The principle behind adding so many batteries is to have common web functionalities in the framework itself instead of adding latter as a separate library.
Django 框架流行的主要原因之一是它拥有庞大的 Django 社区。社区如此庞大,以至于专门为其创建了一个网站,让来自各地的开发者可以开发第三方包,包括身份验证、授权、功能齐全的 Django 驱动的 CMS 系统、电子商务插件等等。你尝试去开发的东西很有可能已被其他人开发出来了,你只需要将那个整合到你的项目中即可。
One of the main reasons behind the popularity of Django framework is the huge Django community. The community is so huge that a separate website was devoted to it where developers from all corners developed third-party packages including authentication, authorization, full-fledged Django powered CMS systems, e-commerce add-ons and so on. There is a high probability that what you are trying to develop is already developed by somebody and you just need to pull that into your project.
Why should you use Django?
Django 的设计是为了鼓励开发者快速、干净、实用地设计地开发网站。Django 以其实用的方式来完成工作而从众多框架中脱颖而出。
Django is designed in such a way that encourages developers to develop websites fast, clean and with practical design. Django’s practical approach to getting things done is where it stands out from the crowd.
如果你计划构建一个高度可定制的应用程序,比如社交媒体网站,Django 是最佳的框架之一。Django 的优势在于它在用户之间的交互以及共享不同类型媒体的能力。Django 的一大优势在于其利用大型社区支持的能力,这给了你高度可定制的第三方即用型插件,用于你的应用程序。
If you’re planning to build a highly customizable app, such as social media website, Django is one of the best frameworks to consider. Django strength lies in its interaction between users or its ability to share different types of media. One of the great advantage of django is its ability to utilize large community-based support which gives you highly customizable third-party ready to use plugins in your applications.
以下是选择 Django 用作 Web 开发的十大理由−
Below are the top ten reasons to choose Django for web development −
Python
Python 是公认的最容易学习的编程语言之一,因为它有简单的语言结构、流结构和简单的语法。它非常通用,既能运行网站,也能运行桌面应用程序和嵌入到许多设备中的移动应用程序,并作为一种流行的脚本语言用于其他应用程序。
Python is arguably one of the easiest programming languages to learn because of its simple language constructs, flow structure and easy syntax. It is versatile and runs websites, desktop applications and mobile applications embedded in many devices and is used in other applications as a popular scripting language.
Batteries Included
Django 带有通用的库,这对于构建诸如 URL 路由、身份验证、对象关系映射器 (ORM)、模板系统和 db 架构迁移之类的通用功能非常重要。
Django comes with common libraries which are essential to build common functionalities like URL routing, authentication, an object-relational mapper (ORM), a templating system and db-schema migrations.
Built-in admin
Django 有一个内置的管理界面,让你可以处理你的模型、用户/组权限,以及管理用户。有了模型界面,除了高级数据库功能以外,就不再需要单独的数据库管理程序。
Django has an in-built administration interface which lets you handle your models, user/ group permissions and to manage users. With model interface in place, there is no need for a separate database administration program for all but advanced database functions.
Doesn’t get in your way
创建一个 Django 应用程序不会添加任何样板代码和不必要的功能。没有强制要求导入、第三方库以及 XML 配置文件。
Creating a Django application adds no boilerplate and no unnecessary functions. There’s no mandatory imports, third-party libraries and no XML configuration files.
Scalable
Django 是基于 MVC 设计模式 的。这意味着所有实体,如数据库 (database)、后端和前端代码,都是独立的实体。Django 允许我们将代码从静态媒体中分离出来,包括图片、文件、CSS 和 JavaScript,它们构成了你的网站。
Django is based on MVC design pattern. It means that all the entities like db (database), back-end and front-end code are individual entity. Django allows us to separate code from the static media including pictures, files, CSS and JavaScript that make up your site.
Django 支持用于 Web 服务器、缓存、性能管理、集群和平衡的第三方库的完整列表。Django 提供的优点之一是对主要的电子邮件和消息应用程序和服务的支持,如 ReST 和 OAuth。
Django supports a full list of third-party libraries for web servers, caching, performance management, clustering and balancing. One of the advantages Django provides is the support for major email and messaging applications and services like ReST and OAuth.
Battle tested
Django 在 2005 年首次开源。在 12 年的发展之后,Django 现在不仅运行新闻发布网站,而且还运行 Pinterest、Instagram、Disqus、Bitbucket、EventBrite 和 Zapier 等主要全球性企业的全部或部分业务。这使得其成为一种强大且可靠的 Web 框架,供开发者使用。
Django was first open-sourced in 2005. After 12 years of growth, Django now not only runs news publishing websites but also runs all or part of major global enterprise like Pinterest, Instagram, Disqus, Bitbucket, EventBrite and Zapier. This makes it a robust and reliable web framework to work with.
Huge package support
由于它有很大的社区支持和庞大的开发者网络,因此你打算做的任何事情很可能以前都已完成过。大量的国际开发者社区通过将他们的项目作为开源包发布,为社区做出贡献。
Because of its large community support and huge developers network, there is a high possibility that whatever you intend to do might have been done before. Large international community of developers contribute to the community by releasing their projects as open-source packages.
这些项目的其中一个资料库是 Django 包网站。目前,Django 包列出了超过 3400 个用于我们在 Django 项目中使用的可重复使用的 Django 应用程序、网站和工具。
One such repository of these projects is Django Package site. Currently, Django packages list over 3400 plus reusable Django apps, sites and tools to use in our Django projects.
Actively developed
与开放源代码项目相关的最大风险之一是其可持续性。我们无法确定它是否能够持续很长时间。
One of the biggest risks associated with open source project is its sustainability. We cannot be sure if it lasts long.
Django 没有此类风险,因为它已经存在 12 年了。它持续发布、提供更新/更好的版本,其活跃社区每天都在壮大,并且拥有一个由自愿贡献者组成的大核心团队,他们每天都维护和改进代码库。
There is no such risk with Django as it is 12 years old. Its consistent releases, newer/better versions and active community is growing every-day with a large core team of voluntary contributors who maintains and improve the code base every-day.
Stable releases
像 Django 这样的开放源代码软件项目在很多情况下都会积极开发,并且比竞争性的专有软件更安全,因为许多开发人员每天都在开发和测试它。但是,开放源代码软件项目的缺点是缺少可供商业上可行的开发使用的稳定代码库。
Open-source software projects like Django are, in many cases, actively developed and more secure than competing proprietary software as many developers are developing and testing it every day. However, the drawback of an open-source software project is the absence of a stable codebase to commercially viable development.
在 Django 中,我们有软件的长期支持 (LTS) 版本和一个明确的发布流程,如下图所示:
In Django, we have Long Term Support (LTS) versions of the software and a defined release process as shown in the below image −

Who’s Using Django?
由于 Django 独一无二的优势,有许多流行网站都使用 Python 构建在 Django 框架之上。以下是基于 Django 全部或部分构建的一些主要网站。
Because of the Django’s unique strength, there are multiple popular websites which are built with Python on top of the Django framework. Below are some of the major sites which are fully or partially built based on Django.
Disqus
它是全球最受欢迎的博客评论托管网站之一。它可以通过 Disqus 轻松地与大多数流行的 CMS(内容管理系统)集成,例如 WordPress 和许多其他系统。通过满足超过 5000 万用户群的需求,Django 可以让网站所有者与其社区取得联系。
It is one of the most preferred blog comment-hosting sites globally. It is easy to integrate with most popular CMS (content management systems) like WordPress and many others through Disqus. Handling a user-base of over 50 million, Django is able to satisfy the site owners to reach out to their communities.

The Onion
洋葱新闻网为他们的讽刺报纸提供了一个在线场所,Django 为它提供了框架。
The Onion website which provide an online venue for their satirical newspaper, Django provides the framework for it.

Bitbucket
Bitbucket 类似于 GitHub,是一个版本控制存储库托管服务。Bitbucket 与 GitHub 之间的唯一区别在于 Bitbucket 托管 Mercurial 存储库,而 GitHub 托管 Git 存储库。由于数百万用户使用 Bitbucket,并且 Bitbucket 提供的所有服务(例如创建存储库、推送代码、添加协作者、提交、提交请求等)都必须稳定可靠。Django 负责运行 Bitbucket 网站。
Bitbucket is like GitHub, a version control repository hosting service. The only difference between Bitbucket and GitHub is that Bitbucket hosts mercurial repositories whereas GitHub hosts git repositories. As millions of users are associated with Bitbucket, and all the services which bitbucket provides (like create a repo, push your code, add collaborators, commits, pull request, etc.) has to be stable. Django is responsible for running the bitbucket site.

Instagram 是一款社交网络应用,专为那些喜欢与所有朋友分享照片和视频的人打造。目前 Instagram 上有很多名人,以便与粉丝们保持更密切的联系。Django 框架也在运行 Instagram。
Instagram is a social networking app built especially for those who love to share photos and videos to all their friends. Currently there are a lot of celebrities on Instagram so as to stay closer to their fans. Django framework is running the Instagram too.

Mozilla Firefox
继 Google Chrome 之后,Mozilla 浏览器是全球使用第二广泛的浏览器。现在 Mozilla 的帮助页面是使用 Django 框架构建的。
Second most widely used browser in the world after Google Chrome is the Mozilla browser. Now the help page of Mozilla is built with Django framework.

全球数百万用户通过 Pinterest 发现他们的新想法和灵感。Pinterest 使用 Django 框架(根据其要求进行修改)来运行它。
Millions of users around the globe discover their new ideas and inspiration from Pinterest. Pinterest is using the Django framework (done modification as per their requirement) to run it.

NASA
美国国家航空航天局的官方网站是一个让数百万用户访问该主要机构提供的新闻、图片、视频和播客的地方。Django 开发了官方 NASA 网站的某些特定部分。
The National Aeronautics and Space Administration’s official website is a place for millions of users to visit and check out the news, images, videos and podcasts provided by the premiere agency. Django develops some specific parts of official NASA website.

The Washington Post
如果世界上有一家有影响力的报纸,那肯定就是《华盛顿邮报》。《华盛顿邮报》的网站是一个非常流行的在线新闻来源,可作为其日报的补充。《华盛顿邮报》的网站拥有巨大的浏览量和流量,而 Django Web 框架能够轻松地应对这些问题。
If there’s one influential newspaper in the world, it is certainly the Washington Post. The Washington Post’s website is a hugely popular online news source to accompany their daily paper. Its huge amount of views and traffic has been easily handled by Django web framework.

Reddit Gifts
大受欢迎的 Reddit 网站已经推出了一款名为 Reddit Gifts 的在线匿名礼物交换和聚会平台。该网站连接了来自世界各地的用户,并在他们之间促成礼物交换。Django Web 框架为其功能提供支持。
The massively popular Reddit website has launched an online, anonymous gift exchange and meetup platform called Reddit Gifts. The site connects users from around the world and facilitates gifts exchange between them. The Django web framework powers its functionalities.

Prezi
Prezi 是基于 Django 框架构建的 Microsoft PowerPoint 的云端替代产品。该网站提供了一个虚拟画布,可以对其进行操作、放大和缩小。这提供了整个演示文稿的视图,而不是各个幻灯片。
Prezi is a cloud based alternative to Microsoft PowerPoint built on the Django framework. The site provides a virtual canvas that can be manipulated and zoomed in and out. This provides the entire view of the presentation rather than individual slides.

Installing and Creating a Django project and app
在安装 Django 之前,我们必须确保已经安装了 Python。假设你正在使用 virtualenv,只需 pip install django 就足够了。
Before installing Django, we have to make sure that Python is installed. Assuming you are using virtualenv, a simple pip install django should suffice.
Creating Django Project
完成安装后,我们需要创建一个 Django 项目。
Once the installation is completed, we need to create a Django project.
在 Windows 机器中运行以下命令将创建如下所示的 Django 项目:
Running the below command in your windows machine will create the following django project −
django-admin startproject my_project_name
django-admin startproject my_project_name


键入 dir 将显示一个新的文件和一个新的目录,如上所示。
Typing dir will show one new file and one new directory as shown above.
manage.py −manage.py 是一个命令行可执行 Python 文件,它只是 django-admin 的包装器。它帮助我们管理项目,这也暗示在它的名称中。
manage.py − manage.py is a command-line-executable Python file which is just a wrapper around django-admin. It helps us manage our project which is implied in its name as well.
通过此,它在 myFirstDjangoProject 中创建了一个名为 myFirstDjangoProject 的目录,它表示我们项目的配置根目录。让我们深入探索一下。
With this, it created a directory called, myFirstDjangoProject inside myFirstDjangoProject which represents the configuration root for our project. Let us explore much deeper into it.
Configuring Django
通过将 myFirstDjangoProject 目录称为“配置根”,我们的意思是该目录包含为常规配置我们的 Django 项目而必需的文件。该目录外部的几乎所有内容都将仅关注与项目的模型、视图、路由等相关的“业务逻辑”。将项目连接在一起的所有点都会在此处生成。
By calling the myFirstDjangoProject directory “configuration root”, we mean this directory holds the files necessary for generally configuring our Django project. Pretty much everything outside this directory will be focused solely on the “business logic” associated with the project’s models, views, routes, etc. All points that connect the project together will lead here.

-
init.py − This is empty and changes the directory into an importable Python package.
-
settings.py − As the name suggest, it is the place where most configuration items will be set.
-
urls.py − The URLs are set with urls.py. With this, we don’t have to explicitly write every URL for the project in this file. However, we have to tell Django about where the URLs have been declared (i.e., we need to link other URL in urls.py).
-
Wsgi.py − This is to help application in production and is similar to other applications like Flask, Tornado, Pyramid which exposes some “app” object.
Setting the settings
查看 settings.py 将揭示它的大小相当大 - 这只是默认设置。其他我们需要注意的事情是静态文件、数据库、媒体文件、云集成或 Django 项目可以配置的其他几十种方式。让我们了解 settings.py 文件中提到的要点:
Taking a look inside settings.py will reveal its considerable size – and these are just the defaults. Other things that we need to take care are the static files, database, media files, cloud integration or other dozens of ways that a Django project can be configured. Let’s understand some points mentioned in the settings.py file −
-
BASE_DIR − This is helpful for locating files. Inside the setting.py file, BASE_DIR parameter sets the absolute path to the base directory.
-
SECRET_KEY − It is used for making hashes. In general, we used secret_key for cookies, sessions, csrf protection and auth tokens.
-
DEBUG − We can set it to project running either in development or production mode.
-
ALLOWED_HOSTS − We provide the list of hostnames through which our application is being served. In development mode, it is optional to set; however, in production machine, we need to set our Django project.
-
INSTALLED_APPS − It is the list of Django “apps” that are currently installed and running in our Django project. In-built Django provides six installed apps as follows −
-
MIDDLEWARE − It helps our Django project to run. It’s a python class that hooks into django request/response processing.
-
TEMPLATES − It defines how the document should be displayed in the frontend. Django templates are used for producing any text-based format.
-
WSGI_APPLICATION − Any server we set up has to know where the WSGI file is. In case you’re using an external server, it will look in its own settings. By default, it points to objects in wsgi.py.
-
DATABASES − It sets to the databases our Django project is currently accessing. It is mandatory to set default database. In case we set the database of our choice, we need to mention few things related to database like - HOST, USER, PASSWORD, PORT, database NAME, and appropriate ENGINE.
-
STATIC_URL − It is the URL to use when referring to static files located in STATIC_ROOT. By default, it’s None.
然而,我们可能需要为静态文件添加一个路径。转到文件末尾,在 STATIC_URL 条目的正下方,添加一个名为 STATIC_ROOT 的新条目,如下所示 −
However, we may need to add a path for static files. Go down to the end of the file, and just underneath the STATIC_URL entry, add a new one called STATIC_ROOT as shown below −
myFirstDjangoProject/settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, ‘static’)
Setting up a Database
有很多不同的数据库软件可以存储你网站的数据。我们将使用默认软件 sqlite3。
There’s a lot of different database software that can store date for your site. We’ll use the default one, sqlite3.
这是在你 myFirstDjangoProject/settings.py − 中给出的以下部分中已经设置的
This is already set up in the below given part of your myFirstDjangoProject/settings.py −
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
为了为我们的博客创建一个数据库,让我们在控制台中运行以下代码 − python manage.py migrate (我们需要在包含 manage.py 文件的 myFirstDjangoProject 目录中。
To create a database for our blog, let’s run the following in the console − python manage.py migrate (we need to be in the myFirstDjangoProject directory that contains the manage.py file.
如果一切顺利,你将获得以下输出 −
You will get the following output if everything goes well −

Starting the Web Server
你需要在包含 manage.py 文件的目录中。在控制台中,我们可以通过如下所示运行 python manage.py runserver 来启动 Web 服务器 −
You need to be in the directory that contains the manage.py file. In the console, we can start the web server by running python manage.py runserver as follows −

现在,你需要做的就是检查你的网站是否正在运行。打开你的浏览器(Firefox、Chrome、Safari、Internet Explorer 或你用任何其他浏览器)并输入此地址 −
Now all you need to do is check that your website is running. Open your browser (Firefox, Chrome, Safari, Internet Explorer or whatever you use) and enter this address −
或
or
http://localhost:8000/ # 因为我们的 Web 服务器仅在我们的本地计算机中运行。
http://localhost:8000/ # As our webserver is running in our local machine only.
恭喜!您刚刚创建了你的第一个网站并使用 Web 服务器运行它!
Congratulations! You’ve just created your first website and run it using a web server!

在 Web 服务器运行期间,你不会看到一个新的命令行提示来输入其他命令。终端将接受下一项文本,但不会执行新命令。这是因为 Web 服务器持续运行以侦听传入请求。
While the web server is running, you won’t see a new command-line prompt to enter additional commands. The terminal will accept next text but will not execute new commands. This is because the web server continuously runs in order to listen to incoming requests.
Django Models
我们正在尝试创建一个 Django 模型,它将存储我们博客中的所有帖子。但要确保其正常工作,我们需要了解对象。
We are trying to create a Django model that will store all the posts in our blog. But to make sure it works, we need to learn about objects.
Objects
对象是属性和操作的集合。让我们用一个例子来理解这一点。假设我们想模拟一只猫,我们将创建一个名为 Cat 的对象,它具有颜色、年龄、情绪(好/坏/困)和主人等属性。
Objects is a collection of properties and actions. Let us understand this with an example. Suppose we want to model a cat, we will create an object called Cat that has properties such as color, age, mood (good/bad/sleepy) and owner.
然后,Cat 有一些动作:呼噜、抓挠或喂食。
Then the Cat has some actions: purr, scratch or feed.
Cat
--------
color
age
mood
owner
purr()
scratch()
feed(cat_food)
CatFood
--------
taste
因此,我们基本上试图用属性(称为对象属性)和操作(称为方法)在代码中描述真实的事物。
So basically we are trying to describe real things in code with properties (called object properties) and actions (called methods).
在构建博客时,我们需要一些文本内容和标题。有作者姓名、创建日期和发布日期也是必要的。
As we are building a blog, we need some text content and a title. It is also necessary to have the author’s name, date of creation and also the date of publication.
因此,我们的博客将包含以下对象:
So our blog will have the following objects −
Post
--------
title
text
author
created_date
published_date
我们还需要一些用于发布该帖子的方法。在了解了什么是对象之后,我们可以为博客文章创建一个 Django 模型。
Also we need to have some method that publishes that post. As we are now aware of what an object is, we can create a Django model for our blog post.
模型是 Django 中一种特殊的对象类型,并保存到数据库中。我们将在 SQLite 数据库中存储我们的数据。
A model is a special kind of object in Django and is saved in the database. We will store our data in SQLite database.
Creating an application
为了保持清晰明了,我们将在项目中创建一个单独的应用程序。接下来,我们将尝试通过运行以下简单的命令来创建博客 Web 应用程序。
To keep everything clear, we will create a separate application inside our project. Below, we’ll try to create a blog web application by running below mentioned simple command.
现在我们注意到,一个新的 myBlog 目录已创建并且其中包含多个文件。我们项目中的目录和文件应如下所示:
Now we will notice that a new myBlog directory is created and it contains a number of files now. The directories and files in our project should be as following −

创建应用程序后,我们还需要告诉 Django 使用它。我们在文件 myFirstDjangoProject/settings.py 中执行此操作。
After creating an application, we also need to tell Django to use it. We do that in the file myFirstDjangoProject/settings.py.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myBlog',
]
Creating a blog post model
在 myBlog/models.py 文件中,我们定义了所有称为模型的对象——这是一个我们定义博客文章的地方。
In the myBlog/models.py file, we define all objects called Models – this is a place in which we will define our blog post.
打开 myBlog/models.py,删除其中的所有内容,并按如下所示编写代码:
Let’s open myBlog/models.py, remove everything from it, and write code as follows −

首先,我们通过调用 from 或 import 从其他文件中导入一些功能。这样,我们可以通过 from and import 包含一些部分,而不用在每个文件中复制和粘贴相同内容。
Firstly, we import some functionalities from other files by calling from or import. So with this, instead of copying and pasting the same things in every file, we can include some parts with from and import.
class Post(models.Model) - 这行代码定义了我们的模型(它是一个对象)。
class Post(models.Model) − This line defines our model (it is an object).
-
class is a special keyword that indicates that we are defining an object.
-
Post is the name of our model. Always start a class name with an uppercase letter.
-
models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database.
现在,让我们讨论一下上面定义的属性:title、text、created_date、published_date 和 author。为此,我们需要定义每个字段的类型。
Now let us discuss about the properties we defined above: title, text, created_date, published_date and author. To do that, we need to define the type of each field.
-
models.CharField − This is how you define text with a limited number of characters.
-
Models.TextField − This is for long text without a limit.
-
Models.DateTimeField − This is for date and time.
-
Models.ForeignKey − This is a link to another model.
我们使用 def 来定义函数/方法,而 str 是该方法的名称。
We define a function/method with def and publish is the name of the method.
方法通常会返回一些内容。在本文中,当我们调用 str () 时,我们会得到一篇 Post 标题下的文本 (字符串)。
Methods often return something. Here when we call str(), we will get a text (string) with a Post title.
Creating tables for models in your database
最后一步是向数据库添加一个新模型。首先,我们必须让 Django 明白我们已对模型做出一些更改。让我们在控制台窗口中使用命令 python manage.py make migrations myBlog 进行此操作,如下所示:-
The final step is to add a new model to our database. First, we have to let Django understand that we have made some changes in our model. Let us do the same in our console window with command python manage.py make migrations myBlog as shown below −

然后,Django 会准备一个迁移文件,我们现在必须将其应用于数据库。在控制台中,我们可以输入: python manage.py migrate myBlog ,输出应如下所示:-
Then, Django prepares a migration file that we now have to apply to our database. In our console we can type: python manage.py migrate myBlog and the output should be as follows −

我们的 Post 模型现在已在我们的数据库中。
Our Post model is now in our database.
Django Admin
我们要添加、编辑和删除刚建模的帖子,现在我们要使用 Django 管理。
To add, edit and delete the posts we’ve just modelled, we are using Django admin.
所以,让我们打开 myBlog/admin.py file 并把以下内容放入其中 -
So let us open the myBlog/admin.py file and put below contents in this −

首先,我们要导入(包含)在之前的章节中定义的 Post 模型。为了让我们的模型在管理页面中可见,我们需要使用 manage.py createsuperuser (Post)向 admin.site 注册模型。
Firstly, we import (include) the Post model defined in the previous chapter. To make our model visible on the admin page, we need to register the model with admin.site.register (Post).
要登录管理网站,你需要创建一个超级用户帐户,这个帐户可以控制网站上的所有内容。所以,请停止 Web 服务器并在命令行中输入 manage.py createsuperuser ,然后按 Enter。
To login to an admin site, you need to create a superuser – a user account that has control over everything on the site. So stop the webserver and type in command line python manage.py createsuperuser, and press enter.

好,现在是时候看一下我们的 Post 模型了。记住在控制台中运行 python manage.py run server 来运行 Web 服务器。转到浏览器并输入地址 https://127.0.0.1:8000/admin/. ,使用我们刚刚选择的凭据登录。然后,你应看到与以下类似的 Django 管理信息中心:-
Ok, so it’s time to look at our Post model. Remember to run python manage.py run server in console to run the web server. Go to your browser and type the address https://127.0.0.1:8000/admin/. Log in with the credentials we have just chosen. Then you should see the Django admin dashboard as below −

转到 Post 并使用它进行一些尝试。你可以从任何地方添加许多博文和内容。你的博文会看起来像这样:-
Go to Posts and experiment a little with it. You can add many blog posts, and contents from anywhere. Your blog will look something like this −

本课程只是 Django 的概览,我们能够使用几行代码创建一个博文。
This is just an overview of Django and we are able to create a blog with just a few lines of code.
Flask Framework
Flask 是一种微框架,几乎不依赖于外部库。它是一种非常轻量的框架,让我们可以自由地做任何我们想做的事情。
Flask is micro-framework which has very little dependency on external libraries. It is a very light framework and gives us freedom to do whatever we want.
在本章中,我们将使用 Python 和 Flask 框架构建一个项目。
In this chapter, we are going to build a project using Python and Flask framework.
Flask Startup and Configuration
类似大多数广泛使用的 python 库,可以从 Python 程序包索引 (PPI) 安装 Flask 程序包。让我们首先创建一个目录(在本章中,我们创建了一个名为 flaskProject 的目录),然后创建一个虚拟环境(并将其称为 flaskEnv ),所有项目相关的依赖项都将加载到该环境中(包括 flask)。你还可以安装 flask-sqlalchemy,以便你的 flask 应用程序可以轻松地与 SQL 数据库通信。
Like most widely used python libraries, the Flask package is installable from the Python Package Index (PPI). Let’s create a directory first (In this chapter, we have created a directory called flaskProject) then created a virtual environment (and called it as flaskEnv) where all the project related dependencies will be loaded (including flask). You can also install flask-sqlalchemy so that your flask application has a simple way to communicate with SQL database.
安装 flask 之后,flaskEnv(我们的虚拟环境名称)将显示类似以下的内容:
After installing the flask, your flaskEnv (our virtualEnvironment name) will show something like below −

Creating an app with flask
通过安装 flask,我们可以使用如下所示的几行代码创建一个简单的“ hello application in flask ”:
By installing flask, we can create a simple “hello application in flask” with very few lines of code as follows −

在终端中键入以下内容:
Type the following in the terminal −
$python flaskapp.py
然后你可以看到以下输出:
And you can see the following output −
在 http://127.0.0.1:5000/ 或 localhost:5000 上运行
Running on http://127.0.0.1:5000/ or on localhost:5000

以下是我们示例代码中所执行功能的说明:
Below is the explanation of what we did in our example code −
-
Firstly, we import the Flask class library. An instance from this class is the WSGI app.
-
Secondly, we create an instance of this class. Application package or module name is our first argument. It is mandatory that flask knows where to find static files, templates and other files.
-
Next is the route() decorator we use to know which URL should trigger our method/function.
Creating URL Routing
URL 路由使 Web 应用程序中的 URL 便于记忆。我们现在将创建一些 URL 路由:
URL Routing makes URLs in your Web app easy to remember. We will now create some URL routes −
/hello
/members
/members/name
我们可以根据上面的 URL 编写下面的代码并保存为 app.py。
We can write the following code based on the above URL and save it as app.py.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return "Index!"
@app.route('/Hello')
def hello():
return "Hello, World!"
@app.route("/members")
def members():
return "Members"
@app.route("/members/<name>/")
def getMember(name):
return name
if __name__ == '__main__':
app.run(debug=True)
$ python app.py
Running on [role="bare"]http://localhost:5000/
Running on [role="bare"]http://localhost:5000/
我们在浏览器中获得下面的输出 −
We will get the following output in our browser −

我们可以在浏览器中尝试其他 URL,如下所示 −
We can try other URLs in our browser as follows −
Running on [role="bare"]http://localhost:5000/hello, will give the following output −
Running on [role="bare"]http://localhost:5000/hello, will give the following output −

Running on [role="bare"]http://localhost:5000/members, will give −
Running on [role="bare"]http://localhost:5000/members, will give −

Running on [role="bare"]http://localhost:5000/members/TutorialsPoint/, will give you the following output −
Running on [role="bare"]http://localhost:5000/members/TutorialsPoint/, will give you the following output −

但通常我们不想返回字符串(如上),我们返回模板。为此,我们想要从 flask 中使用函数 “ render_template ”,并使用一些输入返回 render_template。所以,下面的函数将完成我们的工作 −
But normally we don’t want to return a string (as above), we return templates. For that we want to use a function “render_template” from flask, and return render_template with some input. So, below function will do our work −
from flask import render_template
return render_template(‘home.html’)
让我们创建一个文件夹模板并在其中放置 home.html 文件。
Let us create a folder template and place home.html file in it.
接下来,我们将讨论布局。我们不会为每个单独的模板使用 html head 标签和 body 标签,而是设计一个布局来包含 head 和 body 标签,并包装当前视图或当前模板。为此,我们必须创建一个单独的文件并将其称为 layout.html 。在此,我们可以放置我们的正常 head 标签、body 标签和其他所有必需的标签。
Next, we will discuss about layout. Instead of using html head tag and body tag for every single template, we will design a layout to include head & body tags and wrap the current views or current template. For that, we have to create one separate file and call it layout.html. In this, we can put our normal head tag, body tag and all the other required tags.
我们可以使用下面的代码行创建我们的新 layout.html −
We can create our new layout.html with the following lines of code −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyFlaskApp</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class="container">
{% block body %}
{% endblock %}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js">
</script>
</body>
</html>
在上面的代码中,我们给出了标题曲目 MyFlaskAp,在 head 中使用 css cdn,在 body 块中使用 javascript 来启用引导程序。
In above code, we have given the title track, MyFlaskAp, use css cdn in the head, and javascript in body block to enable the bootstrap.
现在,我们必须为每个单独的页面创建导航栏。为此,我们必须首先创建一个包含文件夹,然后在其中创建 _navbar.html 文件。现在在 _navbar.html 中,我们必须使用 getbootstrap.com 提供的标准启动程序模板。新创建的 _navbar.html 文件如下所示 −
Now, we have to create navbar for every single page. For that, we have to first create an include folder and then create _navbar.html file inside it. Now in the _navbar.html, we have to use the standard starter template from getbootstrap.com. The newly created _navbar.html file will be as follows −

并将此 _navbar.html 文件包含到我们的 layout.html 文件中。
And include this _navbar.html file into our layout.html file.
{% include 'includes/_navbar.html' %}
当我们拥有布局块时,我们能够在我们的主页文件 (home.html) 中扩展此块。
As we have the layout block, we can extend this block in our home file (home.html).
我们的 home.html 文件可以使用下面的代码创建 −
Our home.html file can be created using the below code −
{% extends 'layout.html' %}
{% block body %}
<div class="jumbotron text-center">
<h1>Welcome to FlaskApp</h1>
<p>This application is built on Flask webframework!</p>
</div>
{% endblock %}
使用此内容如果我们尝试运行我们的 flaskapp.py 文件,那么我们可以在我们的浏览器中看到下面的输出 −
Using this if we try to run our flaskapp.py file, then we could see the below output in our browser −

现在,我们希望激活(当前标签无效)我们的 about 标签。为 about 标签创建一个路由并创建一个模板文件 about.html 。
Now we want to activate (currently the tabs are not working) our about tab. Create a route for the about tab and create a template file, about.html.
appflask.py 中的 about 标签路由如下所示 −
About tab route in appflask.py will be as shown below −

about.html 文件的内容如下所示 −
about.html file will have the below content −

因此现在已处理了 Home 和 About。对于文章,我们可以在根目录中创建新文件 (data.py),其中我们放置数据并在我们的网页中调用该数据。
So Home and About are now taken care of. For Articles, we can create a new file (data.py) in the root directory, where we put the data and call it in our webpage.
data.py
def Articles():
articles = [
{
'uid': 1,
'title': 'Article_One',
'body': 'Flask, being a microframework, often requires some repetitive step
to get a third party library working. Because very often these steps could
be abstracted to support multiple projects the Flask Extension Registry
was created.',
'Author': 'Rajesh Joshi',
'Created-on': '07-09-2018'
},
{
'uid': 2,
'title': 'Article_Two',
'body': "Flask, being a microframework, often requires some repetitive steps
to get a third party library working. Because very often these steps could
be abstracted to support multiple projects the Flask Extension Registry
was created.",
'Author': 'Rajesh J',
'Created-on': '07-09-2018'
},
{
'uid': 3,
'title': 'Article_Three',
'body': 'Flask, being a microframework, often requires some repetitive steps
to get a third party library working. Because very often these steps could be
abstracted to support multiple projects the Flask Extension Registry
was created.',
'Author': 'Joshi Rajesh',
'Created-on': '07-09-2018'
}
]
return articles
以下是 articles.html 的代码,该代码将显示每个 uid 的文章标题。
Below is the code for articles.html, which will display article titles for each uid.
{% extends 'layout.html' %}
{% block body %}
<h1>Articles</h1>
{% for article in articles %}
<li class="list-group-item">
<a href="article/{{article.uid}}"> {{article.title}}</a>
</li>
{% endfor %}
{% endblock %}
总结来说,Flask 是目前最流行的 Python Web 框架之一,因为它的轻量级。尽管它是微型的,但它是一个可扩展的 Python Web 框架。通过提供所需的功能,Flask 可加速简单 Web 应用程序的开发。因此,Flask 更适合较小、不太复杂的应用程序。
To summarize, Flask is one of the most popular python web frameworks because of its lightweight. Although it is micro it is an extensible python web framework. By providing the required functionality, flask accelerates the development of simple web application. So Flask, is more suitable for smaller, less complicated applications.
Web2py Framework
Web2py 是一款易于使用的框架。使用 web2py 无需安装和配置,因为它具有可移植性,且可以在 USD 驱动器中运行。它基于 MVC 框架,与许多其他 Python 框架相似。尽管大多数框架不支持旧版本的 Python,但 web2py 仍然支持旧版本:Python 2.6 和 2.7。它还支持 LDAP 认证,这是当今广泛接受的认证方式。
Web2py is an easy-to-use framework. With web2py, no installation and configuration is required as it is portable and can be run on a USD drive too. It is based on the MVC frameworks like many other python frameworks. Though most of them do not support older versions of Python, web2py still supports older versions: python 2.6 and 2.7. It also supports LDAP for authentication which is widely accepted these days.
Web2py 尝试通过关注三个主要目标降低 Web 开发的进入门槛 −
Web2py tries to lower the barrier of entry to web development by focusing on three main goals −
-
Rapid development
-
Ease of use
-
Security
考虑到用户观点,Web2py 会不断在内部进行优化以使其成为更快速、更精简的框架,包括对向后兼容性的支持。
Keeping in mind the user perspective, Web2py is built and constantly being optimized internally to make it a faster and leaner framework including support for backward compatibility.
Installing and Configuring Web2py Framework
运行一个 web2py 非常简单,你需从此链接下载 exe 文件: http://www.web2py.com/init/default/download
Running a web2py is easy, you need to download the exe from the below link: http://www.web2py.com/init/default/download
对于 Windows,你可以下载 zip 文件,将其解压,直接或通过命令行运行 exe 文件。系统会弹出如下屏幕,要求提供管理员密码。
For windows, you can download the zip file, unzip it and run the exe file either directly or from the command line. You will be prompted with below screen asking for the admin password.

你可以选择一个管理员密码并启动服务器。你将看到以下屏幕 −
You can choose an administrator password and start the server. You will see the following screen −

Creating an app using Web2py
现在我们准备创建一个新的应用程序。单击位于底部的 admin 标签。因此,输入管理员密码后,我们将看到以下屏幕 −
Now we are ready to create a new app. Click on the admin tab located at the bottom. So after entering the admin password, we will get the below screen −

转到新简单应用程序,输入一些应用程序名称(如 helloWeb2py),然后单击创建。这将显示如下所示的设计界面页面 −
Go to new simple application, enter some application name (like helloWeb2py) and click on create. This will display design interface page as given below −

你还可以访问当前的实时网络,helloWeb2py,只需在本地机器上输入 http://127.0.0.1:8000/helloWeb2py ,你将看到以下输出 −
You can also go to your current live web,helloWeb2py, simply type http://127.0.0.1:8000/helloWeb2py on your local machine, you will get the below output −

在 helloWeb2py 应用程序的设计页面中,转到控制器,然后单击 default.py 旁边的编辑按钮。如果你更改 index() 函数的返回值,将显示以下输出 −
In the design page of helloWeb2py application, go to the controller and click on edit button next to default.py. If you change the return value of the index() function, the following output will be displayed −

保存更改内容,现在你可以在 helloWeb2py 应用程序中查看所做的更改。只需刷新 http://127.0.0.1:8000/helloWeb2py 链接,你将看到以下输出 −
Save the changes, and now you can check the changes made in your helloWeb2py app. Just refresh the http://127.0.0.1:8000/helloWeb2py link and you will see the below output −

Deploying the app on cloud platform
现在,如果你想在云平台上部署你的应用程序,请返回主页并单击站点。你可以选择任何一种部署选项。在这里,我们选择“pythonAnywhere”。转到 pythonAnywhere 网站并注册(如果尚未注册)。单击 “Add a new web app” 并填写所有凭据(选择 web2py 应用程序)。大功告成。
Now if you want to deploy your app on cloud platform, come back to your home page and click on the site. You can choose any option for deployment. Here, we choose “pythonAnywhere”. Go to pythonAnywhere website and register yourself (if not already done). Click on “Add a new web app” and fill all the credentials (Choose web2py app). All done.
现在,转到 https://username.pythonanywhere.com/welcome/default/index ,单击 admin 标签(输入密码)。然后单击上传并安装打包的应用程序。按如下内容填写凭据并单击安装。
Now go to https://username.pythonanywhere.com/welcome/default/index, click on admin tab (enter password). Next click on upload and install packed application. Fill the credentials as below and click install.

一切都完成后,将出现一个如下所示的弹出消息 −
Once everything is done, a pop-up message will appear as given below −

现在,要查看你的应用程序,请打开以下链接 −
Now to view your app, open the below link −
https://username.pythonanywhere.com/welcome/default/index and you can see the following screen −

我们的第一个 web2py 应用程序已成功创建并部署。
Our first web2py application is successfully created and deployed.
总而言之,Web2py 是一种免费、快速、安全的 web 开发框架,完全用 python 编写,并且鼓励在各个方面(模型、视图、控制器)使用 python。这是一个非常适合小型 web 应用程序或原型的框架,但无法达到企业级质量要求。原因在于,在企业级应用程序中,由于缺乏单元测试、良好准确的错误报告和分散的模型,解决 bug 的复杂度将呈指数级增长。
To summarize, Web2py is a free, fast, secure web development framework that is entirely written in python and encourages using python in every way possible (model, view, controller). It is a very good framework for small web applications or prototypes but fails to fulfil the enterprise class quality requirements. It is because, in an enterprise level application, the complexity of solving bugs will increase exponentially because of the lack of unit tests, good and accurate error reporting and scattered model.
Pyramid Framework
Pyramid 是一个通用、开源的 web 应用程序开发框架,用 python 构建。它允许 python 开发人员轻松创建 web 应用程序。
Pyramid is a general, open source, web application development framework built in python. It allows python developer to create web applications with ease.
Installing, starting up and configuring
正如所描述的,“从小开始,大功告成,坚持到底的框架”,Pyramid 非常像 Flask,安装和运行时只需要很少的工作。事实上,一旦你开始构建这个应用程序,你就会发现其中的一些模式类似于 Flask。
As described, “the start small, finish big, stay finished framework”, Pyramid is much like Flask which takes very little effort to install and run. In fact, you’ll recognize that some of the patterns are similar to Flask once you start building this application.
以下是创建 Pyramid 框架环境的步骤:
Following are the steps to create pyramid framework environment −
-
First, create a project directory. Here, we have created a directory named pyramidProject (you can choose any name you want).
-
Next, create a virtual environment where you will install all the project specific dependencies. Here, we created a virtual environment folder named pyramidEnv where Pyramid is installed.
-
Then, go to the directory, pyramidEnv and install the pyramid with pip install pyramid.
完成上述所有操作后,你的目录结构如下所示:
Once everything is done as mentioned above, your directory structure will be as shown below −

系统中安装的 Pyramid 版本如下所示:
And the pyramid version installed in the system is given below −

Core Concepts
Pyramid 框架基于以下核心概念:
The Pyramid framework is based on below core concepts −
-
Zope (extensibility, traversal, declarative security) − Pyramid is loosely based on Zope in terms of extensibility, the concept of traversal and the declarative security.
-
Pylons (URL dispatch, non-opinionated view of persistence, templating, etc.) − Another area from where pyramid draws its concept is the pylons project. Pylons have that concept of routes, that calls the URL dispatch inside the pyramid framework and they also have the non-opinionated view of persistence layer or templating.
-
Django (View, level of documentation) − Pyramid also gets hint from Django. The way we take our view, routed our URL and the level of documentation is very Django way.
以下是 Pyramid 框架的功能:
The following are the features of the Pyramid framework −
-
It is the fastest known Python web framework.
-
It supports small and large projects (why rewrite when you outgrow your small framework).
-
It supports single file webapps like microframeworks.
-
It has built-in sessions.
-
It supports events similar to Plone/Zope.
-
It provides Transaction Management (if already have noticed that we have used Zope before).
Configuration
配置是影响应用程序操作的设置。配置 Pyramid 应用程序有两种方法:命令式配置和声明式配置。
Configuration is the settings that influence the operation of an application. There are two ways to configure a pyramid application: imperative configuration and declarative configuration.
Pyramid 配置支持:
Pyramid configuration supports −
-
Imperative configuration or even the overriding of the decorator-based configs
-
Configuration conflict detection (including more local vs. less local determination)
-
Configuration Extensibility (included from multiple apps)
-
Flexible Authentication and Authorization Policies
-
Programmatic Introspection of Configuration (view current state of routes to generate nav)
URL generation
在金字塔中,我们可以为路径、资源和静态资源生成 URL。使用 URL 生成 API 既容易又灵活。通过金字塔的多个 API 生成 URL,用户可以任意更改配置,而不必担心破坏任何网页的链接。
In pyramid, we can generate URLs for routes, resources and static assets. It is easy and flexible to work with URL generation APIs. By generating URLs through pyramid’s various APIs, users can change the configuration arbitrarily without much worry of breaking a link with any of your web pages.
简而言之,金字塔中的 URL −
So in short, URL in pyramid −
-
supports URL generation to allow changes to app that won’t break links.
-
generates URLs to static resources that live either inside or outside the application.
-
supports Routes and Traversal.
Views
金字塔的主要任务之一是在请求到达应用程序时查找并调用视图可调用对象。视图可调用对象是在对应用程序中的请求做出响应时执行一些有趣操作的代码片段。
One of the primary jobs of pyramid is to find and invoke a view callable when a request reaches your application. View callables are bits of code which do something interesting in response to a request made in your application.
在将视图映射到 URL 调度或 Python 代码时,可以进行任何类型的调用。视图可以是函数声明或实例,可以在金字塔中用作视图。
When you map your views onto your URL dispatch or python code, there can be any kind of call. Views can be a function declaration or an instance, it can be used as a view in the pyramid.
下面给出视图的一些重要要点:
Some important points about Views are given below −
-
Views are generated from any callable.
-
Renderer based views can simply return dictionaries (not required to return a webby style object).
-
Support multiple views per route (GET vs. POST vs. HTTP Header check, etc.).
-
View response adapters (when you want to specify how view returns values should be handled vs. response objects).
Extensibility
金字塔的设计考虑了可扩展性。因此,如果金字塔开发人员在构建应用程序时牢记某些约束,第三方应该能够在无需修改源代码的情况下更改应用程序的行为。遵守某些约束的金字塔应用程序的行为可以在不进行任何修改的情况下进行覆盖或扩展。它设计用于针对多个环境的灵活部署(无单例)。金字塔具有“Tweens”中间件支持(WSGI 中间件,但在金字塔本身的上下文中运行)。
Pyramid is designed with extensibility in mind. So if a pyramid developer is keeping in mind certain constraints while building an application, a third party should be able to change the application’s behaviour without needing to modify its source code. The behaviour of a pyramid application that obeys certain constraints can be overridden or extended without any modification. It is designed for flexible deployments to multiple environments (No Singletons). Pyramid has “Tweens” middleware support (WSGI middle ware, but runs in the context of Pyramid itself).
Running a Hello, Pyramid Program
在安装金字塔框架以检查一切都运行良好之后,我们可以想到的最简单的程序是运行一个简单的“Hello, World”或“Hello, Pyramid”程序。
The simplest program we can think after installing pyramid framework to check if everything is working fine, is to run a simple “Hello, World” or “Hello, Pyramid” program.
下面是我在端口号 8000 上运行的金字塔“Hello, Pyramid”程序:
Below is my pyramid “Hello, Pyramid” program on 8000 port number −

上面的示例很容易运行。将此保存为 app.py(在此,我们给出了名称 pyramid_helloW.py)。
Above simple example is easy to run. Save this as app.py (In this, we have given the name pyramid_helloW.py).
运行最简单的程序:-
Running the simplest program: −

接下来,在浏览器中打开 http://localhost:8000/ ,您将看到 Hello, Pyramid! 消息如下所示 −
Next, open http://localhost:8000/ in a browser, and you will see the Hello, Pyramid! Message as follows −

以下是上述代码的说明 −
The following is the explanation for above code −
Line no. 1-3
在文件开头,我们有 import 语句。第一行导入 make_server 函数,该函数可以创建一个简单的 Web 服务器,当它传递给应用程序时。第二行和第三行从 pyramid 导入配置和响应函数。这些函数分别用于配置详细信息、设置应用程序的参数以及响应请求。
At the head of the file, we have import statements. The first line imports make_server function, which can create a simple web server when it is passed to an application. The second and third line import the configuration and Response function from pyramid. These functions are used to configure details and set parameters for the application and respond to requests, respectively.
Line no. 5-6
现在,我们有一个名为 hello_world 的函数定义。实现生成响应的视图代码。满足视图要求的函数负责呈现将传递回请求实体的文本。在上述情况下,该函数在调用时使用我们之前导入的响应函数。这会回传一个应该提供给客户端的值。
Now we have a function definition called hello_world. Implement view code that generates the response. A function that fulfils the requirement of a view is responsible for rendering the text that will be passed back to the requesting entity. In the above case, the function, when called, uses the Response function we imported earlier. This passes back a value that should be given to the client.
Line no. 8
if name == ‘ main ’:Python 在从命令行运行时会说“从这里开始”,而不是在导入此模块时。
if name == ‘main’: Python is saying, “Start here when running from the command line”, rather than when this module is imported.
Line no. 9-11
在第 9 行中,我们创建一个名为 config 的变量,该变量来自我们在程序顶部导入的配置器函数创建的对象。第 10 行和第 11 行调用此对象的 add_route 和 add_view 方法。此方法用于定义应用程序可以使用的视图。正如我们所看到的,我们传递了我们之前定义的 hello_world 函数。这是该函数实际上作为视图被合并的地方。
In line no. 9, we create a variable called config out of the object created by the configurator function that we imported at the top of the program. Line 10 and 11 call the add_route and add_view method of this object. This method is used to define a view that can be used by the application. As we can see, we pass the hello_world function we defined earlier. This is where that function is actually incorporated as a view.
Line no. 12-14
在此,我们实际上通过调用配置对象的 make_wsgi_app 方法来创建 WSGI 应用程序。这使用对象的属性(例如,我们添加的视图)来创建一个应用程序。然后将此应用程序传递给我们在导入时导入的 make_server 函数,以创建一个可以启动 Web 服务器来为我们的应用程序提供服务的对象。最后一行启动此服务器。
In this, we actually create the WSGI application by calling the make_wsgi_app method of the config object. This uses the object’s attributes, such as the view we added, to create an application. This application is then passed to the make_server function we imported in order to create an object that can launch a web server to serve our application. The last line launches this server.
我们的 hello world application 是最简单、最容易使用的金字塔应用程序之一,配置为“命令式”。它是必要的,因为我们在执行配置任务时可以使用 Python 的全部功能。
Our hello world application is one of the simplest and easiest possible pyramid applications, configured “imperatively”. It is imperative because the full power of Python is available to us as we perform configuration tasks.
总之,Pyramid 是一个拥有庞大且活跃社区的开源 Python Web 框架。这个大型社区为使 Python Web 框架流行且相关做出了贡献。Pyramid Web 框架通过提供一组健壮的功能和工具简化并加速了 Web 应用程序的开发。
To summarize, Pyramid is an open source python web framework with a large and active community. This large community contributes towards making the python web framework popular and relevant. Pyramid web framework simplify and accelerate web application development by providing a set of robust features and tools.
Dash Framework
在本章中,我们将详细讨论 Dash 框架。
In this chapter, we will discuss about the Dash framework in detail.
Dash 是一个用于构建分析性 Web 应用程序的开源 Python 框架。它是一个强大的库,简化了数据驱动的应用程序的开发。对于那些不太熟悉 Web 开发的 Python 数据科学家而言,它特别有用。用户可以使用 Dash 在其浏览器中创建出色的仪表板。
Dash is an open-source Python framework used for building analytical web applications. It is a powerful library that simplifies the development of data-driven applications. It’s especially useful for Python data scientists who aren’t very familiar with web development. Users can create amazing dashboards in their browser using dash.
基于 Plotly.js、React 和 Flask 构建,Dash 将现代 UI 元素(如下拉菜单、滑块和图形)直接连接到您的分析 Python 代码。
Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders and graphs directly to your analytical python code.
Dash 应用程序包括一个 Flask 服务器,该服务器使用 HTTP 请求通过 JSON 数据包与前端 React 组件通信。
Dash apps consist of a Flask server that communicates with front-end React components using JSON packets over HTTP requests.
Dash 应用程序完全用 Python 编写,因此不需要 HTML 或 JavaScript。
Dash applications are written purely in python, so NO HTML or JavaScript is necessary.
Dash Setup
如果您的终端中尚未安装 Dash,请安装下面提到的 Dash 库。由于这些库处于活动开发阶段,因此请经常安装和升级库。Python 2 和 3 也受支持。
If Dash is not already installed in your terminal, then install the below mentioned Dash libraries. As these libraries are under active development, install and upgrade then frequently. Python 2 and 3 are also supported.
-
pip install dash==0.23.1 # The core dash backend
-
pip install dash-renderer==0.13.0 # The dash front-end
-
pip install dash-html-components==0.11.0 # HTML components
-
pip install dash-core-components==0.26.0 # Supercharged components
-
pip install plotly==3.1.0 # Plotly graphing library
为了确保一切正常工作,我们在这里创建了一个简单的 dashApp.py 文件。
In order to make sure everything is working properly, here, we created a simple dashApp.py file.
Dash or App Layout
Dash 应用程序由两部分组成。第一部分是应用程序的“布局”,它基本上描述了应用程序的外观。第二部分描述了应用程序的交互性。
Dash apps are composed of two parts. The first part is the “layout” of the app which basically describes how the application looks like. The second part describes the interactivity of the application.
Core Components
我们可以用 dash_html_components 和 dash_core_components 库构建布局。Dash 提供了应用程序所有可视化组件的 Python 类。我们还可以用 JavaScript 和 React.js 来自定义我们自己的组件。
We can build the layout with the dash_html_components and the dash_core_components library. Dash provides python classes for all the visual components of the application. We can also customize our own components with JavaScript and React.js.
import dash_core_components as dcc
import dash_html_components as html
dash_html_components 是用于所有 HTML 标签的,而 dash_core_components 用于使用 React.js 构建的交互性。
The dash_html_components is for all HTML tags where the dash_core_components is for interactivity built with React.js.
使用上述这两个库,我们来编写如下所示的代码:
Using above two libraries, let us write a code as given below −
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''Dash Framework: A web application framework for Python.''')
相应的 HTML 代码将类似如下所示:
And the equivalent HTML code would look like this −
<div>
<h1> Hello Dash </h1>
<div> Dash Framework: A web application framework for Python. </div>
</div>
Writing Simple Dash app
我们将在文件 dashApp.py 中学习如何使用上述库编写一个简单的 Dash 示例。
We will learn how to write a simple example on dash using above mentioned library in a file dashApp.py.
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''Dash Framework: A web application framework for Python.'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
Running the Dash app
在运行 Dash 应用程序时,请注意以下几点:
Note the following points while running the Dash app.
(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py
-
Serving Flask app "dashApp1" (lazy loading)
-
Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.
-
Debug mode: on
-
Restarting with stat
-
Debugger is active!
-
Debugger PIN: 130-303-947
-
Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)
127.0.0.1 - - [12/Aug/2018 09:32:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET /favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:39:52] "GET /favicon.ico HTTP/1.1" 200 -
在您的网络浏览器中访问 http:127.0.0.1:8050/ 。您应该会看到一个类似于此的应用程序。
Visit http:127.0.0.1:8050/ in your web browser. You should see an app that looks like this.

在上述程序中,需要特别注意以下几点:
In above program, few important points to be noted are as follows −
-
The app layout is composed of a tree of “components” like html.Div and dcc.Graph.
-
The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application.
-
Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library.
-
Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes.
-
The children property is special. By convention, it’s always the first attribute which means that you can omit it.
-
Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’).
-
The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice − app.css.append_css ({“external_url”:*https://codepen.io/chriddyp/pen/bwLwgP.css*}) to get your file to get the same look and feel of these examples.
More about HTML
dash_html_compoments 库包含一个用于所有 HTML 标签的组件类,以及所有 HTML 参数的关键字参数。
The dash_html_components library contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments.
让我们在先前应用文本中添加组件的内联样式 -
Let us add the inline style of the components in our previous app text −
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
colors = {
'background': '#87D653',
'text': '#ff0033'
}
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(
children='Hello Dash',
style={
'textAlign': 'center',
'color': colors['text']
}
),
html.Div(children='Dash: A web application framework for Python.', style={
'textAlign': 'center',
'color': colors['text']
}),
dcc.Graph(
id='example-graph-2',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
],
'layout': {
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background'],
'font': {
'color': colors['text']
}
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
在上面的示例中,我们使用 style 属性修改了 html.Div 和 html.H1 组件的内联样式。
In the above example, we modified the inline styles of the html.Div and html.H1 components with the style property.

它在 Dash 应用程序中被渲染如下 -
It is rendered in the Dash application as follows −

dash_html_components 和 HTML 属性有一些关键区别 -
There are couple of key distinctions between dash_html_components and HTML attributes −
-
For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string.
-
Style dictionary keys are camelCased, so text-align changes to textalign.
-
ClassName in Dash is similar to HTML class attribute.
-
The first argument is the children of the HTML tag which is specified through the children keyword argument.
Reusable Components
通过用 Python 编写我们的标记,我们可以创建复杂的、可重用的组件(比如表格),而无需切换上下文或语言 -
By writing our markup in Python, we can create complex reusable components like tables without switching contexts or languages −
下面是一个快速示例,它从 pandas 数据框生成一个“表格”。
Below is a quick example that generates a “Table” from pandas dataframe.
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/'
'c78bf172206ce24f77d6363a2d754b59/raw/'
'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
'usa-agricultural-exports-2011.csv')
def generate_table(dataframe, max_rows=10):
return html.Table(
# Header
[html.Tr([html.Th(col) for col in dataframe.columns])] +
# Body
[html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
]) for i in range(min(len(dataframe), max_rows))]
)
app = dash.Dash()
app.layout = html.Div(children=[
html.H4(children='US Agriculture Exports (2011)'),
generate_table(df)
])
if __name__ == '__main__':
app.run_server(debug=True)
我们的输出将类似于 -
Our output will be something like −

More about Visualization
dash_core_components 库包含一个名为 Graph 的组件。
The dash_core_components library includes a component called Graph.
Graph 使用开源 plotly.js JavaScript 绘图库呈现交互式数据可视化。Plotly.js 支持约 35 种图表类型,并在矢量质量 SVG 和高性能 WebGL 中呈现图表。
Graph renders interactive data visualizations using the open source plotly.js JavaScript graphing library. Plotly.js support around 35 chart types and renders charts in both vector-quality SVG and high-performance WebGL.
下面是一个从 Pandas 数据框创建散点图的示例 -
Below is an example that creates a scatter plot from a Pandas dataframe −
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
app = dash.Dash()
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
'gdp-life-exp-2007.csv')
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x=df[df['continent'] == i]['gdp per capita'],
y=df[df['continent'] == i]['life expectancy'],
text=df[df['continent'] == i]['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
if __name__ == '__main__':
app.run_server()
以上代码的输出如下所示 -
The output of the above code is as follows −

这些图形是交互式的和响应式的。你可以将鼠标悬停在点上以查看其值,单击图例项以切换迹线,单击并拖动进行缩放,按住 shift 并单击并拖动进行平移。
These graphs are interactive and responsive. You can hover over points to see their values, click on legend items to toggle traces, click and drag to zoom, hold down shift, and click and drag to pan.
Markdown
当 dash 通过 dash_html_components 库展现 HTML 风格时,用 HTML 编写副本可能很乏味。对于书写文本块,你可以在 dash_core_components 库中使用 Markdown 组件。
While dash exposes HTML flavours through the dash_html_components library, it can be tedious to write your copy in HTML. For writing blocks of texts, you can use the Markdown component in the dash_core_components library.
Core Components
dash_core_components 包含一组更高级别的组件,如下拉菜单、图形、markdown、块等等。
The dash_core_components includes a set of higher-level components like dropdowns, graphs, markdown, blocks and many more.
与其他所有 Dash 组件一样,它们是完全声明式描述的。每个可配置选项都作为组件的关键字参数提供。
Like all other Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component.
下面是这个示例,用到了一些可用的组件−
Below is the example, using some of the available components −
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
html.Label('Dropdown'),
dcc.Dropdown(
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': u'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
value='MTL'
),
html.Label('Multi-Select Dropdown'),
dcc.Dropdown(
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': u'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
value=['MTL', 'SF'],
multi=True
),
html.Label('Radio Items'),
dcc.RadioItems(
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': u'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
value='MTL'
),
html.Label('Checkboxes'),
dcc.Checklist(
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': u'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
values=['MTL', 'SF']
),
html.Label('Text Input'),
dcc.Input(value='MTL', type='text'),
html.Label('Slider'),
dcc.Slider(
min=0,
max=9,
marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
value=5,
),
], style={'columnCount': 2})
if __name__ == '__main__':
app.run_server(debug=True)
以上程序的输出如下−
Output from the above program is as follows −

Calling Help
Dash 组件是声明式的。在安装时,这些组件的每一个可配置方面均作为关键字参数设置。你可以在你的 Python 控制台中,在组件上调用帮助来学习更多关于一个组件和它的可用参数的信息。其中一些信息如下−
Dash components are declarative. Every configurable aspect of these components is set during installation as a keyword argument. You can call help in your python console on any of the components to learn more about a component and its available arguments. Some of them are given below −
>>> help(dcc.Dropdown)
Help on class Dropdown in module builtins:
class Dropdown(dash.development.base_component.Component)
| A Dropdown component.
| Dropdown is an interactive dropdown element for selecting one or more
| items.
| The values and labels of the dropdown items are specified in the `options`
| property and the selected item(s) are specified with the `value` property.
|
| Use a dropdown when you have many options (more than 5) or when you are
| constrained for space. Otherwise, you can use RadioItems or a Checklist,
| which have the benefit of showing the users all of the items at once.
|
| Keyword arguments:
| - id (string; optional)
| - options (list; optional): An array of options
| - value (string | list; optional): The value of the input. If `multi` is false (the default)
-- More --
总之,Dash 应用程序的布局描述了应用程序的外观。布局是一个组件的层级树。dash_html_components 库为所有 HTML 标签和关键字参数提供了类,描述了 HTML 属性,如样式、类名和 id。dash_core_components 库生成了高级组件,如控件和图表。
To summarize, the layout of a Dash app describes what the app looks like. The layout is a hierarchical tree of components. The dash_html_components library provides classes for all the HTML tags and the keyword arguments, and describes the HTML attributes like style, className, and id. The dash_core_components library generates higher-level components like controls and graphs.
Choosing a Better Framework
Python Web 框架的世界提供了多种选择。一些需要考虑的主要框架有 Django、Flask、Bottle、Diesel、Web2py、Pyramid、Falcon、Pecan 等,它们争夺开发人员的心智份额。Pyramid、Django、Web2py 和 Flask 等框架凭借它们的优缺点清单是理想的;为您的项目选择一个框架是一项艰难的选择。
The world of Python web frameworks provides lots of choices. Some of the prominent frameworks to consider are Django, Flask, Bottle, Diesel, Web2py, Pyramid, Falcon, Pecan, etc., that compete for the developer mindshare. Frameworks like Pyramid, Django, Web2py and Flask are ideal with their list of pros and cons; choosing just one for your project is a difficult choice to make.
Dash 完全设计用于满足不同的需求集。因此,作为开发人员,您希望将大量的选项减少到一个选项,该选项将帮助您按时完美地完成项目。
Dash is entirely designed for different set of needs. So, as a developer you want to cut the legions of options down to the one that will help you finish your project on time and with perfection.
如果比较 Flask、Pyramid 和 Django 框架,Flask 是一个微框架,主要针对具有较简单要求的小型应用程序,而 Pyramid 和 Django 都针对较大的应用程序。Pyramid 是以灵活性和自由为理念构建的,因此开发人员拥有适合该项目的正确工具。在金字塔的情况下,开发人员可以自由选择数据库、URL 结构、模板化样式等等。但 Django 包括 Web 应用程序所需的所有电池,所以我们只需要安装 Django 就可以开始工作了。
If we compare Flask, Pyramid and Django frameworks, Flask is a micro-framework primarily aimed at small applications with simpler requirements whereas Pyramid and Django are both aimed at larger applications. Pyramid is built with flexibility and freedom in mind, so the developer has right tools for the project. In case of pyramid, the developer is free to choose the database, URL structure, templating style and more. However, Django includes all the batteries a web application needs, so we just need to install Django and start working.
Django 带有一个 ORM,而 Pyramid 和 Flask 让开发人员自己选择如何(或是否)存储他们的数据。一般来说,迄今为止,最常见的非 Django Web 应用程序 ORM 是 SQLAlchemy,但是其他选项可以是 DjangoDB、MongoDB、LevelDB 和 SQLite。
Django comes with an ORM, whereas Pyramid and Flask leave it to the developer to choose how (or if) they want their data to be stored. Generally, the most common ORM for non-Django web applications is SQLAlchemy by far, however, other options can be DjangoDB, MongoDB, LevelDB and SQLite.
作为一名开发人员,如果我必须在我的项目中选择 Django 和 Web2py,我需要了解这两个框架的优点和缺点。因此,让我们比较 Django 和 Web2py −
Being a developer, if I have to choose between Django and Web2py for my project. I need to have some idea of both the frameworks’ benefits and limitations. So let us compare Django and Web2py −
Django
Django 的社区是一个大优势。这对开发人员来说实际上意味着资源财富将更大。具体来说,这归结为 −
The community of Django is a big plus. This actually means to a developer is the wealth of resources will be greater. Specifically, this comes down to −
-
Documentation
-
Open source resources
-
Third-party apps support
-
Deployment support
-
IRC channels with helpful developers
Django 拥有非常庞大的开发团队和文档社区。当我们处理编写复杂的后台时,它是一个合适的框架,因为它提供了许多第三方应用程序,可以让您像自动化用户逻辑(注册、身份验证)、异步任务、API 创建、博客等事情。
Django has a very big community of development team and documentation. It is the right framework when we are dealing with writing a complex backend as it provides a lot of third party apps that lets you automate things like user’s logic (signup, authentication), asynchronous tasks, API creation, blogs, etc.
Web2py
Web2py 很适合快速开发简单的 Web 应用程序或 http 服务器。以下是 Web2py 的一些优点和局限性。
Web2py is a good fit to fast development of simple web apps or http servers. Below are some of the benefits and limitations of web2py.
Benefits of Web2py
以下是 Web2py 框架的一些优点 -
The following are some of the benefits of Web2py framework −
-
Web2py is a potential framework when compared to Django and Flask in terms of speed and simplicity of the development. As Web2py uses python-based template language, this allows python developers to start writing code immediately after understanding the basics of writing template as views.
-
Web2py can run python compiled code as an optimization to lower the running time and to allow you to distribute your code in a compiled fashion.
Limitations of Web2py
以下是该框架的一些限制:
The following are some of the limitations of the framework:
-
Web2py supports doctests, however it does not support unit testing. Now doctests are not the optimal choice because of their limited scope.
-
There is no differentiation between production and development mode. In case an exception occurred, ticket is generated all the times and you will have to navigate to the ticket to check the error. This might be helpful in case of production server but will be difficult in development environment as developers really need to see the error instantly rather than checking the ticket number.
-
Web2py has a good database abstraction layer (DAL) that allows you to abstract many types of database engines but it lacks powerful ORM. In case you are dealing with relatively large model, your code will get scattered by all nested definitions and attributes which makes things complicated.
-
We cannot use standard python development tools without modifications as web2py has really poor IDE support.
Django 和 Web2py 框架是全栈框架。这意味着它们提供了所需的所有代码 - 从表单生成器到模板布局和表单验证,让您可以根据您的特定需求编写内容。
The Django and Web2py framework are full stack frameworks. This means they provide all the code needed − from form generators to templating layouts and forms validation, and leave you to write things according to your specific needs.
然而对于 Flask 和 Pyramid 等非栈框架,如果您想创建一个功能齐全的网站,则需要自己添加大量代码和额外位。这需要大量的技能和时间。
However, with the non-stack frameworks like Flask and Pyramid, if you want to create a full-featured website, you will need to add a lot of code and extra bits yourself. This takes lot of skill and time.
Dash
Dash 完全设计用于执行为仪表板构建反应式框架的特定任务。Plotly 的 Dash 是让 Python 开发人员不必学习 Javascript 和前端 Web 开发即可创建交互式 Web 应用程序的绝佳方式。Dash 构建在 Flask、Plotly.js、React 和 React Js 之上。
Dash is entirely designed for specific task of building a reactive framework for dashboards. Dash by Plotly is a great way for the python developer to create interactive web apps without having to learn Javascript and front end web development. Dash is built on top of Flask, Plotly.js, React and React Js.
由于属于不同类别的框架,因此 Dash 与其他框架(如上所述)之间没有可比性。以下是一些在其他交互式仪表盘框架(Jupiter Dashboards、matplotlib 以及其他框架)中更喜欢 Dash 的原因 -
There is no comparison between Dash and other frameworks (mentioned above) as they belong to different category of frameworks. Below are some of the reasons to prefer dash over other interactive dashboard frameworks (Jupiter Dashboards, matplotlib and other) −
-
With just 50 lines of code, you can write a simple “hello world” Dash app, as Dash requires very little boilerplater.
-
Entire Dash apps are written in python language, the most preferred language globally.
-
In your own python code, you can bind dash interactive components like dropdown, text inputs, sliders, and graphs with reactive Dash “callbacks”.
-
Complicated UIs in Dash apps can have multiple inputs, multiple outputs and inputs that depends on other inputs.
-
Simultaneously, multiple users can work on Dash apps.
-
For creating your own Dash components with React, dash uses React.js to render components and includes a plugin system.
-
Developers or writers can write dash apps that respond to clicking, hovering or selecting points on the graph as Dash’s Graph components are interactive.
Conclusion
我们可以得出结论,从众多可用的 Python 框架中选择合适的框架完全取决于项目类型、复杂性、小型或企业级项目、可用的社区支持或在线资源、可扩展性、安全性等。
We can conclude that choosing the right framework out of many available python frameworks solely depends on the type of project, complexity, small or enterprise level project, kind of community support available or online resource available, scalability, security, etc.
上面提到的 Python 框架同类最佳,但有各自的优点和缺点(取决于项目需求)。因此,一种类型的框架不适用于所有类型的项目。
The above mentioned python frameworks are best in their class but have their own benefits and drawbacks (depending on the project requirement). So, one type of framework is not suitable for all kinds of projects.