codecamp

Server-side web frameworks

先决条件: 基本的计算机素养。 高级了解服务器端代码如何处理和响应HTTP请求(请参见客户端 - 服务器概述)。
目的: 了解Web框架如何简化服务器端代码的开发/维护,并让读者考虑为自己的开发选择一个框架。

以下部分说明了使用从真实Web框架中提取的代码片段的一些点。 不要担心,所有现在有意义; 我们将通过我们的框架特定模块中的代码来帮助您。

概述

下一部分提供了有关Web框架如何简化Web应用程序开发的更多详细信息。 然后,我们解释一些可用于选择Web框架的标准,然后列出一些选项。

Web框架可以为您做什么?

Web框架提供了工具和库来简化常见的Web开发操作。 您不是使用服务器端网络框架,但强烈建议 - 这将使你的生活更容易。

本节讨论了Web框架常常提供的一些功能(并非每个框架都必须提供所有这些功能!)

直接与HTTP请求和响应一起工作

正如我们在上一篇文章中看到的,Web服务器和浏览器通过HTTP协议进行通信 - 服务器等待来自浏览器的HTTP请求,然后返回HTTP响应中的信息。 Web框架允许您编写简化的语法,生成服务器端代码以处理这些请求和响应。 这意味着你将有一个更容易的工作,与更容易,更高级的代码,而不是低级网络原语交互。

下面的示例显示了如何在Django(Python)Web框架中工作。 每个"视图"函数(请求处理程序)接收包含请求信息的 HttpRequest 对象,并且需要返回带有格式化输出的 HttpResponse 对象 )。

# Django view function
from django.http import HttpResponse

def index(request):
    # Get an HttpRequest (request)
    # perform operations using information from the request.
    # Return HttpResponse
    return HttpResponse('Output string to return')

将请求路由到相应的处理程序

大多数网站会提供多种不同的资源,可通过不同的网址访问。 在一个函数中处理这些都很难维护,因此Web框架提供了简单的机制来将URL模式映射到特定的处理函数。 这种方法在维护方面也有好处,因为您可以更改用于提供特定功能的URL,而无需更改底层代码。

不同的框架使用不同的机制进行映射。 例如,Flask(Python)web框架使用装饰器向视图函数添加路由。

@app.route("/")
def hello():
    return "Hello World!"

虽然Django希望开发人员定义URL模式和视图函数之间的URL映射列表。

urlpatterns = [
    url(r'^$', views.index),
    # example: /best/myteamname/5/
    url(r'^(?P<team_name>\w.+?)/(?P<team_number>[0-9]+)/$', views.best),
]

方便地访问请求中的数据

可以以多种方式在HTTP请求中对数据进行编码。 从服务器获取文件或数据的HTTP GET 请求可能会编码URL参数或URL结构中需要哪些数据。 用于更新服务器上的资源的HTTP POST 请求将在请求的主体内包括更新信息作为"POST数据"。 HTTP请求还可以包括关于客户端侧cookie中的当前会话或用户的信息。

Web框架提供了编程语言适当的机制来访问这些信息。 例如,Django传递给每个视图函数的 HttpRequest 对象包含用于访问目标URL的方法和属性,请求的类型(例如HTTP GET ), > GET POST 参数,cookie和会话数据等。通过在URL映射器中定义"捕获模式",Django还可以传递编码在URL结构中的信息 代码片段在上面的部分)。

抽象和简化数据库访问

网站使用数据库来存储要与用户和用户共享的信息。 Web框架通常提供抽象数据库读取,写入,查询和删除操作的数据库层。 该抽象层被称为对象关系映射器(ORM)。

使用ORM有两个好处:

  • You can replace the underlying database without necessarily needing to change the code that uses it. This allows developers to optimise for the characteristics of different databases based on their usage.
  • Basic validation of data can be implemented within the framework. This makes it easier and safer to check that data is stored in the correct type of database field, has the corrrect format (e.g. an email address), and isn't malicious in any way (crackers can use certain patterns of code to do bad things such as deleting database records).

例如,Django web框架提供了一个ORM,并且将用于定义记录结构的对象称为模型 模型指定要存储的字段类型,其可以提供对可以存储什么信息(例如,电子邮件字段将仅允许有效的电子邮件地址)的字段级验证。 字段定义还可以指定它们的最大大小,默认值,选择列表选项,文档的帮助文本,表单的标签文本等。模型不陈述关于底层数据库的任何信息,因为这是可以改变的配置设置 分开我们的代码。

下面的第一个代码片段为 Team 对象显示了一个非常简单的Django模型。 这将团队名称和团队级别存储为字符字段,并指定要为每个记录存储的最大字符数。 team_level 是一个选择字段,因此我们还提供了要显示的选择和要存储的数据之间的映射以及默认值。

#best/models.py

from django.db import models 

class Team(models.Model): 
    team_name = models.CharField(max_length=40) 

    TEAM_LEVELS = (
        ('U09', 'Under 09s'),
        ('U10', 'Under 10s'),
        ('U11, 'Under 11s'),
        ...  #list our other teams
    )
    team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11')

Django模型提供了一个用于搜索数据库的简单查询API。 这可以使用不同的标准(例如,精确,不区分大小,大于等)一次匹配多个字段,并且可以支持复杂语句(例如,您可以在具有团队的U11团队上指定搜索 以"Fr"开头或以"al"结尾的名称)。

第二个代码片段显示了一个用于显示所有U09团队的视图函数(资源处理程序)。 在这种情况下,我们指定要过滤所有记录,其中 team_level 字段正好是文本\'U09\'(请注意下面如何将此条件传递给 filter >函数作为参数,字段名称和匹配类型由双下划线分隔: team_level__exact )。

#best/views.py

from django.shortcuts import render
from .models import Team 

def youngest(request):
    list_teams = Team.objects.filter(team_level__exact="U09")
    context = {'youngest_teams': list_teams}
    return render(request, 'best/index.html', context)

渲染数据

Web框架通常提供模板系统。 这些允许您指定输出文档的结构,为生成页面时要添加的数据使用占位符。 模板通常用于创建HTML,但也可以创建其他类型的文档。

Web框架通常提供一种机制,可以轻松地从存储的数据生成其他格式,包括 JSON 和 XML

例如,Django模板系统允许您使用"双句柄"语法(例如 { { variable_name } } ),它将被渲染页面时从视图函数传递的值替换。 模板系统还支持表达式(具有语法: {% expression %} ),允许模板执行简单操作,例如迭代传递到模板中的列表值。

注意:许多其他模板系统使用类似的语法,例如:Jinja2(Python),handlebars(JavaScript),mustache(JavaScript)等。

下面的代码段显示了如何工作。 继续上一节中的"最新团队"示例,HTML模板通过视图传递一个名为 youngest_teams 的列表变量。 在HTML框架内部,我们有一个表达式,首先检查 youngest_teams 变量是否存在,然后在 for 循环中迭代它。 在每次迭代时,模板在列表项中显示团队的 team_name 值。

#best/templates/best/index.html

<!DOCTYPE html>
<html lang="en">
<body>

 {% if youngest_teams %}
    <ul>
    {% for team in youngest_teams %}
        <li>{{ team.team_name }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No teams are available.</p>
{% endif %}

</body>
</html>

如何选择Web框架

许多Web框架存在几乎每一种可能需要使用的编程语言(我们列出了几个更流行的框架在下一节)。 有了这么多的选择,它可能变得难以确定什么框架为您的新的Web应用程序提供了最好的起点。

可能影响您决定的一些因素是:

  • Effort to learn: The effort to learn a web framework depends on how familiar you are with the underlying programming language, the consistency of its API, the quality of its documentation, and the size and activity of its community. If you're starting from absolutely no programming experience then consider Django (it is one of the easiest to learn based on the above criteria). If you are part of a development team that already has significant experience with a particular web framework or programming language, then it makes sense to stick with that.
  • Productivity: Productivity is a measure of how quickly you can create new features once you are familiar with the framework, and includes both the effort to write and maintain code (since you can't write new features while old ones are broken). Many of the factors affecting productivity are similar to those for "Effort to learn" — e.g. documentation, community, programming experience, etc. — other factors include:
    • Framework purpose/origin: Some web frameworks were initially created to solve certain types of problems, and remain better at creating web apps with similar constraints. For example, Django was created to support development of a newspaper website, so is good for blogs and other sites that involve publishing things. By contrast, Flask is a much lighter-weight framework and is great for creating web apps running on embedded devices.
    • Opinionated vs unopinionated: An opinionated framework is one in which there are recommended "best" ways to solve a particular problem. Opinionated frameworks tend to be more productive when you're trying to solve common problems, because they lead you in the right direction, however they are sometimes less flexible.
    • Batteries included vs. get it yourself: Some web frameworks include tools/libraries that address every problem their developers can think "by default", while more lightweight frameworks expect web developers to pick and choose solution to problems from separate libraries (Django is an example of the former, while Flask is an example of a very light-weight framework). Frameworks that include everything are often easier to get started with because you already have everything you need, and the chances are that it is well integrated and well documented. However if a smaller framework has everything you (will ever) need then it can run in more constrained environments and will have a smaller and easier subset of things to learn.
    • Whether or not the framework encourages good development practices: For example, a framework that encourages a Model-View-Controller architecture to separate code into logical functions will result in more maintainable code than one that has no expectations on developers. Similarly, framework design can have a large impact on how easy it is to test and re-use code.
  • Performance of the framework/programming language: Usually "speed" is not the biggest factor in selection because even relatively slow runtimes like Python are more than "good enough" for mid-sized sites running on moderate hardware. The perceived speed benefits of another language, e.g. C++ or JavaScript, may well be offset by the costs of learning and maintenance.
  • Caching support: As your website becomes more successful then you may find that it can no longer cope with the number of requests it is receiving as users access it. At this point you may consider adding support for caching. Caching is an optimisation where you store all or part of a web request so that it does not have to be recalculated on subsequent requests. Returning a cached request is much faster than calculating one in the first place. Caching can be implemented in your code or in the server (see reverse proxy). Web frameworks will have different levels of support for defining what content can be cached.
  • Scalability: Once your website is fantastically successful you will exhaust the benefits of caching and even reach the limits of vertical scaling (running your web application on more powerful hardware). At this point you may need to scale horizontally (share the load by distributing your site across a number of web servers and databases) or scale "geographically" because some of your customers are based a long way away from your server. The web framework you choose can make a big difference on how easy it is to scale your site.
  • Web security: Some web frameworks provide better support for handling common web attacks. Django for example sanitises all user input from HTML templates so that user-entered JavaScript cannot be run. Other frameworks provide similar protection, but it is not always enabled by default.

还有许多其他可能的因素,包括许可,无论框架是否在积极发展等。

如果你是编程的绝对初学者,那么你可能会选择基于"易于学习"的框架。 除了语言本身的"易用性"之外,高质量的文档/教程和活跃的社区帮助新用户是您最宝贵的资源。 我们选择了 Django (Python)和 ="external"> Express (Node / JavaScript)在后面的课程中写我们的例子,主要是因为它们容易学习和有良好的支持。

注意:让我们访问 Django (Python)和 ="http://expressjs.com/"class ="external"> Express (Node / JavaScript),并查看他们的文档和社区。

  1. Nativate to the main sites (linked above)
    • Click on the Documentation menu links (named things like "Documentation, Guide, API Reference, Getting Started".
    • Can you see topics showing how to set up URL routing, templates, and databases/models?
    • Are the documents clear
  2. Navigate to mailing lists for each site (accessible from Community links).
    • How many questions have been posted in the last few days
    • How many have responses.
    • Do they have an active community?

几个好的网络框架?

让我们继续,讨论几个特定的服务器端Web框架。

下面的服务器端框架代表了写作时最流行的几个 他们都有你需要的一切,以生产力 - 他们是开源,正在积极发展,有热情的社区创建文档和帮助用户讨论板,并用于大量的高调网站。 有许多其他伟大的服务器端框架,你可以使用基本的互联网搜索发现。

注意:说明来自(部分)来自框架网站!

Django(Python)

Django 是一个高级Python Web框架,它鼓励快速开发和干净,务实的设计。 由经验丰富的开发人员构建,它需要处理大量的网络开发麻烦,所以你可以专注于编写你的应用程序,而不需要重新发明轮子。 它是免费和开源的。

Django遵循"包括电池"的理念,并提供几乎所有大多数开发人员可能想做的"开箱即用"。 因为一切都包括在内,它一起工作,遵循一致的设计原则,并有广泛和最新的文档。 基于Python,Django代码易于阅读和维护。 Django的主要优点是:

Ridiculously fast

Django旨在帮助开发人员尽快将应用程序从概念到完成。

Reassuringly secure

Django认真对待安全性,并帮助开发人员避免许多常见的安全错误。

Exceedingly scalable
Some of the busiest sites on the Web leverage Django’s ability to quickly and flexibly scale.

使用Django(来自Django主页)的热门网站包括:Disqus,Instagram,Knight基金会,MacArthur基金会,Mozilla,国家地理,开放知识基金会,Pinterest,开放堆栈。

Flask(Python)

Flask 是Python的微框架。

虽然简约,Flask可以创建严肃的网站开箱。 它包含开发服务器和调试器,并且包括对 Jinja2 模板,安全Cookie, https://en.wikipedia.org/wiki/Unit_testing"class ="external">单元测试 ="external"> RESTful 请求分派。 它有良好的文档和活跃的社区。

Flask已经变得非常受欢迎,特别是对于需要在小型,资源受限的系统上提供Web服务的开发人员(例如,在 "> Raspberry Pi 无人机控制器等。 )

Express(Node.js / JavaScript)

Express 是一个快速,无庸置疑,灵活和简约的网络框架,用于 en /"class ="external"> Node.js (节点是运行JavaScript的无浏览器环境)。 它为Web和移动应用程序提供了一组强大的功能,并提供了有用的HTTP实用程序方法和中间件

Express非常受欢迎,部分原因是它简化了客户端JavaScript Web程序员在服务器端开发中的迁移,部分是因为它是资源高效的(基础节点环境在线程中使用轻量级多任务,而不是为每个线程创建单独的进程 新的Web请求)。

因为Express是一个简约的Web框架,它不包含您可能想要使用的每个组件(例如,数据库访问和对用户和会话的支持通过独立的库提供)。 有许多优秀的独立组件,但有时可能很难找到,这是最好的特定目的!

许多流行的服务器端和全栈框架(包括服务器端和客户端框架)都基于Express,包括羽毛 ItemsAPI KeystoneJS Kraken external"> LEAN-STACK LoopBack MEAN Sails

许多知名公司使用Express,包括:Uber,Accenture,IBM等(提供了一个列表 ="external">此处)。

Ruby on Rails(Ruby)

Rails (通常称为"Ruby on Rails")是为Ruby编程语言编写的Web框架。

Rails遵循与Django非常相似的设计理念。 像Django一样,它提供了标准机制,用于路由URL,从数据库访问数据,从模板生成HTML并将数据格式化为 ="glossaryLink"> JSON XML 它同样鼓励使用像DRY("不重复自己" - 只写一次代码,如果可能的话),MVC(模型 - 视图控制器)和许多其他设计模式。

由于具体的设计决定和语言的性质,当然有许多差异。

Rails已用于高度重视的网站,包括: Basecamp ://github.com/"class ="external"> GitHub Shopify "https://airbnb.com/"class ="external"> Airbnb Twitch href ="https://soundcloud.com/"class ="external"> SoundCloud Hulu Zendesk Square >,高层

ASP.NET

ASP.NET 是由Microsoft开发的用于构建现代Web应用程序和服务的开源网络框架。 使用ASP.NET,您可以快速创建基于HTML,CSS和JavaScript的网站,扩展它们供数百万用户使用,并轻松添加更复杂的功能,如Web API,数据形式或实时通信。

ASP.NET的区别之一是它建立在公共语言运行时(CLR) ,允许程序员使用任何支持的.NET语言(C#,Visual Basic等)编写ASP.NET代码。 像许多Microsoft产品一样,它受益于优秀的工具(通常是免费的),活跃的开发者社区和精心撰写的文档。

ASP.NET由Microsoft,Xbox.com,Stack Overflow和许多其他人使用。

概要

本文展示了Web框架可以使开发和维护服务器端代码变得更加容易。 它还提供了一些流行框架的高级概述,并讨论了选择Web应用程序框架的标准。 您现在至少应该有一个如何选择一个Web框架为您自己的服务器端开发的想法。 如果没有,那么不要担心 - 稍后我们将给你详细的Django和Express教程,给你一些实际使用web框架的经验。

对于本单元中的下一篇文章,我们将稍微改变方向并考虑网络安全。

Useful string methods
Website security
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }