码农行者 码农行者
首页
  • Python

    • 语言特性
    • Django相关
    • Tornado
    • Celery
  • Golang

    • golang学习笔记
    • 对比python学习go
    • 模块学习
  • JavaScript

    • Javascript
  • 数据结构预算法笔记
  • ATS
  • Mongodb
  • Git
云原生
运维
垃圾佬的快乐
  • 数据库
  • 机器学习
  • 杂谈
  • 面试
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

DeanWu

软件工程师
首页
  • Python

    • 语言特性
    • Django相关
    • Tornado
    • Celery
  • Golang

    • golang学习笔记
    • 对比python学习go
    • 模块学习
  • JavaScript

    • Javascript
  • 数据结构预算法笔记
  • ATS
  • Mongodb
  • Git
云原生
运维
垃圾佬的快乐
  • 数据库
  • 机器学习
  • 杂谈
  • 面试
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 单文件 Django 服务构建

  • 开发语言
  • Python
  • Django
DeanWu
2020-11-13

单文件 Django 服务构建

今天在使用vue框架开发系统的时候,需要用到后端接口,但是接口还没有开发。便想使用最简单的方式构建一个极简的API服务,由于本人偏爱Django框架,便想能不能用Django框架简单的构建想Flask那样的单文件web服务。果然,被我找到了,摘录分享给大家。

# app.py 
import os
import sys
from dataclasses import dataclass

from django.conf import settings
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import path
from django.utils.crypto import get_random_string

# django 的配置文件,相当于 settings.py 配置文件,可直接在这里添加和删除
# 下边已经是最简的Django 启动需要的参数了
settings.configure(
    DEBUG=(os.environ.get("DEBUG", "") == "1"),
    ALLOWED_HOSTS=["*"],  # Disable host header validation
    ROOT_URLCONF=__name__,  # Make this module the urlconf
    SECRET_KEY=get_random_string(
        50
    ),  # We aren't using any security features but Django requires this setting
    MIDDLEWARE=["django.middleware.common.CommonMiddleware"],
)

# 使用dataclass 装饰器模拟了 model。
@dataclass
class Character:
    name: str
    age: int

    def as_dict(self, id_):
        return {
            "id": id_,
            "name": self.name,
            "age": self.age,
        }

# 列举数据,完全可以直接使用字段来构造需要返回的数据
characters = {
    1: Character("Rick Sanchez", 70),
    2: Character("Morty Smith", 14),
}

# Django  View 部分,为方便简单直接使用 function base view  
def index(request):
    return HttpResponseRedirect("/characters/")

def characters_list(request):
    return JsonResponse(
        {"data": [character.as_dict(id_) for id_, character in characters.items()]}
    )

def characters_detail(request, character_id):
    try:
        character = characters[character_id]
    except KeyError:
        return JsonResponse(
            status=404,
            data={"error": f"Character with id {character_id!r} does not exist."},
        )
    return JsonResponse({"data": character.as_dict(character_id)})

# Django route 部分,同 url.py 
urlpatterns = [
    path("", index),
    path("characters/", characters_list),
    path("characters/<int:character_id>/", characters_detail),
]

# 构建 uwsgi 使用 application 可使用 uwsgi 等 WSGI 协议的软件启动。 
app = get_wsgi_application()

if __name__ == "__main__":
    # 引入命令行启动方式函数,方便直接启动测试, 同 manage.py 文件
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

直接运行如下命令即可启动服务:

python app.py runserver
1

还可以使用 uwsgi 等应用程序启动。如使用 gunicorn 如下:

gunicorn app:app
1

希望可以帮助到你~

更多的Django 单文件的测试及构建方法可以到Adam Johnson (opens new window)(Django 技术委员会成员,英国Django MeetUp的组织者)的博客 (opens new window)查阅。

#Django
上次更新: 2023/03/28, 16:27:19
最近更新
01
chromebox/chromebook 刷bios步骤
03-01
02
redis 集群介绍
11-28
03
go语法题二
10-09
更多文章>
Theme by Vdoing | Copyright © 2015-2024 DeanWu | 遵循CC 4.0 BY-SA版权协议
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式