Django Framework csv Files and Project Deployment

Keywords: Django Nginx sudo Python

Django Web Framework Teaching Notes

Catalog

Article directory

User authentication in Django (using Django authentication system)

  • Django comes with a user authentication system. It handles user accounts, groups, permissions, and cookie-Based user sessions.

  • Effect:

    1. Add ordinary and super users
    2. Change Password
  • Document see

  • https://docs.djangoproject.com/en/1.11/topics/auth/

  • User Model Class

  • Location: from django.contrib.auth.models import User

  • The basic properties of the default user are:

    Attribute name type Is it necessary?
    username User name yes
    password Password yes
    email mailbox Optional
    first_name name
    last_name surname
    is_superuser Is it an administrator account (/ admin)
    is_staff Can you access admin management interface?
    is_active Whether it is an active user or not, default True. Generally, the user is_activity is set to False instead of deleting the user.
    last_login Last logon time
    date_joined Time of user creation
  • Representation form of database

mysql> use myauth;
mysql> desc auth_user;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| password     | varchar(128) | NO   |     | NULL    |                |
| last_login   | datetime(6)  | YES  |     | NULL    |                |
| is_superuser | tinyint(1)   | NO   |     | NULL    |                |
| username     | varchar(150) | NO   | UNI | NULL    |                |
| first_name   | varchar(30)  | NO   |     | NULL    |                |
| last_name    | varchar(30)  | NO   |     | NULL    |                |
| email        | varchar(254) | NO   |     | NULL    |                |
| is_staff     | tinyint(1)   | NO   |     | NULL    |                |
| is_active    | tinyint(1)   | NO   |     | NULL    |                |
| date_joined  | datetime(6)  | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
11 rows in set (0.00 sec)

Auh Basic Model Operation:

  • Create user
    • Create ordinary user create_user
      from django.contrib.auth import models
      user = models.User.objects.create_user(username='User name', password='Password', email='mailbox',...)
      ...
      user.save()
      
    • Create superuser create_superuser
      from django.contrib.auth import models
      user = models.User.objects.create_superuser(username='User name', password='Password', email='mailbox',...)
      ...
      user.save()
      
  • delete user
    from django.contrib.auth import models
    try:
        user = models.User.objects.get(username='User name')
        user.is_active = False  # Note that the current user is invalid
        user.save()
        print("Successful deletion of ordinary users!")
    except:
        print("Failed to delete ordinary users")
    return HttpResponseRedirect('/user/info')
    
  • Modify the password set_password
    from django.contrib.auth import models
    try:
        user = models.User.objects.get(username='xiaonao')
        user.set_password('654321')
        user.save()
        return HttpResponse("Successful password modification!")
    except:
        return HttpResponse("Failed to change password!")
    
  • Check if the password is correct check_password
    from django.contrib.auth import models
    try:
        user = models.User.objects.get(username='xiaonao')
        if user.check_password('654321'):  # Successful return to True, failure return to False
            return HttpResponse("Password correct")
        else:
            return HttpResponse("Password error")
    except:
        return HttpResponse("No such user!")
    

Generating CSV files

Django can directly generate csv files in view functions and respond to browsers

import csv
from django.http import HttpResponse
from .models import Book

def make_csv_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="mybook.csv"'
	all_book = Book.objects.all()
    writer = csv.writer(response)
    writer.writerow(['id', 'title'])
    for b in all_book:    
    	writer.writerow([b.id, b.title])

    return response
  • The response yields a special MIME type text / csv. This tells the browser that the document is a CSV file, not an HTML file.
  • The response will get an additional Content-Disposition header containing the name of the CSV file. It will be used by browsers to "save as..." Dialog box
  • For each line in the CSV file, call writer.writerow to pass an iteratable object, such as a list or tuple.

Email

  • Sending E-mail by QQ Mailbox
  • The django.core.mail subpackage encapsulates the SMT protocol for automatically sending e-mail
  • Previous preparations:
    1. Apply for QQ number
    2. Login QQ Mailbox with QQ Number and Modify Settings
      • Log in with the QQ number and password you applied for https://mail.qq.com/
      • Modify QQ Mailbox - > Settings - > Accounts - > "POP3/IMAP... Services"
    3. Setting up Django server side, sending e-mail with Simple Mail Transfer Protocol
  • settings.py settings
# Send Mail Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Fixed writing
EMAIL_HOST = 'smtp.qq.com' # Tencent QQ Mailbox SMTP Server Address
EMAIL_PORT = 25  # Port number of SMTP service
EMAIL_HOST_USER = 'xxxx@qq.com'  # QQ mailbox for sending mail
EMAIL_HOST_PASSWORD = '******'  # Mailbox password (QQ password)
EMAIL_USE_TLS = True  # Whether to start TLS link (secure link) default false when communicating with SMTP server

View function

from django.core import mail
mail.send_mail(
            subject,  #subject
            message,  # Message content
            from_email,  # Sender [current configuration mailbox]
            recipient_list=['xxx@qq.com'],  # Receiver mailing list
            auth_password='xxxxxxx'  # In QQ Mailbox - > Settings - > Accounts - > POP3/IMAP... Services, get the third party login QQ Mailbox Authorization Code
            )

Project deployment

  • Project deployment is to install the development board software running on the development machine to the server for long-term operation after the completion of software development.
  • Deployment takes the following steps
    1. Install and configure the same version of the database on the installation machine
    2. django project migration (configuring the same python version and lazy packages on the installation machine as the development environment)
    3. Using uwsgi instead of Python 3 management.py runserver to start the server
    4. Configuring nginx reverse proxy server
    5. Using nginx to configure the static file path to solve the static path problem
  1. Install the same version of the database

    • Installation steps
  2. django project migration

    1. Install python

      • $ sudo apt install python3
    2. Install the same version of packages

      • Export the information of the current module packet:
        • $ pip3 freeze > package_list.txt
      • Import to another new host
        • $ pip3 install -r package_list.txt
    3. Copy the current project source code to the remote host (scp command)

      • Sudo scp-a Current Project Source Code Remote Host Address and File Folder

      • sudo scp -a /home/tarena/django/mysite1 root@88.77.66.55:/home/root/xxx
        //Please enter the root password:
        

WSGI Django Work Environment Deployment

  • WSGI (Web Server Gateway Interface)Web server gateway interface is an interface between Python applications or frameworks and Web servers, which is widely used.
  • It implements WSGI protocol, http protocol and so on. The function of HttpUwsgiModule in Nginx is to exchange with the uWSGI server. WSGI is a Web server gateway interface.

uWSGI Gateway Interface Configuration (ubuntu 18.04 Configuration)

  • Using Python management.py runserver is usually used only in development and test environments.

  • When the development is finished, the perfect project code needs to run in an efficient and stable environment, then uWSGI can be used.

  • uWSGI is a kind of WSGI, which can let the web sites developed by Django, Flask run among them.

  • Install uWSGI

    • Install uwsgi Online
      $ sudo pip3 install uwsgi
      
    • Off line installation
      1. Download the installation package online:
        $ pip3 download uwsgi
        
        • The downloaded file is uwsgi-2.0.18.tar.gz
      2. Off line installation
        $ tar -xzvf uwsgi-2.0.18.tar.gz
        $ cd uwsgi-2.0.18
        $ sudo python3 setup.py install
        
  • Configure uWSGI

    • Add Configuration File Project Folder / uwsgi.ini

      • For example: mysite1/uwsgi.ini
      [uwsgi]
      # IP address of socket mode: port number
      # socket=127.0.0.1:8000
      # IP Address of Http Communication: Port Number
      http=127.0.0.1:8000
      # Current working directory of the project
      chdir=/home/tarena/.../my_project Here you need to change to the absolute path of the project folder
      # The directory of the wsgi.py file in the project, relative to the current working directory
      wsgi-file=my_project/wsgi.py
      # Number of processes
      process=4
      # Number of threads per process
      threads=2
      # pid record file for service
      pidfile=uwsgi.pid
      # Location of the service's log file
      daemonize=uwsgi.log
      
    • Modify settings.py to change DEBUG=True to DEBUG=False

    • Modify settings.py to change ALLOWED_HOSTS= [] to ALLOWED_HOSTS= ['*']

  • Operation Management of uWSGI

    • Start uwsgi

      cd project folder
       sudo uwsgi --ini project folder / uwsgi.ini
      
    • Stop uwsgi

      $ cd Project Folder
      $ sudo uwsgi --stop uwsgi.pid
      
      
      ps aux | grep 'uwsgi'
      sudo kill -9 process id
      
    • Explain:

      • When uwsgi is started, the program of the current django project has become a daemon, and the process will not stop when the current terminal is closed.
  • Test:

nginx reverse proxy configuration

  • Nginx is a lightweight high-performance Web server. It provides a series of important features such as HTTP proxy and reverse proxy, load balancing, caching and so on. It is widely used in practice.

  • C Language Writing, High Efficiency of Implementation

  • Role of nginx

    • Load balancing, multiple servers take turns processing requests
    • Reverse proxy
  • Principle:

  • The client requests nginx, and then the nginx requests uwsgi to run python code under django

  • nginx installation under ubuntu
    $ sudo apt install nginx

  • nginx configuration

    • Modify nginx configuration file/etc/nginx/sites-available/default
    # Add a new location item under the server node to point to the ip and port of uwsgi.
    server {
        ...
        location / {
            uwsgi_pass 127.0.0.1:8000;  # Redirected to port 127.0.0.1, 8000
            include /etc/nginx/uwsgi_params; # Transfer all parameters to uwsgi
        }
        ...
    }
    
  • nginx service control

    $ sudo /etc/init.d/nginx start|stop|restart|status
    # or
    $ sudo service nginx start|stop|restart|status
    

    Through start,stop,restart,status, it is possible to start, stop, restart and chap poker status of nginx service.

  • Modify uWSGI configuration

    • Modify Http communication mode under project folder/uwsgi.ini to socket communication mode, such as:
    [uwsgi]
    # Remove the following
    # http=127.0.0.1:8000
    # Change to
    socket=127.0.0.1:8000
    
    • Restart uWSGI service
    $ sudo uwsgi --stop uwsgi.pid
    $ sudo uwsgi --ini Project Folder/uwsgi.ini
    
  • Test:

    • Enter on the browser side http://127.0.0.1 Testing
    • Note that the port number is 80(nginx default)

nginx configuration static file path

  • Solving Static Path Problem

    # file : /etc/nginx/sites-available/default
    # Add a new location/static routing configuration to redirect to the specified absolute path
    server {
        ...
        location /static {
            # The absolute path of the root static folder, such as:
            root /home/tarena/my_django_project; # The path of the redirect/static request is changed to the folder of your project
        }
        ...
    }
    	sudo vim /var/log/nginx/error.log	View error log
    
  • The nginx service needs to be restarted after modifying the configuration file

404 interface

  • Add a 404.html template to the template folder and it will be displayed when the view triggers an Http404 exception
  • 404.html only works in the release (when DEBUG=False in set. py)
  • When the Http404 exception is triggered to the appropriate handler, it jumps to the 404 interface.
    from django.http import Http404
    def xxx_view(request):
        raise Http404  # Direct return 404
    

Posted by mark103 on Mon, 23 Sep 2019 04:43:35 -0700