使用Lambda将Django无服务器部署
我成功将Django部署到AWS Lambda上了。使用Serverless Framework可以轻松实现。
以下是网址和存储库链接。
https://django-sls-helloworld.umihi.co/
https://github.com/umihico/django-sls-helloworld
2021年5月26日 追記:
还有Laravel和Nuxt的版本可供选择。
-
- NuxtをコンテナにしてLambdaでデプロイするのが超簡単になった2021年
- DjangoをLambdaを使ってサーバレスにデプロイする
创建一个默认的sls项目,并在f1a13ba的确认操作后,安装自定义域名插件0970afe。由于API Gateway无法去除URL末尾的stage名称,与Django的路由不兼容,因此我们先准备好自定义域名。
$ serverless create --template aws-python3 --path django-sls-helloworld # プロジェクト作成
$ cd django-sls-helloworld
$ serverless deploy # 一度デプロイ
$ serverless invoke -f hello # 正常に動くかテスト
{
"statusCode": 200,
"body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}}"
}
$ sls plugin install -n serverless-domain-manager # ドメイン設定のためのプラグインインストール
我将编辑serverless.yml。
+ custom:
+ customDomain:
+ domainName: django-sls-helloworld.umihi.co
+ certificateName: umihi.co
+ basePath: ''
+ stage: ${opt:stage, self:provider.stage}
+ createRoute53Record: true
+ endpointType: 'edge'
+ securityPolicy: tls_1_2
provider:
name: aws
runtime: python3.8
$ sls create_domain
# 最大40分かかると言われるが、次のデプロイコマンドはすぐにできる。ただドメイン適用に時間がかかるだけ。
$ sls deploy
这样,已经完成了设置了自定义域名的网页。接下来需要安装Django所需的库。80e8f1b。
$ sls plugin install -n serverless-python-requirements
我添加了以下文件,并且出于测试目的编辑了handler.py文件,尽管它是不必要的,但已经被导入了。
import os
import sys
requirements = os.path.join(
os.path.split(__file__)[0],
'.requirements',
)
if requirements not in sys.path:
sys.path.append(requirements)
Django
Werkzeug
PyMySQL
import json
+ import requirements
def hello(event, context):
+ # testing import libraries
+ import django
+ import werkzeug
+ import pymysql
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
如果部署成功并且使用”serverless invoke -f hello”命令正常运行,那么import就成功了。
接下来,创建Django项目。930a0c2
然后,安装用于服务器无状态库的WSGI插件。52386e4
$ django-admin startproject django_sls_helloworld .
$ sls plugin install -n serverless-wsgi
最后,
修正安装PyMySQL代替MySQLdb,以及修复版本不匹配的问题,30361dd
加入设置的ALLOWED_HOST域名,1966857
将Lambda指向WSGI进行路由。1dce3d3
import os
+ import pymysql
+
+ pymysql.version_info = (1, 4, 2, "final", 0)
+ pymysql.install_as_MySQLdb()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
省略
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+ 'ENGINE': 'django.db.backends.mysql',
+ 'NAME': 'djangodemo',
}
}
省略
- ALLOWED_HOSTS = []
+ ALLOWED_HOSTS = ["django-sls-helloworld.umihi.co"]
endpointType: 'edge'
securityPolicy: tls_1_2
+ wsgi:
+ app: django_sls_helloworld.wsgi.application
+ packRequirements: false
省略
functions:
hello:
- handler: handler.hello
+ handler: wsgi_handler.handler
# The following are a few example events you can configure
我們在自定義的域名上部署後,熟悉的畫面也出現了。以上就是這些。
順帶一提,這是一個一次性項目,所以我們以DEBUG=True的方式進行部署,同時也將SECRET_KEY上傳到了Github上,但在實際運營中這是禁忌,請留意。
