PYTHON3.django_day08 (see pdf)

Middleware
   Middleware definitions
     from django.utils.deprecation Import MiddlewareMixin
     class MyMiddleware (MiddlewareMixin):
         DEF process_request (Self, Request):
             to be called before routing
             ....
         DEF process_view (Self, Request, cb,
             cb_args, cb_kwargs ):
             this method after routing, view and there is a function call before calling
         def process_response (self, request, response ):
             method will be called when returning from view function
         DEF process_exception (Self, Request, Exception):
              ...
         process_templates_response DEF (Self, Request, the Response)
                 ...


         urlpatterns = [
             url(r'user/login', views.login_view)
         ]

CSRF
    django.middleware.csrf.CsrfViewMiddleware
    each inspection POST request
       form csrfmiddlewaretoken values are legal,



django form module in the form of
    role:
       to create form controls within a form
       used for inspection certificate forms
   1. Form Controls:
     class XXX (forms.Form):
          Search = forms.CharField (....)
     xxx = XXX ()
     xxx .as_p ()
     xxx.as_ul ()
     xxx.as_table () 
   2. form validation
     class XXX (forms.Form):
         Search = forms.CharField (....)
         password1 = ...
         password2 = ...
         DEF clean_search ( Self):
             # to verify the legality of search content
             ...
         DEF Clean (Self):
             # overall verify the legality of all content

    xxx_view DEF (Request):
         xxx = XXX (request.POST)
         IF xxx.is_valid ():
            contents of the form dictionary = xxx.cleaned_data ()


day08 notes
    paging
    file upload
      view files:
         Load and browse through the static file
           http://127.0.0.1:8000/static/files/meinv.png

nginx
    http://127.0.0.1/
    mapped to 127.0.0.1:8000

Project deployment
     Configuration uwsgi Alternatively manage.py
     2. nginx configured to map port 80 to port 8000 uwsgi
     Configuration nginx static route to the home location
     4. interface 404 configure and customize

Huawei cloud deployments
   1. Elastic cloud server later the ECS
   2. Register
   3. name system
   4. Configuration security group, so that the port 80 on the public network can be displayed (hit occurs CS)
   5. Installation Python
   6. The mounting Django
   7. The configuration deployed
       landing remote server:
       $ SSH [email protected]
       $ scp command can be uploaded to the cloud server locally

---------------------------------------------------------------------------------------------------------------------------------


### pages
- when paging means that the web page has a large amount of data needs to be displayed, when the contents of a case of too much is not conducive to reading and unfavorable data extraction can be divided into multiple pages to be displayed.
- Django provides classes to help you manage data pagination - that is, the data is divided in different pages, and with the "Previous / Next" link.
- These classes are in django / core / paginator.py in.

#### Paginator the object
- the object constructor
     - Paginator (the object_list, per_page)
     - parameter
         - the object_list Object list
         - the number of data per per_page
     - Return Value:
         - Object tab

- Paginator Properties
     - count: Total number of objects
     - num_pages: total number of pages
     - page_range: starting from a target range, the number of records for the current face Code
     - per_page page number

- Method Paginator
     - Paginator.page (number)
         - the parameter is the page number information (starting from 1)
         - Returns the page information corresponding to the current page number
         - page number does not exist if provided, throw exception InvalidPage

- Paginator abnormal Exception
     - InvalidPage: When thrown pass an invalid page to page ()
     - PageNotAnInteger: thrown when an incoming value is not an integer to a page ()
     - EmptyPage: When providing page () a valid thrown value, but nothing on that page

#### Page object
- creating an object
page Paginator object () method returns the Page object, does not require manual configuration
- Page Object Properties
     - object_list: list of all objects on the current page
     - number: current page number, starting at 1
     - paginator: objects related to the current page paginator objects
- Page object methods
     - has_next (): If there is a next return True
     - has_previous (): If there Previous Back True
     - has_other_pages (): If there are previous or next page returns True
     - next_page_number (): returns the next page number, if there is no next, an exception is thrown InvalidPage
     - previous_page_number (): return to the previous page number, if the previous does not exist, an exception is thrown InvalidPage
     - len (): returns the current page number of objects
- Description:
     - page objects are iterable, you can use for statements to access each object on the current page

- Reference document < https://docs.djangoproject.com/en/1.11/topics/pagination/ >


- Paging Example:
     - a view function
     `` `Py
     DEF Book (Request):
         BKS = models.Book.objects.all ()
         the paginator = Paginator (BKS, 10)
         Print ( 'the current total number of objects is:', paginator .count)
         Print ( 'current range code object plane is:', paginator.page_range)
         Print ( 'total number of pages is:', paginator.num_pages)
         Print ( 'the maximum number of page:', paginator.per_page)

        cur_page = request.GET.get ( 'page', 1) # get the default this page
         Page paginator.page = (cur_page)
         return the render (Request, 'Bookstore / book.html', about locals ())
     `` `
     - Template design
     `` `HTML
     <HTML>
     <head>
         <title> pagination </ title>
     </ head>
     <body>
     {%}% for Page B in
         <div> b.title {{}} </ div>
     { % endfor%}

    {# #} Paging function
     {Previous function # #}
     {%}% IF page.has_previous
     <a href="{% URL "book" %}?page={{ page.previous_page_number }}"> Previous </a>
     {%}% the else
     Previous
     {% endif%}

    {% for p in paginator.page_range %}
         {% if p == page.number %}
             {{ p }}
         {% else %}
             <a href="{% url "book" %}?page={{ p }}">{{ p }}</a>
         {% endif %}
     {% endfor %}

    Next function {#} #
     {%}% IF page.has_next
     <a href="{% URL "book" %}?page={{ page.next_page_number }}"> Next </a>
     {% else%}
     Next
     {% endif%}
     pages: page.len {{}}
     </ body>
     </ HTML>
     `` `


Day08 ##
<-! <Upload files can be modified for each update it after uploading pictures> ->

### File Upload
- File Upload must be submitted to the POST mode
- form `<form>` upload file must have with `enctype =" multipart / form- data " will be included when the file contents data`.
- form with `<input type =" file " name =" xxx ">` upload tag
     - the corresponding name `xxx`` request.FILES [ 'xxx'] `buffer memory corresponding stream object file. You can lead a `request.FILES [ 'xxx']` upload file object returned data acquisition
     - `file = request.FILES [ 'xxx ']` file stream object binding file, the file may be acquired by the object information file stream data
         file.name file name of
         the byte stream data files file.file
        
- upload files to the following picture type, the type can be defined as a module class attribute models.ImageField
     - `image_file = models.ImageField (upload_to = 'images /')`
     - Note: If the attribute type is ImageField need to be installed pilow
     - PIP install Pillow == 3.4.1
     - Image storage path
- exercise:
     create a static folder in the project root directory
     after upload pictures, is saved in the "/ static / files / "

     MEDIA_ROOT = os.path.join (BASE_DIR, "static / files")
     using the django management background, experience ImageField type of property will be a file box, complete the file upload
     manually uploaded template code

- upload files written form
`` `HTML
<- File:! Static / upload.html ->
<HTML>
<head>
     <title> File Upload </ title>
     <Meta charset =" UTF-8 ">
</ head>
<body>
     <h1 of> upload </ h1 of>
     <form Method = "POST" Action = "/ Upload" the enctype = "multipart / form-Data">
         <INPUT type = "file" name = "myfile "/> <br>
         <the INPUT of the type =" the Submit "value =" upload ">
     </ form>
</ body>
</ HTML>
` ``

- set a variable used to record the location MEDIA_ROOT setting.py the uploaded file
`` `Py
# File: the settings.py
...
STATIC_URL = '/ static /'
STATICFILES_DIRS = (
     the os.path.join (base_dir, 'static '),
)
MEDIA_ROOT = os.path.join (base_dir,' static / files')
...
`` `
- create a` static in the current project folder / files` folder
`` `
$ mkdir -p static / Files
`` `
- adding the corresponding routing and handling functions
` `` Py
# File the urls.py
the urlpatterns = [
     URL (R & lt 'ADMIN ^ /', admin.site.urls),
     URL (R & lt '^ Upload', views. upload_file)
]
`` `
- view handler upload files
` `` Py
# file views.py
from django.http Import HttpResponse, Http404
from django.conf import settings
import os

# from  django.views.decorators.http import require_POST
# @require_POST
def upload_file(request):
     if request.method == "POST":
         file = request.FILES['myfile']
         print("上传文件名是:", file.name)

        the os.path.join = filename (settings.MEDIA_ROOT, file.name)
         with Open (filename, 'WB') AS F:
             f.write (file.file.read ())
             return the HttpResponse ( "successfully received file")
     The raise Http404
`` `
- access address: < http://127.0.0.1:8000/static/upload.html >


### Deployment Project
- Project portion disposed in the software developed, the development of software running on the boards actually mounted to the machine running on a server for long-term
- the deployment steps to be divided into the following
     1. installed and configured on a mounting machine the same version of the database
     1. django project migration (configured on the machine installation and development of the same python version and environment in accordance with lazy bag)
     1. start `python3 manage.py runserver` alternative method uwsgi server
     1. configure nginx reverse proxy server
     1. nginx static configuration file path, a path to solve the problem of static

1. Install the same version of the database
     - installation steps slightly
2. django project migration
     1. Install Python
         - `APT python3` $ sudo install
     2. Install the same version of the package
         - Export current module information packet:
             -` $ PIP3 Freeze> package_list.txt`
         - into another new host
             - `$ PIP3 install -r package_list.txt`
     3. copy the current project source code into fortune host (scp command)
         - $ sudo scp -a source code of the remote host the current project address and folder
3.


#### WSGI Django working environment deployment
- WSGI (Web Server Gateway Interface) Web Server Gateway Interface, is an interface between the framework and Python applications or Web server, is widely used
- it implements the WSGI protocol, http, etc. protocol. Nginx role in HttpUwsgiModule uWSGI is exchanged with the server. WSGI is a Web Server Gateway Interface.

<-! Ubuntu 16.04 Configuration
  ->
#### uWSGI Gateway Interface Configuration
- use `python manage.py runserver` usually only used in the development and test environments.
- After the end of development, improve project code needs to run in a highly efficient and stable environment, then you can use uWSGI
- uWSGI is a WSGI, it can make Django, Flask such as the development of web sites run them.

-  安装uWSGI
     $ sudo pip3 install uwsgi

- Configuration uWSGI
     `` `INI
     # File: The project folder /uwsgi.ini #: mysite1 / uwsgi.ini
     [to uwsgi]
     # the IP address of the socket of the embodiment: port number
     # Socket = 127.0.0.1: 8000
     # the Http communication IP address mode: the port number of the
     HTTP = 127.0.0.1: 8000
     # items in the current working directory
     chdir = / home / weimz / my_django_project ... here need to change the address for the project
     # project directory wsgi.py file, relative to the current working Catalog
     WSGI-file = my_django_project / wsgi.py
     # process number
     process = 4
     # is the number of threads per process
     threads = 2
     # services pid file records
     the PidFile = uwsgi.pid
     # service project log file location
     daemonize = uwsgi. log
     `` `

- uWSGI operation management
     - start uwsgi
         `` `shell
         $ cd project folder
         $ sudo uwsgi --ini project folder /uwsgi.ini
         ` ``
     - stop uwsgi
         `` `shell
         $ cd project folder
         $ sudo uwsgi - uwsgi.pid sTOP
         `` `
     - Description:
         - after uwsgi start, the current django project program has become a daemon, this process does not stop when you close the current terminal.
- Test:
     - input in the browser < http://127.0.0.1:8000 > test
     - Note that, at this time the port number 8000

#### nginx reverse proxy configuration
- Nginx is a lightweight, high-performance Web server, such as providing HTTP proxy and a reverse proxy, load balancing, caching and a series of important characteristics, widely used in practice.
- written in C language, high efficiency

- nginx role
     - load balancing, multiple server processes the request in turn
     - reverse proxy
- How it works:
     - Client Request nginx, and then by nginx request uwsgi, python django run under the code

- nginx installation under Ubuntu
     $ sudo APT install nginx

- nginx configuration
     - Modify nginx configuration file / etc / nginx / sites-the Available / default
     `` `
     # to add a new entry in the server node location, point uwsgi the ip and port.
     {Server
         ...
         LOCATION / {
             uwsgi_pass 127.0.0.1:8000; # redirected to 127.0.0.1 port 8000
             include / etc / nginx / uwsgi_params; # all the parameters to the next to uwsgi
         }
         ...
     }
     `` `
- start nginx`
     $ sudo /etc/init.d/nginx start`
     - or
     - `$ sudo Service nginx restart`
- View nginx process
     - the AUX PS` $ | grep nginx`
     - or
     - `$ sudo / etc / init .d / nginx status`
     - or
     - `$ sudo service nginx status`
- Stop nginx
     - `$ sudo /etc/init.d/nginx stop`
     - or
     -` $ sudo Service nginx stop`
- Restart nginx
     - `$ sudo /etc/init.d/nginx restart`
     - or
     -` $ sudo service nginx restart`

- Modify uWSGI configuration
     - modify `Http communication project folder under / uwsgi.ini` to socket communication, such as:
     ` `` INI
     [to uwsgi]
     # removed as
     # HTTP = 127.0.0.1: 8000
     # to
     socket 127.0.0.1 =: 8000
     `` `
     - restart uWSGI service
     ` `` shell
     $ sudo uwsgi --stop uwsgi.pid
     $ sudo uwsgi --ini project folder /uwsgi.ini

- Test:
     - input in the browser < of http://127.0.0.1 > test
     - Note that, at this time the port number is 80 (nginx default)

#### nginx configure a static file path
- a path to solve the problem of static
     `` `the INI
     # File: / etc / nginx / sites-the Available / default
     # newly added location / static routing configuration, redirected to the specified absolute path to
     Server {
         . ..
         lOCATION / static {
             # root absolute path to the folder where the static, such as:
             root / Home / weimz / my_django_project; # redirect / static request path, where instead of your project file folder
         }
         ...
     }
     `` `
- after modifying the configuration file you need to restart the service nginx

#### 404 interface
- add 404.html template in the template file folder, when a response is returned HttpResponseNotFound or raise Http404 will be displayed
- 404.html only in the release version (ie setting.py when the DEBUG = False ) it works
- when the handler should trigger Http404 will jump to 404 interface anomalies
     `` `Py
     from django.http Import Http404
     DEF xxx_view (Request):
         the raise Http404 # 404 direct return
     ` ``

Guess you like

Origin www.cnblogs.com/shengjia/p/11229572.html