Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: ✏️ django examples #56

Merged
merged 2 commits into from
Dec 3, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
docs: ✏️ django examples
ZhaoQi99 committed Dec 3, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit a74a9dc1b7199832707002dbf8219e059b725a4a
42 changes: 42 additions & 0 deletions examples/django/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
FROM python:3.10-bullseye as build

WORKDIR /root/demo

RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

ARG PYPI_URL=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
RUN pip config set global.index-url $PYPI_URL

RUN sed -i '[email protected]@mirrors.aliyun.com@g' /etc/apt/sources.list
RUN sed -i '[email protected]@mirrors.aliyun.com@g' /etc/apt/sources.list

RUN apt update
RUN apt install gettext git vim lrzsz less gcc -y

ADD requirements.txt /root/demo
RUN pip install -r requirements.txt
COPY . /root/demo/

RUN python manage.py collectstatic --noinput

# --- Encryption ---
RUN pip install git+https://github.com/ZhaoQi99/pyencrypt-pye.git
RUN pyencrypt encrypt --in-place --yes .
RUN cp encrypted/loader*.so .
RUN rm -rf encrypted build/

RUN echo "import loader\n$(cat demo/__init__.py)" > demo/__init__.py

COPY manage.py /root/demo
COPY demo/gunicorn.py /root/demo/demo

RUN pip uninstall pyencrypt-pye pycryptodome Cython python-minifier -y
# --- Encryption ---


FROM scratch
COPY --from=build / /

WORKDIR /root/demo
EXPOSE 8000
# ENTRYPOINT [ "bash", "/root/demo/bin/start.sh"]
5 changes: 5 additions & 0 deletions examples/django/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Pyencrypt Django Example

This example shows how to use `pyencrypt` with Django.

## How to use
Empty file.
3 changes: 3 additions & 0 deletions examples/django/account/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions examples/django/account/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class AccountConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'account'
132 changes: 132 additions & 0 deletions examples/django/account/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# Generated by Django 4.1.10 on 2024-12-03 05:34

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]

operations = [
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"first_name",
models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
(
"last_name",
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined"
),
),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.permission",
verbose_name="user permissions",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]
Empty file.
6 changes: 6 additions & 0 deletions examples/django/account/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
pass
3 changes: 3 additions & 0 deletions examples/django/account/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
9 changes: 9 additions & 0 deletions examples/django/account/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
app_name = "account"

from django.urls import path

from .views import LoginView

urlpatterns = [
path("login/", LoginView.as_view(), name="login"),
]
22 changes: 22 additions & 0 deletions examples/django/account/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from django.http import JsonResponse
from django.views import View


class LoginView(View):
def get(self, request, *args, **kwargs):
username = request.GET["username"]
password = request.GET["password"]
if username == "admin" and password == "admin":
return JsonResponse(
{
"username": username,
"token": "<token>",
},
)

return JsonResponse(
{
"message": "Invalid password",
},
status=401,
)
4 changes: 4 additions & 0 deletions examples/django/bin/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/bash

python manage.py migrate
python manage.py runserver 0.0.0.0:8000
11 changes: 11 additions & 0 deletions examples/django/compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
services:
demo1: &demo1
build: .
command: python manage.py runserver 0.0.0.0:8000
ports:
- 8001:8000
demo2:
<<: *demo1
command: gunicorn -c demo/gunicorn.py demo.wsgi
ports:
- 8002:8000
Empty file.
16 changes: 16 additions & 0 deletions examples/django/demo/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for demo project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")

application = get_asgi_application()
6 changes: 6 additions & 0 deletions examples/django/demo/gunicorn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
bind = "0.0.0.0:8000"
workers = 1
worker_class = "gevent"
worker_tmp_dir = "/tmp"
pidfile = "/tmp/gunicorn.pid"
accesslog = "-"
129 changes: 129 additions & 0 deletions examples/django/demo/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 4.1.10.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", "DEMO")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"account.apps.AccountConfig",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "demo.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "demo.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Custom
AUTH_USER_MODEL = "account.User"
STATIC_ROOT = BASE_DIR / "static"
22 changes: 22 additions & 0 deletions examples/django/demo/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path("admin/", admin.site.urls),
path("account/", include("account.urls", namespace="account")),
]
16 changes: 16 additions & 0 deletions examples/django/demo/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for demo project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions examples/django/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions examples/django/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Django==5.1.3
gunicorn==23.0.0
gevent==24.11.1