From 06257c8f6fdbe59529aa727573f026990df4f63f Mon Sep 17 00:00:00 2001 From: Qi Zhao Date: Tue, 3 Dec 2024 21:26:27 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20=E2=9C=8F=EF=B8=8F=20django=20examples?= =?UTF-8?q?=20(#56)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 + examples/README.md | 5 + examples/django/Dockerfile | 42 ++++++ examples/django/README.md | 26 ++++ examples/django/account/__init__.py | 0 examples/django/account/admin.py | 3 + examples/django/account/apps.py | 6 + .../django/account/migrations/0001_initial.py | 132 ++++++++++++++++++ .../django/account/migrations/__init__.py | 0 examples/django/account/models.py | 6 + examples/django/account/tests.py | 3 + examples/django/account/urls.py | 9 ++ examples/django/account/views.py | 22 +++ examples/django/compose.yml | 11 ++ examples/django/demo/__init__.py | 0 examples/django/demo/asgi.py | 16 +++ examples/django/demo/gunicorn.py | 6 + examples/django/demo/settings.py | 129 +++++++++++++++++ examples/django/demo/urls.py | 22 +++ examples/django/demo/wsgi.py | 16 +++ examples/django/manage.py | 22 +++ examples/django/requirements.txt | 3 + 22 files changed, 483 insertions(+) create mode 100644 examples/README.md create mode 100644 examples/django/Dockerfile create mode 100644 examples/django/README.md create mode 100644 examples/django/account/__init__.py create mode 100644 examples/django/account/admin.py create mode 100644 examples/django/account/apps.py create mode 100644 examples/django/account/migrations/0001_initial.py create mode 100644 examples/django/account/migrations/__init__.py create mode 100644 examples/django/account/models.py create mode 100644 examples/django/account/tests.py create mode 100644 examples/django/account/urls.py create mode 100644 examples/django/account/views.py create mode 100644 examples/django/compose.yml create mode 100644 examples/django/demo/__init__.py create mode 100644 examples/django/demo/asgi.py create mode 100644 examples/django/demo/gunicorn.py create mode 100644 examples/django/demo/settings.py create mode 100644 examples/django/demo/urls.py create mode 100644 examples/django/demo/wsgi.py create mode 100755 examples/django/manage.py create mode 100644 examples/django/requirements.txt diff --git a/README.md b/README.md index f7ddbdf..1129bdf 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,10 @@ pip install pyencrypt-pye ✨🍰✨ ``` Or you can use `pip install git+https://github.com/ZhaoQi99/pyencrypt-pye.git` install latest version. + +## Examples +View examples in the [examples](./examples) directory. + ## Usage ```shell diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..5218079 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,5 @@ +# Pyencrypt Examples + +This directory contains examples of how to use pyencrypt. + +* [`django`](./django): Pyencrypt Django Example \ No newline at end of file diff --git a/examples/django/Dockerfile b/examples/django/Dockerfile new file mode 100644 index 0000000..3cc0c1b --- /dev/null +++ b/examples/django/Dockerfile @@ -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 's@deb.debian.org@mirrors.aliyun.com@g' /etc/apt/sources.list +RUN sed -i 's@security.debian.org@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"] diff --git a/examples/django/README.md b/examples/django/README.md new file mode 100644 index 0000000..9494787 --- /dev/null +++ b/examples/django/README.md @@ -0,0 +1,26 @@ +# Pyencrypt Django Example + +This example shows how to use `pyencrypt` with Django. + +## How to use +```shell +docker compose up -d +``` + +## Test +* runserver: `curl http://127.0.0.1:8001/account/login/?username=admin&password=admin` +* gunicorn: `curl http://127.0.0.1:8002/account/login/?username=admin&password=admin` + +## Note +* `manage.py` shouldn't be encrypted. +* `gunicorn.py` shouldn't be encrypted. + +### Loader +* Copy `encrypted/loader*.so` to where `manage.py` is located. +* Add `import loader` at the top of `/__init__.py`. +* Don't forget to remove `encrypted` and `build` directory. + +### Docker +* For preventing to extract origin layer from image, using [`scratch`](https://docs.docker.com/build/building/base-images/#create-a-base-image) to convert image to single layer. + > [docker: extracting a layer from a image - Stack Overflow](https://stackoverflow.com/questions/40575752/docker-extracting-a-layer-from-a-image) +* Remember to specify `WORKDIR`, `ENTRYPOINT` and other in `Dockerfile` again after `scratch`. \ No newline at end of file diff --git a/examples/django/account/__init__.py b/examples/django/account/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django/account/admin.py b/examples/django/account/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/examples/django/account/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/examples/django/account/apps.py b/examples/django/account/apps.py new file mode 100644 index 0000000..2b08f1a --- /dev/null +++ b/examples/django/account/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class AccountConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'account' diff --git a/examples/django/account/migrations/0001_initial.py b/examples/django/account/migrations/0001_initial.py new file mode 100644 index 0000000..229bc30 --- /dev/null +++ b/examples/django/account/migrations/0001_initial.py @@ -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()), + ], + ), + ] diff --git a/examples/django/account/migrations/__init__.py b/examples/django/account/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django/account/models.py b/examples/django/account/models.py new file mode 100644 index 0000000..7e21811 --- /dev/null +++ b/examples/django/account/models.py @@ -0,0 +1,6 @@ +from django.contrib.auth.models import AbstractUser +from django.db import models + + +class User(AbstractUser): + pass diff --git a/examples/django/account/tests.py b/examples/django/account/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/examples/django/account/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/examples/django/account/urls.py b/examples/django/account/urls.py new file mode 100644 index 0000000..3a71d5b --- /dev/null +++ b/examples/django/account/urls.py @@ -0,0 +1,9 @@ +app_name = "account" + +from django.urls import path + +from .views import LoginView + +urlpatterns = [ + path("login/", LoginView.as_view(), name="login"), +] diff --git a/examples/django/account/views.py b/examples/django/account/views.py new file mode 100644 index 0000000..c3f5b0a --- /dev/null +++ b/examples/django/account/views.py @@ -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": "", + }, + ) + + return JsonResponse( + { + "message": "Invalid password", + }, + status=401, + ) diff --git a/examples/django/compose.yml b/examples/django/compose.yml new file mode 100644 index 0000000..d320889 --- /dev/null +++ b/examples/django/compose.yml @@ -0,0 +1,11 @@ +services: + demo1: + build: . + command: python manage.py runserver 0.0.0.0:8000 + ports: + - 8001:8000 + demo2: + build: . + command: gunicorn -c demo/gunicorn.py demo.wsgi + ports: + - 8002:8000 diff --git a/examples/django/demo/__init__.py b/examples/django/demo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django/demo/asgi.py b/examples/django/demo/asgi.py new file mode 100644 index 0000000..e1bffe0 --- /dev/null +++ b/examples/django/demo/asgi.py @@ -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() diff --git a/examples/django/demo/gunicorn.py b/examples/django/demo/gunicorn.py new file mode 100644 index 0000000..63bf59e --- /dev/null +++ b/examples/django/demo/gunicorn.py @@ -0,0 +1,6 @@ +bind = "0.0.0.0:8000" +workers = 1 +worker_class = "gevent" +worker_tmp_dir = "/tmp" +pidfile = "/tmp/gunicorn.pid" +accesslog = "-" diff --git a/examples/django/demo/settings.py b/examples/django/demo/settings.py new file mode 100644 index 0000000..948687a --- /dev/null +++ b/examples/django/demo/settings.py @@ -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" \ No newline at end of file diff --git a/examples/django/demo/urls.py b/examples/django/demo/urls.py new file mode 100644 index 0000000..0ec538f --- /dev/null +++ b/examples/django/demo/urls.py @@ -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")), +] diff --git a/examples/django/demo/wsgi.py b/examples/django/demo/wsgi.py new file mode 100644 index 0000000..a673741 --- /dev/null +++ b/examples/django/demo/wsgi.py @@ -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() diff --git a/examples/django/manage.py b/examples/django/manage.py new file mode 100755 index 0000000..5c02e34 --- /dev/null +++ b/examples/django/manage.py @@ -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() diff --git a/examples/django/requirements.txt b/examples/django/requirements.txt new file mode 100644 index 0000000..b06d2c0 --- /dev/null +++ b/examples/django/requirements.txt @@ -0,0 +1,3 @@ +Django==5.1.3 +gunicorn==23.0.0 +gevent==24.11.1 \ No newline at end of file