博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
构建静态服务器_为静态网站构建无服务器联系表
阅读量:2530 次
发布时间:2019-05-11

本文共 18393 字,大约阅读时间需要 61 分钟。

构建静态服务器

介绍 (Introduction)

A few years ago AWS launched static hosting service S3, which was a paradigm shift for hosting static websites. The tech was crystal clear, all the static assets (HTML, CSS, and JS) would reside in an S3 bucket to host your impressive website. A pretty cool idea I personally liked it, really. Had it not been for that super important contact form hosting on S3 would have been cool but your contact form would be a joke unless you had another server in place to service AJAX requests from that form. The moment you had that service ready, the S3 solution wouldn’t appear so attractive at all.

几年前,AWS启动了静态托管服务S3,这是托管静态网站的一种模式转变。 该技术非常清晰,所有静态资产(HTML,CSS和JS)都将驻留在S3存储桶中,以托管您印象深刻的网站。 我个人真的很喜欢这个很棒的主意。 如果不是因为在S3上托管的超重要联系表单不是很酷,但是除非您有其他服务器来处理来自该表单的AJAX请求,否则您的联系表单会很开玩笑。 准备好该服务的那一刻,S3解决方案似乎就不会那么吸引人。

In the age of cutting edge technology, there’s always jaw-dropping innovations around the corner. One of the awesome tech innovation happens to be serverless. Not that there are no servers involved but you can care less about them now. Serverless can be a proper and viable solution to a lot of problems, it is the most perfect solution for your static hosted contact form. Keep reading by the end of this post you will be able to handle your website forms in the most inexpensive and simplest manner possible.

在尖端技术时代,总是有令人corner目结舌的创新指日可待。 令人敬畏的技术创新之一就是无服务器。 并不是说没有服务器,但您现在可以在乎它们。 无服务器可以是解决许多问题的合适且可行的解决方案,它是静态托管联系表单的最完美解决方案。 在本文结尾处继续阅读,您将能够以最便宜和最简单的方式处理您的网站表单。



无服务器框架 (The Serverless Framework)

Serverless is your toolkit for deploying and operating serverless architectures. Focus on your application, not your infrastructure.

无服务器是用于部署和操作无服务器体系结构的工具箱。 关注您的应用程序,而不是基础架构。

The Swiss army knife of Serverless technologies. Serverless Framework is a free and open-source web framework written in Node.js. Serverless was the first framework to be developed for building applications exclusively on AWS Lambda, the serverless computing platform provided by Amazon Web Services. Currently, applications developed with Serverless Framework can be deployed to other FaaS service providers. Here is the list of the Serverless cloud services supported by the Serverless Framework:

无服务器技术的瑞士军刀。 无服务器框架是使用Node.js编写的免费开源Web框架。 Serverless是第一个为专门在AWS Lambda(由Amazon Web Services提供的无服务器计算平台)上构建应用程序而开发的框架。 当前,使用无服务器框架开发的应用程序可以部署到其他FaaS服务提供商。 这是无服务器框架支持的无服务器云服务的列表:



无服务器框架入门 (Getting started with Serverless Framework)

Obviously, you are pretty excited to get started with the Serverless Framework, let’s cut to the chase and start by installing Serverless.

显然,您很高兴开始使用无服务器框架,让我们开始追逐并开始安装无服务器框架。

Setting up Serverless is simple. You need to install it through npm and link it to your AWS account.

设置无服务器很简单。 您需要通过npm安装它并将其链接到您的AWS账户。

1.全局安装无服务器 (1. Installing Serverless Globally)

Time to get hands-on Serverless stuff.

是时候动手实践无服务器的东西了。

$ npm install serverless -g

This command installs Serverless globally on your local machine. The Serverless commands are now available to you from your terminal.

此命令在本地计算机上全局安装无服务器。 现在,您可以从终端上使用无服务器命令。

Note: Running Linux, you may want to run the above command as sudo.

注意:在 Linux上,您可能需要以sudo的身份运行上述命令。

2.在AWS控制台中创建一个IAM用户 (2. Create an IAM user in the AWS Console)

Go to your , you will find the listed below the “Security, Identity & Compliance” group. Inside the IAM dashboard click on the Users tab and click “Add User” button.

转到您的 ,您将在“安全性,身份和合规性”组下面找到 。 在IAM仪表板内,单击“用户”选项卡,然后单击“添加用户”按钮。

Create a new user and allow the user programmatic access by clicking on the Programmatic access checkbox. Next, in the permissions section, you need to add a set of permissions to the user. From the list of available options under the “Attach existing policies directly” check the AdministratorAccess.

创建一个新用户,并允许通过点击程序访问复选框用户编程访问 。 接下来,在权限部分,您需要向用户添加一组权限。 在“直接附加现有策略”下的可用选项列表中,检查AdministratorAccess

After the user is created, you will have access to the users Access Key ID andSecret Access Key. You will be required to use these keys in the next step.

创建用户之后,您将有权访问用户的访问密钥ID秘密访问密钥 。 您将需要在下一步中使用这些键。

Word of Caution: These are the kind of credentials you don’t want to lose even by mistake, remember you have provided AdministratorAccess to this user. The user with AdministratorAccess can do pretty much everything with your AWS account.

警告词:这些是您甚至不希望丢失的凭据,记住您已经为该用户提供了AdministratorAccess 。 具有AdministratorAccess的用户几乎可以使用您的AWS账户执行所有操作。

3.配置无服务器以使用IAM凭据 (3. Configuring Serverless to use IAM Credentials)

Great! With the keys, you can set up Serverless Framework to access your AWS account. Switch to your terminal and use this command to configure Serverless:

大! 使用密钥,您可以设置Serverless Framework来访问您的AWS账户。 切换到您的终端并使用此命令配置无服务器:

$ sls config credentials --provider aws --key xxxxxxxxxxxxxx --secret xxxxxxxxxxxxxx --profile 

Now your Serverless installation knows what account AWS to connect.

现在,您的无服务器安装知道了要连接哪个帐户AWS。

Note: sls is an alias for the serverless command. You can use both to the same effect. But sls is kinda cool.

注意: slsserverless命令的别名。 您可以同时使用这两种效果。 但是sls有点酷。

4.创建服务 (4. Creating a service)

With the Serverless Framework hooked up with your AWS account, you can set up a Serverless project in a jiffy. Fire up the terminal and issue the following command:

通过将无服务器框架与您的AWS帐户挂钩,您可以轻松设置无服务器项目。 启动终端并发出以下命令:

$ sls create --template aws-python --path 

The --template flag is used to specify a preset template with the given settings. In the above command the template aws-python will set up the project configured to use AWS as the provider and Python as the runtime. The command will auto-generate serverless.yml , handler.py and .gitignorefile with preset values.

--template标志用于指定具有给定设置的预设模板。 在上面的命令中,模板aws-python将设置项目,该项目配置为使用AWS作为提供者,使用Python作为运行时。 该命令将使用预设值自动生成serverless.ymlhandler.py.gitignore文件。

The configuration is defined in the serverless.yml file. This file is the most important file in the Serverless Framework. It’s almost magical, given how it can spin up the infrastructure you have defined in it. The contents of the auto-generated serverless.yml file will look something like this:

该配置在serverless.yml文件中定义。 该文件是无服务器框架中最重要的文件。 考虑到它如何提升您在其中定义的基础架构,这几乎是神奇的。 自动生成的serverless.yml文件的内容如下所示:

service: 
provider: name: aws runtime: python2.7 functions: hello: handler: handler.hello

The provider section defines everything related to the service provider, there are a lot more properties to configure it further you can take a look at them . In the auto-generated serverless.yml file, you need to add two important tags under the provider section, which are as follows:

provider部分定义了与服务提供者相关的所有内容,还有更多属性可以对其进行进一步配置,您可以在 。 在自动生成的serverless.yml文件中,您需要在provider部分下添加两个重要标记,如下所示:

region: 
profile:

The functions property is used to declare the serverless functions, you can declare multiple functions under this property. The above example declares a function called hello present in the handler.py file. Browse over to the handler.py file and you will find something like this:

functions属性用于声明无服务器功能,您可以在此属性下声明多个功能。 上面的示例在handler.py文件中声明了一个名为hello的函数。 浏览到handler.py文件,您会发现类似以下内容:

import jsondef hello(event, context):    	body = {    	"message": "Go Serverless v1.0! Your function executed      successfully!",                "input": event        }    response = {    	"statusCode": 200,                "body": json.dumps(body)        }    return response


无服务器应用 (The Serverless App)

Our Serverless solution makes use of AWS infrastructure, it consists of API Gateway, Lambda Functions, DynamoDB and Simple Email Service(SES). To achieve this end result we will use the previously introduced Serverless Framework.

我们的无服务器解决方案利用了AWS基础设施,由API网关,Lambda函数,DynamoDB和简单电子邮件服务(SES)组成。 为了达到这个最终结果,我们将使用以前引入的Serverless Framework。

  • Static Website — Amazon S3 provides a robust and simple web server. All of the static HTML, CSS and JS files for your application can be served from S3. The contact form on our static website is submitted using AJAX.

    静态网站 -Amazon S3提供了功能强大且简单的Web服务器。 可以从S3提供应用程序的所有静态HTML,CSS和JS文件。 我们静态网站上的联系表是使用AJAX提交的。

  • API Gateway — The API Gateway is the event source for the application, it acts as a bridge between our contact form and serverless lambda function. It routes the request from the contact form to the lambda function. The API Gateway also performs tasks such as access control, monitoring, API version control and traffic management.

    API网关 -API网关是应用程序的事件源,它充当联系表单和无服务器lambda函数之间的桥梁。 它将请求从联系表路由到lambda函数。 API网关还执行诸如访问控制,监视,API版本控制和流量管理之类的任务。

  • AWS Lambda — AWS Lambda is the place where the action takes place. Lambda functions run in stateless compute containers that are event-triggered, managed and ephemeral. In our example, we use a lambda function to send email using SES and store the request contents in DynamoDB NoSQL database.

    AWS Lambda- AWS Lambda是执行操作的地方。 Lambda函数在无状态的计算容器中运行,这些容器是事件触发的,托管的和短暂的。 在我们的示例中,我们使用lambda函数通过SES发送电子邮件并将请求内容存储在DynamoDB NoSQL数据库中。

  • Simple Email Service (SES) — The cloud-based email sending service from Amazon. Scalable email service, you can send marketing and transactional emails using SES. In our example, we use SES to send emails using a verified email address.

    简单电子邮件服务(SES)-来自Amazon的基于云的电子邮件发送服务。 可扩展的电子邮件服务,您可以使用SES发送市场营销和交易电子邮件。 在我们的示例中,我们使用SES通过已验证的电子邮件地址发送电子邮件。

  • DynamoDB — DynamoDB provides a scalable, consistent, fully managed and non-relational database from Amazon. In our example, we use DynamoDB to store and retrieve the messages received from the static contact form.

    DynamoDB — DynamoDB从Amazon提供了一个可扩展的,一致的,完全托管的非关系数据库。 在我们的示例中,我们使用DynamoDB来存储和检索从静态联系人表单收到的消息。

You can find the source code for the demo application here. Go ahead and clone it!

您可以在此处找到演示应用程序的源代码。 继续克隆它!



应用演练 (Application Walkthrough)

Let’s have a stroll through the demo application before we actually deploy it on AWS.

在实际将示例应用程序部署到AWS之前,让我们先来看看。

1.解密serverless.yml文件 (1. Demystifying the serverless.yml file)

The serverless.yml file defines the services the application needs to use and interact with. The resources and the actions the Serverless functions can perform are listed under the iamRoleStatements property. It lists the actions and resources.

serverless.yml文件定义应用程序需要使用并与之交互的服务。 无服务器功能可以执行的资源和操作列在iamRoleStatements 属性。 它列出了操作和资源。

iamRoleStatements:  - Effect: "Allow"    Action:      - ses:SendEmail            - ses:SendRawEmail        Resource: "*"    - Effect: "Allow"        Action:            - dynamodb:Scan            - dynamodb:PutItem        Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

In the serverless.yml we are allowing the Serverless functions to use ses:SendEmail and dynamoDB:PutItem actions among many others defined above.

serverless.yml我们允许无服务器功能使用ses:SendEmaildynamoDB:PutItem操作以及上面定义的许多其他操作。

Since Lambda runs serverless functions in the cloud, we need to define the functions somewhere. Functions are defined using the functions property. In our example application we have defined events attached to them.

由于Lambda在云中运行无服务器功能,因此我们需要在某处定义功能。 函数是使用functions属性定义的。 在示例应用程序中,我们定义了附加到它们的事件。

functions:    sendMail:        handler: handler.sendMail    description: Send Email using AWS SES Service    events:      - http:                  path: sendMail                  method: post                  integration: lambda                  cors: true                  response:                      headers:                          "Access-Control-Allow_Origin": "'*'"                list:        handler: handler.list        description: List all the contact form submissions        events:            - http:                  path: list                  method: get                  integration: lambda                  cors: true                  response:                      headers:                          "Access-Control-Allow_Origin": "'*'"

Another great feature of Serverless Framework is that it will create an API in the AWS API Gateway and link it with relevant Lambda function. This is done using the http property defined in the events property.

无服务器框架的另一个重要功能是它将在AWS API Gateway中创建一个API,并将其与相关的Lambda函数链接。 这是使用events属性中定义的http属性完成的。

2.创建资源 (2. Creating Resources)

With Serverless Framework you create resources like a DynamoDB table as we have done here. This snippet of code is responsible for creating a DynamoDB table with the given configuration.

使用无服务器框架,您可以像在此处创建DynamoDB表之类的资源。 此代码段负责使用给定的配置创建DynamoDB表。

resources:    Resources:        ContactFormDynamoDbTable:            Type: 'AWS::DynamoDB::Table'            DeletionPolicy: Retain            Properties:                AttributeDefinitions:                    -                        AttributeName: id                        AttributeType: S                KeySchema:                    -                        AttributeName: id                        KeyType: HASH                ProvisionedThroughput:                    ReadCapacityUnits: 1                    WriteCapacityUnits: 1                TableName: ${self:provider.environment.DYNAMODB_TABLE}

3.浏览无服务器功能 (3. Peek into the Serverless functions)

The demo application is written in python, it uses AWS SDK to send emails using SES and for performing read/write operations on DynamoDB.

该演示应用程序是用python编写的,它使用 AWS开发工具包通过SES发送电子邮件并在DynamoDB上执行读/写操作。

The sendMail function is triggered when a POST request is received from the contact form on the /sendMail path. The list function is triggered by a GET request to /list path defined in the serverless.yml file.

当从/sendMail路径上的联系表收到POST请求时,将触发sendMail函数。 list功能由对serverless.yml文件中定义的/list路径的GET请求触发。



构建应用程序 (Building the Application)

Now that you have set up and configured the Serverless Framework in your machine, it’s time to get things rolling.

现在,您已经在计算机中设置并配置了无服务器框架,是时候开始了。

1.克隆应用程序 (1. Clone the application)

Let’s start by cloning the application from Github.

让我们从克隆Github开始。

$ git clone https://github.com/faizanbashir/python-ses-dynamodb-contactform$ cd python-ses-dynamodb-contactform

2.使用SES验证电子邮件地址 (2. Verify e-mail address with SES)

Fast-forward to verifying the email you intend to send email from SES. All you need to do is add an email address, AWS will send you a verification with a link to verify the email address.

快速验证您要从SES发送电子邮件的电子邮件。 您所需要做的就是添加一个电子邮件地址,AWS将向您发送带有链接的验证邮件,以验证该电子邮件地址。

After verifying the email address, the “Verification Status” for the email will show up as “verified”.

验证电子邮件地址后,电子邮件的“验证状态”将显示为“已验证”。

3.配置应用程序 (3. Configuring the application)

You need to configure the serverless.yml with your account specific details to make it work. Replace the region, profile and SENDER_EMAIL properties in serverless.yml as seen here:

您需要使用您的帐户特定详细信息配置serverless.yml ,以使其正常运行。 更换regionprofileSENDER_EMAIL在性能serverless.yml如下所示:

provider:    name: aws    runtime: python2.7    region: 
profile:
...environment: SENDER_EMAIL:

Awesome! with the configuration done you can turn your attention to deploying the application.

太棒了! 完成配置后,您可以将注意力转移到部署应用程序上。

4.部署到AWS (4. Deploying to AWS)

Everything in place now you can deploy application with a single command, ain’t that super cool.

现在,一切就绪,您就可以使用单个命令来部署应用程序,这不是超级酷。

$ sls deploy -v

It will take a minute or two to execute if you religiously followed this tutorial, at the end it will provide you a list of endpoints to use for calling our functions. It will look something like this:

如果您认真地遵循本教程,将需要一两分钟才能执行,最后,它将为您提供用于调用我们的函数的端点列表。 它看起来像这样:

endpoints:POST - https://xxx.execute-api.xx.amazonaws.com/development/sendMailGET - https://xxxx.execute-api.xx.amazonaws.com/development/list

5.测试端点 (5. Testing the endpoints)

Now that we have the endpoints let’s test application to see if it’s working or not. The /sendMail endpoint expects input in JSON format.

现在我们有了端点,让我们测试应用程序以查看其是否正常运行。 /sendMail端点期望以JSON格式输入。

$ curl --header "Content-Type: application/json" \--request POST \--data '{"firstname": "John", "lastname": "Doe", "email": "john@doe.com", "message": "Hi there"}'\https://xxx.execute-api.xx.amazonaws.com/development/sendMail

If the email is sent and the entry written to DynamoDB the request will exit with a response like this.

如果发送了电子邮件并将条目写入DynamoDB,则请求将以这样的响应退出。

> "Email Sent!"

Now, let’s test the /list endpoint in the same manner with the GET endpoint you got after deploying the application.

现在,让我们以与部署应用程序后获得的GET端点相同的方式测试/list端点。

$ curl https://xxxx.execute-api.xx.amazonaws.com/development/list

The /list endpoint response will look something like this:

/list端点响应将如下所示:

> {"body": [{"firstname": "John", "lastname": "Doe", "email": "john@doe.com", "updatedAt": 1529425349731, "message": "Hi there", "id": "f651c404-73dc-11e8-bf3e-be54be0b5d22", "createdAt": 1529425349731}], "statusCode": 200}

6.联系表 (6. The Contact Form)

With the Serverless functions working properly we can go ahead and integrate it into our static contact form. The static form code is in the public folder.

在无服务器功能正常运行的情况下,我们可以将其集成到我们的静态联系表中。 静态形式的代码是在public文件夹中。

Open the index.html file in your favourite IDE and update the URL variable with the /sendMail endpoint and you are good to go.

在您最喜欢的IDE中打开index.html文件,并使用/sendMail端点更新URL变量, /sendMail顺利。

//Insert your lambda function URL herevar URL = "https://xxx.execute-api.xx.amazonaws.com/development/sendMail";

Navigate to the page using the file:///<path>/<to>/<folder>/index.html in the browser or upload it to S3 bucket and enable static hosting.

使用浏览器中的file:///<path>/<to>/<folder>/index.html导航到该页面,或将其上传到S3存储桶并启用静态托管。

$ aws s3 sync public s3://your-bucket-name

Treat yourself with a Cappuccino, Latte or <insert-your-favorite-drink>. You just implemented a cool way to keep your website on static hosting with handling your forms, thanks to Serverless.

用卡布奇诺咖啡,拿铁咖啡或<插入您喜欢的饮料>对待自己。 多亏了Serverless,您刚刚实现了一种很酷的方法来处理表单,使网站保持在静态主机上。



事后思考 (Afterthoughts)

Serverless is definitely the way forward, not just for the worlds static contact forms. Serverless has opened a universe of opportunities for you, the contact form was just to get started with. How about using Serverless for your website analytics, a visitor counter or maybe click tracking?

无服务器无疑是前进的方向,而不仅仅是世界范围内的静态联系方式。 Serverless为您打开了无限的商机,联系表只是开始。 如何使用Serverless进行网站分析,访问者计数器或点击跟踪?

Endless opportunities are waiting for you. Get started for your next project in Serverless, it’ll be an awesome journey.

无尽的机会等着您。 开始您在Serverless中的下一个项目,这将是一段了不起的旅程。



Originally published at .

最初发布在

翻译自:

构建静态服务器

转载地址:http://xpuzd.baihongyu.com/

你可能感兴趣的文章
window资源管理器下无法打开ftp站点
查看>>
spring特点与好处
查看>>
html 自制属性
查看>>
面向对象术语概念
查看>>
细胞(cell) 矩阵快速幂
查看>>
HDU - 1272 小希的迷宫
查看>>
EntityFramework(1)基础概念与Database First
查看>>
Spring Boot 任务
查看>>
2018APIO 进京赶考
查看>>
Duilib程序添加托盘图标显示
查看>>
在windows上搭建redis集群(redis-cluster)
查看>>
【省选十连测之九】【DP】【组合计数去重】【欧拉函数】基本题
查看>>
文件上传功能 -- jquery.form.js/springmvc
查看>>
阿里云ecs(phpstudy一件包)
查看>>
Python核心编程的四大神兽:迭代器、生成器、闭包以及装饰器
查看>>
linux /proc/sys/fs/file-nr /proc/sys/fs/file-max /etc/security/limits.conf 三者的关联
查看>>
AndroidStudio-快捷键
查看>>
用python DIY一个图片转pdf工具并打包成exe
查看>>
6月14 空控制器和空操作及命名空间
查看>>
volicity文法学习和总结
查看>>