> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何托管 Django 应用

> 了解如何在 Square Cloud 上创建并托管 Django 应用。

export const PortNote = ({lang}) => {
  if (lang == 'pt-br') {
    return <Note>
            <b>Qual porta devo usar para o meu servidor?</b><br />
            Você deve usar a porta <b>80</b> para o seu servidor. A porta 80 é a porta padrão para tráfego HTTP; a Square Cloud a encaminha para 443 (HTTPS) para estabelecer uma conexão segura.<br />
            Certifique-se de configurá-la antes de compactar e enviar seu projeto.
        </Note>;
  }
  return <Note>
            <b>What port should I use for my server?</b><br />
            You should use port <b>80</b> for your server. Port 80 is the default port for HTTP traffic, which is handled by Square Cloud to route it to 443, HTTPS, for a secure connection.<br />
            Make sure to configure it before compressing and uploading your project.
        </Note>;
};

export const PyDepFiles = ({lang}) => {
  const desc = {
    "pt-br": {
      requirements: "Arquivo padrão usado em projetos Python para listar todas as bibliotecas externas e dependências necessárias para o seu projeto. Cada linha neste arquivo especifica um pacote a ser instalado usando o pip, o gerenciador de pacotes do Python",
      pyproject: "Um arquivo de configuração moderno para projetos Python que permite especificar requisitos do sistema de compilação e metadados do projeto. É utilizado por ferramentas como o Poetry para gerenciar dependências e empacotamento."
    },
    en: {
      requirements: "Standard file used in Python projects to list all the external libraries and dependencies that your project needs. Each line in this file specifies a package to be installed using pip, the Python package manager.",
      pyproject: "A modern configuration file for Python projects that can specify build system requirements and project metadata. It is used by tools like Poetry to manage dependencies and packaging."
    }
  };
  return <CardGroup cols={2}>
            <Card title="requirements.txt" icon="file-lines" href="../../articles/how-to-create-your-requirements">
            {desc[lang].requirements}
            </Card>
            <Card title="pyproject.toml" icon="file" href="../../articles/how-to-create-your-pyproject">
            {desc[lang].pyproject}
            </Card>
        </CardGroup>;
};

export const RecommendedPlan = ({lang, plan, tier, cpu, appType}) => {
  const url = `https://squarecloud.app/${lang}/pay?plan=${plan.toLowerCase()}&tier=${tier}`;
  if (lang == 'en') {
    return <Note>
        <b>Wondering how much RAM and CPU your plan needs to host {appType}?</b><br />
        Don't worry, we're here to help.
        Our <a href={url}>{plan}</a> plan offers <b>{tier}GB</b> of RAM and <b>{cpu}vCPU</b>, which should be sufficient for most {appType}. 
        However, if you are working on a larger project and seeking extra stability, we recommend considering our <b>Pro</b> plan. With additional resources, you can maintain stability even during demand spikes. 
        To purchase, simply click <a href="https://squarecloud.app/en/pay?plan=pro">here</a>.
      </Note>;
  } else {
    return <Note>
          <b>Está se perguntando quanta RAM e CPU seu plano precisa para hospedar {appType}?</b><br />
          Não se preocupe, estamos aqui para ajudar.
          Nosso plano <a href={url}>{plan}</a> oferece <b>{tier}GB</b> de RAM e <b>{cpu}vCPU</b>, o que deve ser suficiente para a maioria dos {appType}.
          No entanto, se você estiver trabalhando em um projeto maior e precisar de mais estabilidade, recomendamos considerar nosso plano <b>Pro</b>.
          Com recursos adicionais, você pode manter a estabilidade mesmo durante picos de demanda.
          Para comprar, basta clicar <a href={`https://squarecloud.app/${lang}/pay?plan=pro`}>aqui</a>.
        </Note>;
  }
};

export const appType_0 = "a Django application"

## 简介

要在 Square Cloud 上开发和托管 {appType_0}，遵循一套结构化的配置和前置条件流程至关重要。本技术指南将涵盖整个过程，从初始设置到生产环境部署。

### 前置条件

* **Square Cloud 账户**：通过[注册页面](https://squarecloud.app/zh/signup)使用你的邮箱进行注册。
* **有效的付费套餐**：为你的应用提供专属资源和优化的性能。查看我们[可用的套餐](https://squarecloud.app/zh/pricing)，选择最适合你需求的方案。

<RecommendedPlan appType="Django applications" plan="Standard" tier="4" cpu="4" lang="en" />

## 创建项目

要创建 Django 应用，在按照以下步骤操作之前，你的系统上需要安装 Python 和 pip。

### 安装库

安装好 Python 和 pip 后，你就可以创建一个新的 Django 项目。首先，使用 pip 安装 Django：

```bash theme={null}
pip install django
```

### 开发项目

创建一个新的 Python 文件（例如 `app.py`），并添加以下代码来创建一个基础的 Django 应用：

```python app.py theme={null}
from django.conf import settings
from django.http import HttpResponse
from django.urls import path
from django.core.wsgi import get_wsgi_application

# Basic Django settings
settings.configure(
    DEBUG=False,                # Disable debug mode
    SECRET_KEY='mysecretkey',   # Define your secret key
    ALLOWED_HOSTS=['*'],        # Allow all hosts for simplicity
    ROOT_URLCONF=__name__,      # Set the root URL configuration to this module
    MIDDLEWARE_CLASSES=(),      # Use an empty tuple to disable middleware
)

# Simple view
def index(request):
    return HttpResponse("Hello world!")  # Return a simple HTTP response

# URL configuration
urlpatterns = [
    path('', index),  # Map the root URL to the index view
]

# WSGI application
application = get_wsgi_application()

# WSGI server
if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    httpd = make_server('', 80, application)  # Serve the application using WSGI server on port 80
    print("Django server running on port 80...")
    httpd.serve_forever()  # Start the server
```

在上面的代码中，我们创建了一个基础路由，访问时会返回 "Hello, World!"。该应用被配置为在 80 端口上运行，这是 HTTP 流量的默认端口。

接下来，我们需要创建依赖文件。在 Python 中，我们可以使用 requirements.txt 或 pyproject.toml。

<PyDepFiles lang="en" />

## 选择生产服务器

Django 内置的开发服务器不适合用于生产环境。相反，我们建议使用像 Gunicorn 这样面向生产的 WSGI 服务器。

<CardGroup cols={1}>
  <Card title="Gunicorn" icon="unicorn" href="/zh/tutorials/python/how-to-use-gunicorn">
    Gunicorn 是一个用于 UNIX 的 Python WSGI HTTP 服务器。它采用预派生（pre-fork）工作进程模型，会派生多个工作进程来处理请求。
    这使它成为在生产环境中运行 Python Web 应用的绝佳选择。
  </Card>
</CardGroup>

## 部署

准备好项目文件后，你现在可以将它们上传到 Square Cloud 并托管你的项目。
为此，请创建一个包含所有项目文件的 ZIP 文件。

<Note>
  如果你的 Django 项目需要应用迁移，请确保在部署到 Square Cloud 之前完成迁移。\
  你可以在本地环境中运行以下命令来完成：

  ```bash theme={null}
  python manage.py migrate
  ```
</Note>

<PortNote lang="en" />

### 通过控制面板

<Steps>
  <Step title="访问上传页面">
    访问[上传页面](https://squarecloud.app/zh/dashboard/new)并上传你的项目 zip 文件。
  </Step>

  <Step title="配置你的环境">
    上传 zip 后，你需要为项目配置名称、主文件或运行时环境以及其他设置。\
    如果你上传的是 Web 项目，请务必选择 "Web Publication" 并为项目设置子域名。
  </Step>

  <Step title="部署你的项目">
    最后，点击 "Deploy" 按钮，即可将项目托管到 Square Cloud。\
    部署完成后，你可以在控制面板中监控项目的状态和日志。

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif" alt="正在上传应用到 Square Cloud" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>
</Steps>

### 通过 CLI

要使用此方法，你需要在项目根目录中创建一个名为 `squarecloud.app` 的配置文件。该文件将包含项目所需的配置。

<Card title="了解更多：如何为 Square Cloud 创建配置文件。" icon="link" href="/zh/getting-started/config-file">
  squarecloud.app 文件是一个配置文件，用于配置你的应用；它将用于定义你的环境。
</Card>

<Steps>
  <Step title="安装 CLI">
    首先，你的环境中需要已安装 CLI。如果尚未安装，请在终端中运行以下命令：

    ```
    npm install -g @squarecloud/cli
    ```

    如果你已经安装，我们建议对其进行更新。为此，请在终端中运行以下命令：

    <Tabs>
      <Tab title="Windows">
        ```bash theme={null}
        squarecloud update
        ```
      </Tab>

      <Tab title="Linux、macOS 和 WSL">
        ```bash theme={null}
        curl -fsSL https://cli.squarecloud.app/install | bash
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="进行身份验证">
    现在，要进行身份验证并使用其他 CLI 命令，你可以在[此处](https://squarecloud.app/zh/account/security)点击 "Request API Key" 找到你的授权密钥。获取授权密钥后，运行以下命令：

    ```bash theme={null}
    squarecloud auth login
    ```
  </Step>

  <Step title="上传你的项目">
    最后，要使用 CLI 将应用部署到 Square Cloud，你需要运行以下命令：

    ```bash theme={null}
    squarecloud upload 
    ```

    或者，如果你手动创建了 zip 文件，可以使用：

    ```bash theme={null}
    squarecloud upload --file <path/to/zip> 
    ```
  </Step>
</Steps>

## 更多资源

有关 Django 及其工具的更多信息，请访问 [Django 官方文档](https://docs.djangoproject.com/en/5.0/)。
在那里，你将找到详细的指南、教程和 API 文档，帮助你充分利用 Django。

## 故障排查

<CardGroup cols={1}>
  ### 自定义域名

  <Card horizontal>
    若要使用自定义域名（例如 `mysite.com`）来代替默认 URL `mysite.squareweb.app`，你需要 **Standard 计划或更高等级**。子域名由配置文件中的 **SUBDOMAIN** 字段定义。
  </Card>

  ### 最低内存要求

  <Card horizontal>
    简单网站/API 的**最低要求为 512MB RAM**。对于使用框架的站点（Next.JS、React、Vue、Angular 等），我们始终建议**至少 1GB RAM**。对于更大型的应用，请分配更多 RAM，以防止应用内存耗尽而崩溃。
  </Card>

  ### 找不到此站点。

  <Card horizontal>
    请检查**子域名/域名**是否与 **SUBDOMAIN** 字段或**自定义域名设置**中配置的内容一致。如果你刚上传站点，请等待最多 **60 秒**，让 Square 启用**首次访问**。
  </Card>

  ### 站点响应超时……

  <Card horizontal>
    请检查你是否在应用中正确配置了**端口 80** 和**主机 0.0.0.0**。我们建议使用 Square 强制注入的环境变量：来自 `.env` 文件的 **PORT** 和 **HOST**。
  </Card>
</CardGroup>

## 联系我们

如果你仍然遇到**技术问题**，我们的**专业支持团队**可以为你提供帮助。[**联系我们**](https://squarecloud.app/zh/support)，我们很乐意协助你解决任何问题。
