Django筆記
於 2022年6月3日 (五) 07:11 由 Tankianting(討論 | 貢獻) 所做的修訂
建立新專案
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; } }