Django運行方式
- 調試模式 直接 python manage.py runserver
python manage.py runserver
python manage.py runserver 0.0.0.0:80
- web + uwsgi + django
請求順序:the web client <-> the web server <-> the socket <-> uwsgi <-> Django
下面具體說明如何實現:
參考:http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
- 安裝uwsgi
pip install uwsgi
- 創建測試文件
#!/usr/bin/env python # -*- coding: utf-8 -*- # pyversion:python3.5 # owner:fuzj # Pw @ 2017-01-09 15:46:32 def application(env,start_response): start_response('200 OK',[('Content_Type','text/html')]) return "Congraduation!!! uWSGI Testing OK!!!"
- 運行
[root@test ~]# uwsgi --http :8000 --wsgi-file ./test.py *** Starting uWSGI 2.0.14 (64bit) on [Mon Jan 9 18:08:23 2017] *** compiled with version: 4.4.7 20120313 (Red Hat 4.4.7-17) on 09 January 2017 17:37:30 os: Linux-2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 nodename: test.novalocal machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /root detected binary path: /usr/local/python2.7/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 30523 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 4 spawned uWSGI http 1 (pid: 2553) uwsgi socket 0 bound to TCP address 127.0.0.1:47160 (port auto-assigned) fd 3 Python version: 2.7.11 (default, Dec 29 2016, 15:13:34) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0xd46800 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72768 bytes (71 KB) for 1 cores *** Operational MODE: single process *** WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xd46800 pid: 2552 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 2552, cores: 1)
- 結果
Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 1246/redis-server * tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 979/sshd tcp 0 0 127.0.0.1:47160 0.0.0.0:* LISTEN 2552/uwsgi tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1228/master tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 2552/uwsgi tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 1130/mysqld tcp 0 0 :::6379 :::* LISTEN 1246/redis-server * tcp 0 0 :::22 :::* LISTEN 979/sshd tcp 0 0 ::1:25 :::* LISTEN 1228/master [root@test core]# curl http://127.0.0.1:8000 Congraduation!!! uWSGI Testing OK!!![root@test core]#****
-
nginx + uwsgi + django
-
nginx 配置:
server { listen 80; server_name op.xywy.com; #charset koi8-r; access_log logs/op.xywy.com-access.log main; location ^~ /static { alias /usr/local/python2.7/lib/python2.7/site-packages/django/contrib/admin/static/; } location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; } }
-
uwsgi配置
uwsgi 支持 .ini .xml 等格式的配置文件,。以ini為例
-
[uwsgi] chdir=/data/eoms #項目目錄 module=eoms.wsgi:application #uwsgi的模塊 #env=DJANGO_SETTINGS_MODULE=eoms.settings.prod master=True #主進程 pidfile=/tmp/eoms.pid socket=127.0.0.1:8000 processes=4 #子進程數量 max-requests=5000 vacuum=True #退出、重啟時清理文件 daemonize=/tmp/eoms.log
啟動nginx和uwsgi
/usr/local/nginx/sbin/nginx
uwsgi /data/eoms/uwsgi.ini
Django 處理請求
Django使用Request對象和Response對象在客戶端和服務端傳遞狀態,當客戶端發起請求到django之后,Django會建立一個包含請求元數據的HttpRequest對象,所以,django的url對應的視圖中,每個views函數中需將此httprequest作為參數傳遞進去,最后每個視圖會講處理的結果封裝為Httpresponse對象
HttpRequest對象
HttpRequest 作為參數傳遞到views中,具有的相關屬性如下:
- request.scheme client 的請求協議 通常是http或者https
- request.body 請求正文,通常post請求會將數據放入body中
- request.path 請求uri。但是不包含host
- request.path_info 獲取具有 URL 擴展名的資源的附加路徑信息。相對於HttpRequest.path,使用該方法便於移植 例如,如果應用的WSGIScriptAlias 設置為"/minfo",那么當path 是"/minfo/music/bands/the_beatles/" 時path_info 將是"/music/bands/the_beatles/"。
- request.method 請求的方式,比如: GET POST .........
- request.encoding 請求中表單提交數據的編碼。
- request.content_type 獲取請求的MIME類型(從CONTENT_TYPE頭部中獲取) django1.10的新特性。
- request.content_params 獲取CONTENT_TYPE中的鍵值對參數,並以字典的方式表示,django1.10的新特性。
- request.GET 返回一個 querydict 對象
- request.POST 返回一個 querydict ,該對象包含了所有的HTTP POST參數,通過表單上傳的所有 字符 都會保存在該屬性中。
- request.COOKIES 以字典形式返回header中cookie
-
request.FILES 以字典形式返回上傳文件的對象,key的值是input標簽中name屬性的值,value的值是一個UploadedFile對象
-
request.META 以字典形式返回所有http頭部信息
-
request.user 一個auth_user_model類型的對象,表示當前登錄的用戶,如果沒有登錄,user將設置為django.contrib.auth.models.AnonymousUser 的一個實例
-
request.session 當前會話的session
具有的相關方法如下:
- request.get_host() 返回請求的源主機。example: 127.0.0.1:8000
- request.get_port() django1.9的新特性。
- request.get_full_path() 返回完整路徑,並包括附加的查詢信息。example: "/music/bands/the_beatles/?print=true"
- request.bulid_absolute_uri(location) 返回location的絕對uri,location默認為request.get_full_path()。 Example: "https://example.com/music/bands/the_beatles/?print=true"
HttpResponse對象
httpresponse 是視圖返回的對象,由django.http模塊定義。
屬性:
- HttpResponse.content 返回的具體內容,默認編碼為header 中content_type,也可以在實例化的時候指定
- HttpResponse.status_code 相應的http狀態碼
- HttpResponse.streaming 用於中間件middleware區別對待流式response和常規response
- HttpResponse.closed 關閉連接
方法:
HttpResponse.__init__(content='', content_type=None, status=200, reason=None, charset=None)
使用頁面的內容(content)和content-type來實例化一個HttpResponse對象。
-
HttpResponse.__setitem__(header, value)
由給定的首部名稱和值設定相應的報文首部。 header 和 value 都應該是字符串類型。 -
HttpResponse.__delitem__(header)
根據給定的首部名稱來刪除報文中的首部。如果對應的首部不存在將沉默地(不引發異常)失敗。不區分大小寫。 -
HttpResponse.__getitem__(header)
根據首部名稱返回其值。不區分大小寫。 -
HttpResponse.has_header(header)
通過檢查首部中是否有給定的首部名稱(不區分大小寫),來返回True 或 False 。 -
HttpResponse.setdefault(header, value)
設置一個默認首部,除非該首部 header 已經存在了。 -
HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
設置cookie -
HttpResponse的子類
- HttpResponseRedirect 302臨時重定向
- HttpResponsePermanentRedirect 301 永久重定向
- HttpResponseNotModified 304 沒有任何改變
- HttpResponseBadRequest 400 錯誤的請求
- HttpResponseNotFound 404 請求對象不存在
- HttpResponseForbidden 403 請求被拒絕
- HttpResponseNotAllowed 405 請求的方式不允許
- HttpResponseGone 410 請求的資源已被刪除
- HttpResponseServerError 500 服務內部錯誤
-
JsonResponse對象 JsonResponse可以直接將返回的對象序列化為json字符串
JsonResponse.__init__(data, encoder=DjangoJSONEncoder, safe=True, **kwargs)
它的第一個參數data,應該為一個dict 實例。如果safe 參數設置為False,它可以是任何可JSON 序列化的對象