【Django总结】Django基础知识

https://blog.csdn.net/yilovexing/article/details/82969103

urls.py

URL:统一资源定位符

APP下的urls.py:在APP里添加urls.py是将App的URL都写入到该文件中

根目录下的urls.py:项目根目录下的urls.py是将APP下的urls.py统一管理

原理:当程序收到用户请求,首先在根目录的urls.py查找该URL是否属于哪个APP;

          然后从APP的urls.py找到具体的URL信息。

 1 # 根目录urls.py
 2 from django.contrib import admin
 3 from django.urls import path,include
 4 urlpatterns = [
 5                path('admin/', admin.site.urls), #Admin站点管理
 6                path('', include('index.urls'))        #首页地址
 7 ]
 8 # path('admin/', admin.site.urls):设定Admin的URL ,'admin/'代表#127.0.0.1:8000/admin地址信息,admin后面的斜杆是路径分隔符;#admin.site.urls是URL的处理函数,也称视图函数
 9 #path('', include('index.urls')):URL为空,代表为网站的域名,即#127.0.0.1:8000/,通常是网站的首页,include代表将URL分发给index的urls.py处理 
10 
11 # APP目录的urls.py
12 # index的urls.py
13 from django.urls import path, include
14 from . import view
15 
16 urlpatterns = [ 
17                path('', views.index)   
18 ]
19 # index中的urls.py和根目录下的大致相同
20 
21 # index的view.py
22 from django.http import HttpResponse
23 
24 def index(request):
25     return HttpResponse('Hello World')
26 
27 # 然后访问127.0.0.1:8000/就会显示 Hello World

 带变量的URL

 1 # index的urls.py
 2 from django.urls import path
 3 from . import views
 4 # 变量的几种数据格式
 5 # str 字符串
 6 # int 整形 
 7 # slug 注释后缀或附属等概念
 8 # uuif 匹配uuif格式的对象,防止冲突
 9 urlpatterns = [
10           path('<year>/<int:month>/<slug:day>', views.mydate)
11 ]
12 
13 # views.py的mydate函数
14 def mydate(request, year, month, day):
15     return HttpResponse(str(year) + '/' + str(month) + '/' + str(day))
16 
17 # urls.py 正则
18 from django.urls import path,re_path
19 
20 urlpatterns = [
21      #path('<year>/<int:month>/<slug:day>', views.mydate)
22      re_path('(?P<year>[0-9]{4}/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})).html', view.mydate)
23 ]    
#实际操作
#根目录:F:\mysite\mysite\urls.py
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/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 path, include

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

# APP目录 F:\mysite\polls\urls.py
from django.urls import path,re_path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    # URl匹配规则从上往下
    #path('<year>/<int:month>/<slug:day>', views.mydate),
    re_path('(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})', views.mydate_re)
]
# APP目录 F:\mysite\polls\views.py
import datetime
import json
import mimetypes
import os
import re
import sys
import time
from email.header import Header
from http.client import responses
from urllib.parse import quote, urlparse

from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedirect
from django.core.serializers.json import DjangoJSONEncoder
from django.http.cookie import SimpleCookie
from django.utils import timezone
from django.utils.encoding import iri_to_uri
from django.utils.http import http_date

_charset_from_content_type_re = re.compile(r';\s*charset=(?P<charset>[^\s;]+)', re.I)


class BadHeaderError(ValueError):
    pass


class HttpResponseBase:
    """
    An HTTP response base class with dictionary-accessed headers.

    This class doesn't handle content. It should not be used directly.
    Use the HttpResponse and StreamingHttpResponse subclasses instead.
    """

    status_code = 200

    def __init__(self, content_type=None, status=None, reason=None, charset=None):
        # _headers is a mapping of the lowercase name to the original case of
        # the header (required for working with legacy systems) and the header
        # value. Both the name of the header and its value are ASCII strings.
        self._headers = {}
        self._closable_objects = []
        # This parameter is set by the handler. It's necessary to preserve the
        # historical behavior of request_finished.
        self._handler_class = None
        self.cookies = SimpleCookie()
        self.closed = False
        if status is not None:
            try:
                self.status_code = int(status)
            except (ValueError, TypeError):
                raise TypeError('HTTP status code must be an integer.')

            if not 100 <= self.status_code <= 599:
                raise ValueError('HTTP status code must be an integer from 100 to 599.')
        self._reason_phrase = reason
        self._charset = charset
        if content_type is None:
            content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
                                               self.charset)
        self['Content-Type'] = content_type

    @property
    def reason_phrase(self):
        if self._reason_phrase is not None:
            return self._reason_phrase
        # Leave self._reason_phrase unset in order to use the default
        # reason phrase for status code.
        return responses.get(self.status_code, 'Unknown Status Code')

    @reason_phrase.setter
    def reason_phrase(self, value):
        self._reason_phrase = value

    @property
    def charset(self):
        if self._charset is not None:
            return self._charset
        content_type = self.get('Content-Type', '')
        matched = _charset_from_content_type_re.search(content_type)
        if matched:
            # Extract the charset and strip its double quotes
            return matched.group('charset').replace('"', '')
        return settings.DEFAULT_CHARSET

    @charset.setter
    def charset(self, value):
        self._charset = value

    def serialize_headers(self):
        """HTTP headers as a bytestring."""
        def to_bytes(val, encoding):
            return val if isinstance(val, bytes) else val.encode(encoding)

        headers = [
            (to_bytes(key, 'ascii') + b': ' + to_bytes(value, 'latin-1'))
            for key, value in self._headers.values()
        ]
        return b'\r\n'.join(headers)

    __bytes__ = serialize_headers

    @property
    def _content_type_for_repr(self):
        return ', "%s"' % self['Content-Type'] if 'Content-Type' in self else ''

    def _convert_to_charset(self, value, charset, mime_encode=False):
        """
        Convert headers key/value to ascii/latin-1 native strings.

        `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
        `value` can't be represented in the given charset, apply MIME-encoding.
        """
        if not isinstance(value, (bytes, str)):
            value = str(value)
        if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
                isinstance(value, str) and ('\n' in value or '\r' in value)):
            raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
        try:
            if isinstance(value, str):
                # Ensure string is valid in given charset
                value.encode(charset)
            else:
                # Convert bytestring using given charset
                value = value.decode(charset)
        except UnicodeError as e:
            if mime_encode:
                value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
            else:
                e.reason += ', HTTP response headers must be in %s format' % charset
                raise
        return value

    def __setitem__(self, header, value):
        header = self._convert_to_charset(header, 'ascii')
        value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
        self._headers[header.lower()] = (header, value)

    def __delitem__(self, header):
        self._headers.pop(header.lower(), False)

    def __getitem__(self, header):
        return self._headers[header.lower()][1]

    def has_header(self, header):
        """Case-insensitive check for a header."""
        return header.lower() in self._headers

    __contains__ = has_header

    def items(self):
        return self._headers.values()

    def get(self, header, alternate=None):
        return self._headers.get(header.lower(), (None, alternate))[1]

    def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False, samesite=None):
        """
        Set a cookie.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then calculate ``max_age``.
        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]['expires'] = expires
        else:
            self.cookies[key]['expires'] = ''
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]['expires'] = http_date(time.time() + max_age)
        if path is not None:
            self.cookies[key]['path'] = path
        if domain is not None:
            self.cookies[key]['domain'] = domain
        if secure:
            self.cookies[key]['secure'] = True
        if httponly:
            self.cookies[key]['httponly'] = True
        if samesite:
            if samesite.lower() not in ('lax', 'strict'):
                raise ValueError('samesite must be "lax" or "strict".')
            self.cookies[key]['samesite'] = samesite

    def setdefault(self, key, value):
        """Set a header unless it has already been set."""
        if key not in self:
            self[key] = value

    def set_signed_cookie(self, key, value, salt='', **kwargs):
        value = signing.get_cookie_signer(salt=key + salt).sign(value)
        return self.set_cookie(key, value, **kwargs)

    def delete_cookie(self, key, path='/', domain=None):
        # Most browsers ignore the Set-Cookie header if the cookie name starts
        # with __Host- or __Secure- and the cookie doesn't use the secure flag.
        secure = key.startswith(('__Secure-', '__Host-'))
        self.set_cookie(
            key, max_age=0, path=path, domain=domain, secure=secure,
            expires='Thu, 01 Jan 1970 00:00:00 GMT',
        )

    # Common methods used by subclasses

    def make_bytes(self, value):
        """Turn a value into a bytestring encoded in the output charset."""
        # Per PEP 3333, this response body must be bytes. To avoid returning
        # an instance of a subclass, this function returns `bytes(value)`.
        # This doesn't make a copy when `value` already contains bytes.

        # Handle string types -- we can't rely on force_bytes here because:
        # - Python attempts str conversion first
        # - when self._charset != 'utf-8' it re-encodes the content
        if isinstance(value, bytes):
            return bytes(value)
        if isinstance(value, str):
            return bytes(value.encode(self.charset))
        # Handle non-string types.
        return str(value).encode(self.charset)

    # These methods partially implement the file-like object interface.
    # See https://docs.python.org/library/io.html#io.IOBase

    # The WSGI server must call this method upon completion of the request.
    # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
    def close(self):
        for closable in self._closable_objects:
            try:
                closable.close()
            except Exception:
                pass
        self.closed = True
        signals.request_finished.send(sender=self._handler_class)

    def write(self, content):
        raise IOError("This %s instance is not writable" % self.__class__.__name__)

    def flush(self):
        pass

    def tell(self):
        raise IOError("This %s instance cannot tell its position" % self.__class__.__name__)

    # These methods partially implement a stream-like object interface.
    # See https://docs.python.org/library/io.html#io.IOBase

    def readable(self):
        return False

    def seekable(self):
        return False

    def writable(self):
        return False

    def writelines(self, lines):
        raise IOError("This %s instance is not writable" % self.__class__.__name__)


class HttpResponse(HttpResponseBase):
    """
    An HTTP response class with a string as content.

    This content that can be read, appended to, or replaced.
    """

    streaming = False

    def __init__(self, content=b'', *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Content is a bytestring. See the `content` property methods.
        self.content = content

    def __repr__(self):
        return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % {
            'cls': self.__class__.__name__,
            'status_code': self.status_code,
            'content_type': self._content_type_for_repr,
        }

    def serialize(self):
        """Full HTTP message, including headers, as a bytestring."""
        return self.serialize_headers() + b'\r\n\r\n' + self.content

    __bytes__ = serialize

    @property
    def content(self):
        return b''.join(self._container)

    @content.setter
    def content(self, value):
        # Consume iterators upon assignment to allow repeated iteration.
        if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):
            content = b''.join(self.make_bytes(chunk) for chunk in value)
            if hasattr(value, 'close'):
                try:
                    value.close()
                except Exception:
                    pass
        else:
            content = self.make_bytes(value)
        # Create a list of properly encoded bytestrings to support write().
        self._container = [content]

    def __iter__(self):
        return iter(self._container)

    def write(self, content):
        self._container.append(self.make_bytes(content))

    def tell(self):
        return len(self.content)

    def getvalue(self):
        return self.content

    def writable(self):
        return True

    def writelines(self, lines):
        for line in lines:
            self.write(line)


class StreamingHttpResponse(HttpResponseBase):
    """
    A streaming HTTP response class with an iterator as content.

    This should only be iterated once, when the response is streamed to the
    client. However, it can be appended to or replaced with a new iterator
    that wraps the original content (or yields entirely new content).
    """

    streaming = True

    def __init__(self, streaming_content=(), *args, **kwargs):
        super().__init__(*args, **kwargs)
        # `streaming_content` should be an iterable of bytestrings.
        # See the `streaming_content` property methods.
        self.streaming_content = streaming_content

    @property
    def content(self):
        raise AttributeError(
            "This %s instance has no `content` attribute. Use "
            "`streaming_content` instead." % self.__class__.__name__
        )

    @property
    def streaming_content(self):
        return map(self.make_bytes, self._iterator)

    @streaming_content.setter
    def streaming_content(self, value):
        self._set_streaming_content(value)

    def _set_streaming_content(self, value):
        # Ensure we can never iterate on "value" more than once.
        self._iterator = iter(value)
        if hasattr(value, 'close'):
            self._closable_objects.append(value)

    def __iter__(self):
        return self.streaming_content

    def getvalue(self):
        return b''.join(self.streaming_content)


class FileResponse(StreamingHttpResponse):
    """
    A streaming HTTP response class optimized for files.
    """
    block_size = 4096

    def __init__(self, *args, as_attachment=False, filename='', **kwargs):
        self.as_attachment = as_attachment
        self.filename = filename
        super().__init__(*args, **kwargs)

    def _set_streaming_content(self, value):
        if not hasattr(value, 'read'):
            self.file_to_stream = None
            return super()._set_streaming_content(value)

        self.file_to_stream = filelike = value
        if hasattr(filelike, 'close'):
            self._closable_objects.append(filelike)
        value = iter(lambda: filelike.read(self.block_size), b'')
        self.set_headers(filelike)
        super()._set_streaming_content(value)

    def set_headers(self, filelike):
        """
        Set some common response headers (Content-Length, Content-Type, and
        Content-Disposition) based on the `filelike` response content.
        """
        encoding_map = {
            'bzip2': 'application/x-bzip',
            'gzip': 'application/gzip',
            'xz': 'application/x-xz',
        }
        filename = getattr(filelike, 'name', None)
        filename = filename if (isinstance(filename, str) and filename) else self.filename
        if os.path.isabs(filename):
            self['Content-Length'] = os.path.getsize(filelike.name)
        elif hasattr(filelike, 'getbuffer'):
            self['Content-Length'] = filelike.getbuffer().nbytes

        if self.get('Content-Type', '').startswith(settings.DEFAULT_CONTENT_TYPE):
            if filename:
                content_type, encoding = mimetypes.guess_type(filename)
                # Encoding isn't set to prevent browsers from automatically
                # uncompressing files.
                content_type = encoding_map.get(encoding, content_type)
                self['Content-Type'] = content_type or 'application/octet-stream'
            else:
                self['Content-Type'] = 'application/octet-stream'

        if self.as_attachment:
            filename = self.filename or os.path.basename(filename)
            if filename:
                try:
                    filename.encode('ascii')
                    file_expr = 'filename="{}"'.format(filename)
                except UnicodeEncodeError:
                    file_expr = "filename*=utf-8''{}".format(quote(filename))
                self['Content-Disposition'] = 'attachment; {}'.format(file_expr)


class HttpResponseRedirectBase(HttpResponse):
    allowed_schemes = ['http', 'https', 'ftp']

    def __init__(self, redirect_to, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self['Location'] = iri_to_uri(redirect_to)
        parsed = urlparse(str(redirect_to))
        if parsed.scheme and parsed.scheme not in self.allowed_schemes:
            raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)

    url = property(lambda self: self['Location'])

    def __repr__(self):
        return '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % {
            'cls': self.__class__.__name__,
            'status_code': self.status_code,
            'content_type': self._content_type_for_repr,
            'url': self.url,
        }


class HttpResponseRedirect(HttpResponseRedirectBase):
    status_code = 302


class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
    status_code = 301


class HttpResponseNotModified(HttpResponse):
    status_code = 304

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        del self['content-type']

    @HttpResponse.content.setter
    def content(self, value):
        if value:
            raise AttributeError("You cannot set content to a 304 (Not Modified) response")
        self._container = []


class HttpResponseBadRequest(HttpResponse):
    status_code = 400


class HttpResponseNotFound(HttpResponse):
    status_code = 404


class HttpResponseForbidden(HttpResponse):
    status_code = 403


class HttpResponseNotAllowed(HttpResponse):
    status_code = 405

    def __init__(self, permitted_methods, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self['Allow'] = ', '.join(permitted_methods)

    def __repr__(self):
        return '<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>' % {
            'cls': self.__class__.__name__,
            'status_code': self.status_code,
            'content_type': self._content_type_for_repr,
            'methods': self['Allow'],
        }


class HttpResponseGone(HttpResponse):
    status_code = 410


class HttpResponseServerError(HttpResponse):
    status_code = 500


class Http404(Exception):
    pass


class JsonResponse(HttpResponse):
    """
    An HTTP response class that consumes data to be serialized to JSON.

    :param data: Data to be dumped into json. By default only ``dict`` objects
      are allowed to be passed due to a security flaw before EcmaScript 5. See
      the ``safe`` parameter for more information.
    :param encoder: Should be a json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
    """

    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs)
View Code

 

一、工作原理Django 的部署可以有很多方式,采用 nginx + uwsgi 的方式是其中比较常见的一种方式。
在这种方式中,我们的通常做法是,将 nginx 作为服务器最前端,它将接收 web 的所有请求,统一管理请求。nginx 把所有静态请求自己来处理(这是 nginx 的强项)。然后,nginx 将所有非静态请求通过 uwsgi 传递给 Django,由 Django 来进行处理,从而完成一次 web 请求。


可见,uwsgi 的作用就类似一个桥接器,起到桥梁的作用。
Linux 的强项是用来做服务器,所以,下面的整个部署过程我们选择在 Ubuntu 16.04 下完成。
技术扩展:
WSGI 是 Web Server Gateway Interface 的缩写。以层的角度来看,WSGI 所在层的位置低于 CGI。但与 CGI 不同的是 WSGI 具有很强的伸缩性且能运行于多线程或多进程的环境下,这是因为 WSGI 只是一份标准并没有定义如何去实现。实际上 WSGI 并非 CGI,因为其位于 web 应用程序与 web 服务器之间,而 web 服务器可以是 CGI。可以理解为是 Python 内置的一个测试 web 服务器。
uWSGI 是一个Web服务器,它实现了 WSGI 协议、uwsgi、http 等协议。Nginx 中HttpUwsgiModule 的作用是与 uWSGI 服务器进行交换。WSGI 是一种 Web 服务器网关接口。比如把 HTTP 协议转化成 WSGI 协议,让 Python 可以直接使用。
二、项目环境操作系统: Ubuntu 16.04
编程语言: Python 3.5.2
Web 框架: Django 2.0.3
Web 服务器: uWSGI 2.0.17
Web 服务器: Nginx 1.10.3
具体的安装这里不做详述,Ubuntu 使用 apt-get 安装特别方便。
sudo apt-get install python3sudo apt-get install python3-pipsudo apt-get install nginx123Nginx 安装成功在浏览器中输入 127.0.0.1,出现 “Welcome to nginx!”表示安装成功。
三、uWSGI 安装配置安装sudo pip3 install uwsgi1测试创建 test.py 文件
#!/usr/bin/env python3# -*- coding: UTF-8 -*-
def application(env, start_response):    start_response('200 OK', [('Content-Type','text/html')])    return [b'Hello World']123456通过 uWSGI 运行该文件
uwsgi --http :8000 --wsgi-file test.py1在浏览器中输入 127.0.0.1:8000,出现 “Hello World”表示安装成功。
四、Django 与 uWSGI 之间的通信安装 Djangosudo pip3 install Django==2.0.31创建 Django 项目django-admin startproject myweb1我的 Django 项目位置为:/home/setup/myweb
uwsgi --http :8000 --chdir /home/setup/myweb --wsgi-file myweb/wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:80011常用选项http: 协议类型和端口号
processes: 开启的进程数量
workers: 开启的进程数量,等同于 processes
chdir: 指定运行目录
wsgi-file: 载入 wsgi-file
stats: 在指定的地址上,开启状态服务
threads: 运行线程。由于 GIL 的存在,我觉得这个真心没啥用。
master: 允许主进程存在
daemonize: 使进程在后台运行,并将日志打到指定的日志文件或者 udp 服务器(daemonize uWSGI)。实际上最常用的,还是把运行记录输出到一个本地文件上。
pidfile: 指定pid文件的位置,记录主进程的pid号。
vacuum: 当服务器退出的时候自动清理环境,删除 unix socket 文件和 pid 文件
五、Nginx、uWSGI、Django 之间的通信接下来,我们要将三者结合起来
1. 配置 Django 和 uWSGI先在 Django 项目根目录下新建一个 uWSGI 的配置文件 uwsgi.ini
cd mywebtouch uwsgi.ini 12此时 Django 项目的目录文件结构如下:
myweb/├── manage.py├── myweb│   ├── __init__.py│   ├── __pycache__│   │   ├── __init__.cpython-35.pyc│   │   └── settings.cpython-35.pyc│   ├── settings.py│   ├── urls.py│   └── wsgi.py└── uwsgi.ini1234567891011在我们通过 Django 创建 myweb 项目时,在子目录 myweb 下已经帮我们生成的 wsgi.py文件。所以,我们只需要再创建 uwsgi.ini 配置文件即可。
uwsgi 支持多种类型的配置文件,如 xml、ini 等。此处,使用 ini 类型的配置。
接下来打开刚刚创建好的配置文件 uwsgi.ini 添加如下配置:
[uwsgi]
socket = :8888chdir           = /home/setup/mywebmodule          = myweb.wsgimaster          = trueprocesses       = 4vacuum          = true12345678这个配置,其实就相当于在上一小节中通过 wsgi 命令,后面跟一堆参数的方式,给文件化了。
socket: 指定项目执行的端口号。
chdir: 指定项目的目录。
module: module = hello.wsgi 可以这么来理解。对于 uwsgi.ini 文件而言,与它同级目录有一个 myweb 目录,这个目录下有一个 wsgi.py 文件。
其它几个参数,可以参考上一小节中参数的介绍。
接下来,通过 uwsgi 命令读取 uwsgi.ini 文件启动项目
uwsgi --ini uwsgi.ini1运行结果:
setup@labideas-data:~/myweb$ uwsgi --ini uwsgi.ini[uWSGI] getting INI configuration from uwsgi.ini*** Starting uWSGI 2.0.17 (64bit) on [Tue Mar 20 11:11:30 2018] ***compiled with version: 5.4.0 20160609 on 19 March 2018 09:13:12os: Linux-4.4.0-105-generic #128-Ubuntu SMP Thu Dec 14 12:42:11 UTC 2017nodename: labideas-datamachine: x86_64clock source: unixdetected number of CPU cores: 4current working directory: /home/setup/hellodetected binary path: /usr/local/bin/uwsgi!!! no internal routing support, rebuild with pcre support !!!chdir() to /home/setup/helloyour processes number limit is 64049your memory page size is 4096 bytesdetected max file descriptor number: 65535lock engine: pthread robust mutexesthunder lock: disabled (you can enable it with --thunder-lock)uwsgi socket 0 bound to TCP address :8888 fd 3Python version: 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609]*** Python threads support is disabled. You can enable it with --enable-threads ***Python main interpreter initialized at 0x1f73aa0your server socket listen backlog is limited to 100 connectionsyour mercy for graceful operations on workers is 60 secondsmapped 364520 bytes (355 KB) for 4 cores*** Operational MODE: preforking ***WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1f73aa0 pid: 7097 (default app)*** uWSGI is running in multiple interpreter mode ***spawned uWSGI master process (pid: 7097)spawned uWSGI worker 1 (pid: 7099, cores: 1)spawned uWSGI worker 2 (pid: 7100, cores: 1)spawned uWSGI worker 3 (pid: 7101, cores: 1)spawned uWSGI worker 4 (pid: 7102, cores: 1)123456789101112131415161718192021222324252627282930313233注意查看uwsgi的启动信息,如果有错,就要检查配置文件的参数是否设置有误。
2. 配置 NginxNginx 默认的配置文件都在 /etc/nginx 目录下
setup@labideas-data:/etc/nginx$ lltotal 64drwxr-xr-x  6 root root 4096 Mar 20 09:37 ./drwxr-xr-x 95 root root 4096 Mar 19 19:56 ../drwxr-xr-x  2 root root 4096 Mar 19 20:13 conf.d/-rw-r--r--  1 root root 1077 Feb 12  2017 fastcgi.conf-rw-r--r--  1 root root 1007 Feb 12  2017 fastcgi_params-rw-r--r--  1 root root 2837 Feb 12  2017 koi-utf-rw-r--r--  1 root root 2223 Feb 12  2017 koi-win-rw-r--r--  1 root root 3957 Feb 12  2017 mime.types-rw-r--r--  1 root root 1919 Mar 20 09:33 nginx.conf-rw-r--r--  1 root root  180 Feb 12  2017 proxy_params-rw-r--r--  1 root root  636 Feb 12  2017 scgi_paramsdrwxr-xr-x  2 root root 4096 Mar 20 10:00 sites-available/drwxr-xr-x  2 root root 4096 Mar 19 14:59 sites-enabled/drwxr-xr-x  2 root root 4096 Mar 19 14:59 snippets/-rw-r--r--  1 root root  664 Feb 12  2017 uwsgi_params-rw-r--r--  1 root root 3071 Feb 12  2017 win-utf123456789101112131415161718我们需要进入 /etc/nginx/sites-available 目录下进行配置 default 文件(有些 Linux 发行版的配置文件是在 /etc/nginx/nginx.conf 下,还有一些在其他地方,这里我们以 Ubuntu 16.04 为准)。
将原有配置文件进行备份,并打开 nginx 配置文件
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.baksudo vi /etc/nginx/sites-available/default12将默认的 80 端口号改成其它端口号,如 8080。因为默认的 80 端口号很容易被其它应用程序占用,而且我们配置我们自己的 Django 项目也需要用到默认端口。
# Django 2.0 项目部署server {
    listen          80;     server_name     data.labideas.cn     charset         UTF-8;    access_log      /var/log/nginx/myweb_access.log;    error_log       /var/log/nginx/myweb_error.log;
    client_max_body_size 75M;
    location / { 
        include uwsgi_params;        uwsgi_pass 127.0.0.1:8888;        uwsgi_read_timeout 2;    }   
    location /static {
        expires 30d;        autoindex on;         add_header Cache-Control private;        alias /home/setup/myweb/static/;    }   }1234567891011121314151617181920212223242526listen: 指定的是 nginx 代理 uwsgi 对外的端口号。
server_name: 网上大多资料都是设置的一个网址(例,www.baidu.com,如果指定的是 localhost 或 127.0.0.1 则只能在本机访问。
那么 nginx 到底是如何 uwsgi 产生关联的呢?现在看来大概最主要的就是这两行配置。
include uwsgi_params;uwsgi_pass 127.0.0.1:8888;12include 必须指定为 uwsgi_params。而 uwsgi_pass 指的是本机 IP 和端口号,并且要与 myweb_uwsgi.ini 配置文件中的 IP 和端口号必须保持一致。
现在重新启动 nginx
sudo /etc/init.d/nginx restart1然后浏览器访问 127.0.0.1
Invalid HTTP_HOST header: 'data.labideas.cn'. You may need to add 'data.labideas.cn' to ALLOWED_HOSTS.[pid: 7924|app: 0|req: 1/1] 114.249.204.30 () {40 vars in 658 bytes} [Tue Mar 20 06:16:28 2018] GET / => generated 54903 bytes in 41 msecs (HTTP/1.1 400) 1 headers in 53 bytes (1 switches on core 0)12在 uWSGI 后台就可以看到有信息输出。通过 IP 和端口号的指向,请求应该是先到 nginx 的,如果你在页面上执行一些请求,就会看到,这些请求最终会转到 uwsgi 来处理。
最后我们将 uWSGI 配置为开机自启
打开 sudo vi /etc/rc.local 将
uwsgi --ini /home/setup/myweb/uwsgi.ini &1添加到文件中
注意要添加到 exit 0 之前,& 表示该服务是在后台执行。
六、遇到的问题在配置过程中,总会遇到各种各样的问题,这里我将最常用的几项问题罗列出来,希望能帮到你。
1. Django 启动报错setup@labideas-data:~/myweb$ python3 manage.py runserverPerforming system checks...
System check identified no issues (0 silenced).
You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.Run 'python manage.py migrate' to apply them.
March 20, 2018 - 06:28:52Django version 2.0.3, using settings 'myweb.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.123456789101112创建一个新项目,利用 Django 本身的测试服务器启动,会出现上述的错误。这是因为你的项目中有些默认数据并没有迁移到数据库中。
解决办法:
将数据迁移到数据库中
python3 manage.py migrate12. uwsgi 启动报错在启动 uwsgi 的时候,在启动信息中如果有下面的错误提示:
!!! no internal routing support, rebuild with pcre support !!!1是依赖有问题
解决办法:
卸载 uwsgi,注意此时卸载,pip 会有缓存留在系统里
pip uninstall uwsgi1安装 pcre 依赖库
centos 安装
sudo yum install pcre pcre-devel pcre-static1ubuntu 安装
sudo apt-get install libpcre3 libpcre3-dev1重新安装 uwsgi,不走 pip 缓存
pip install uwsgi -I --no-cache-dir1再次启动 uwsgi,已经没有 !!! no internal routing support, rebuild with pcre support !!! 的报错了。
3. 端口报错有时候进过多次配置,启动 Django 和 uWSGI 可能会出现如下报错
Error: That port is already in use1这是端口号已被占用,是 servr 已经在运行了,也有可能在后台运行或者是你停掉可 Django 但是,进程资源和端口号并没有释放掉。
解决办法:
找到该进程 kill 掉即可
sudo ps aux | grep uwsgisudo kill -9 PID12或者最简单的解决方法就是直接杀掉
sudo fuser -k 8000/tcp1这样和端口 8000 相关的进程就都死掉了
4. 公网端口安全组屏蔽还有一些情况,感觉明明所有东西都配置好了,还检查了好多遍。本地没有一丁点问题,但是一上线就日了狗了,总是报“服务器未响应”等错误,或者 localhost 能访问,但是就是使用域名或外网访问不了,气的都想砸电脑…这又是怎么一回事呢?
项目在正式的环境中上线,一定是在公网上的,有时候我们会选择云服务器,这里以阿里云服务器为例,我们需要为其开放对应的端口号。
聪明的同学可能已经有所觉察,为什么上图中并没有 uwsgi.ini 文件中 8888 的端口号呢?
这是因为,阿里云的安全组规则端口是对外屏蔽的,我们 Nginx 和 uWSGI 之间通信的 socket 端口号 8888 是在内网环境中,所以不受影响。
5. 正式上线模式因为我们在实际开发的时候,需要用到 DEBUG 模式,但是在正式上线的时候我们需要关闭 DEBUG 模式。
打开 Django 项目中的 settings.py 配置文件

DEBUG = True1修改为
DEBUG = False1将
ALLOWED_HOSTS = []1修改为
ALLOWED_HOSTS = ['data.labideas.cn']1或者
ALLOWED_HOSTS = ['*']1建议不使用通配符 *,添加具体的域名即可!
6. Admin 管理界面样式表丢失曾几何时,Admin 是检验 Django 是否成功安装的标准。但是在正式环境中,经常会遇到样式表丢失的问题。为什么会这样呢?
这是因为 Nginx 在正式环境中,找不到 Django 项目中的静态文件。
解决办法:
① 在 Django 项目中新建一个 static 目录,用于放置一些静态文件
② 打开 Django 项目中的 settings.py 配置文件
添加一行
STATIC_ROOT = '/home/setup/myweb/static/'1将 STATIC_ROOT 指向存放静态文件的 static 目录
③ 从 Django 资源包中复制必须的静态文件到 STATIC_ROOT 指向的 static 目录中,这其中包括 admin 界面所必须的样式表(style)、图片(image)及脚本(js)等。
python3 manage.py collectstatic1需要注意的是,假如不做第 ① 步的话,直接运行这个命令会导致错误发生。
④ 修改 Nginx 配置文件
location /static {
    expires 30d;    autoindex on;     add_header Cache-Control private;    alias /home/setup/html/data/static/;}1234567将 alias 也指向存放静态文件的 static 目录,需要和 Django 项目中的 settings.py 配置文件中的 STATIC_ROOT 指向目录保持一致。
⑤ 重启 uWSGI 和 Nginx
# 杀掉 uwsgi.ini 进程ps aux | grep uwsgi | grep -v grep | awk '{print $2}' | xargs kill -9uwsgi --ini /home/setup/html/data/uwsgi.ini &
sudo /etc/init.d/nginx restart12345好了,至此本教程也已完结。之所以选择 Django2.0 版和 Python3 部署,是因为从 Django2.0 开始只支持 Python3.4 以上的版本了,并不向下兼容。而且未来投身到这坑中的同学也越来越多,为此也算是为 Python 和 Django 社区做点微小贡献。
关于 Django 和 Nginx 部署的文章网上有很多,大多数都比较乱,有些太简单的看不懂,有些又太啰嗦的不知道核心的几步是什么,感觉那些人顺着自己的思路写的。有很多细节没有特别标注,导致怎么弄都是失败报错。经过 1 天时间的潜心摸索,把能踩得坑都踩了,总结出一篇比较清晰详细的教程,希望这篇文章能帮到你!————————————————版权声明:本文为CSDN博主「极客点儿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/yilovexing/article/details/82969103

posted @ 2020-05-17 16:06  gtea  阅读(312)  评论(0编辑  收藏  举报