「Django筆記」修訂間的差異

出自Tan Kian-ting的維基
跳至導覽 跳至搜尋
行 88: 行 88:
==參考==
==參考==
* https://docs.djangoproject.com
* https://docs.djangoproject.com
* https://stackoverflow.com/questions/58024196/nginx-proxy-pass-gunicorn-can-t-be-reached
* https://stackoverflow.com/questions/58024196/nginx-proxy-pass-gunicorn-can-t-be-reached 以及其他 stack overflow 答案
* https://chentsungyu.github.io/2020/07/19/Python/Django/%5BDjango%5D%20%E5%9C%A8Ubuntu%E4%B8%AD%E9%81%8B%E7%94%A8Nginx%E3%80%81Gunicorn%20%E6%9E%B6%E8%A8%AD%20Django%20API%20Server
* https://chentsungyu.github.io/2020/07/19/Python/Django/%5BDjango%5D%20%E5%9C%A8Ubuntu%E4%B8%AD%E9%81%8B%E7%94%A8Nginx%E3%80%81Gunicorn%20%E6%9E%B6%E8%A8%AD%20Django%20API%20Server

於 2022年6月3日 (五) 07:12 的修訂

建立新專案

django-admin startproject [網站目錄名]

跑伺服器

cd [網站目錄名]; ./manage.py runserver [Port number]

子結構說明

  • urls.py - url 網頁路徑傳送門
  • views.py - 顯示的方式

urls.py 基礎

假設urls.py 的所屬目錄包含 views.py,views.py有user這個函數,我們要傳字串/user/abc 的 abc 當成 user 函數的 username 變數,則可以這樣設定:

from django.contrib import admin
from django.urls import path

from . import views

urlpatterns = [
    path('/users/<slug:username>', views.user),
    path('admin/', admin.site.urls),
]

view.py

假設要做 activitypub 協定,回傳 json 的話,可以這樣設定:

from django.http import Http404, HttpResponse
import json

from . import config # import the config variables in the file './config.py'.

def user(request, username):
    user_json = {"@context": "https://www.w3.org/ns/activitystreams",
        "id": config.site_url + "/users/" + username,
        "inbox": config.site_url +  "/users/" + username + "/inbox",
        "outbox": config.site_url + "/users/" + username + "/outbox",
        "type": "Person", # the json for the type
        "name": username , # user name
        } 

    if username != 'John':
        raise Http404() # throw 404
    else:
        # return json file with setting content_type
       return HttpResponse(json.dumps(user_json), content_type="application/activity+json")

如果不是 John,就回傳 Http404()。

設定Gunicorn

   /etc/systemd/system/gunicorn.service                                                               

Group=www-data
WorkingDirectory=/root/lianlok                
ExecStart=/usr/local/bin/gunicorn(或其他絕對路徑) --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock lianlok.wsgi:application
[Install]
WantedBy=multi-user.target

設定 nginx

site-available 裏面的 test 設定檔為:

server {
listen 80;
server_name kianting.ddns.net 127.0.0.1;

# https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-production
# location /static/ { # STATIC_URL
#    alias /home/www/example.com/static/; # STATIC_ROOT
#                  }

    access_log /root/log/lianlok-access.log;
    error_log /root/log/lianlok-error.log;

    location / {
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;
            proxy_pass http://127.0.0.1:8080;
        }
}

參考