Create django project
django-admin startproject devops
Introduction to Django project directory structure
devops/ |-- manage.py `-- devops |-- __init__.py |-- settings.py |-- urls.py `-- wsgi.py
- The outermost devops / directory is just a part of your project
- manage.py is a practical command-line tool that allows you to interact with the Django project in various ways
- The inner devops / directory is the actual Python package in your project. Through it, you can import anything on its surface
- devops/init.py: an empty file that tells Python that the directory is a Python package
- devops/settings.py: the configuration file of the Django project
- devops/urls.py: URL declaration of the Django project
- devops/wsgi.py: a WSGI compatible Web service portal
Start up service
cd devops python manage.py runserver
Specify the port to start the service
python manage.py runserver 8000
Specify ip and port start service
python manage.py runserver 0.0.0.0:8000
New Django app
1: Create a new app named dashboard
python manage.py startapp dashboard
2: Configure url
from django.conf.urls import include, url urlpatterns = [ ... url(r'^dashboard/', include("dashboard.urls")), ]
3: Activate app
INSTALLED_APPS = ( ...... 'dashboard', )
Example: single file implementation of Hello world
# step 1: Authoring views from django.http import HttpResponse def index(request): return HttpResponse("Hello world !!!") # step 2: configure url from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ]
HttpRequest object
Created by django
Properties:
HttpRequest.scheme HttpRequest.body HttpRequest.path HttpRequest.method HttpRequest.encoding HttpRequest.GET HttpRequest.POST HttpRequest.META
method:
HttpRequest.get_host() HttpRequest.get_port() HttpRequest.get_full_path() HttpRequest.is_secure() HttpRequest.is_ajax()
HttpResponse object
Pass a character as the content of the page to the HttpResponse constructor
>>> from django.http import HttpResponse >>> response = HttpResponse("Here's the text of the Web page.") >>> response = HttpResponse("Text only, please.", content_type="text/plain")
Properties:
HttpResponse.content HttpResponse.charset HttpResponse.status_code HttpResponse.reason_phrase
method:
HttpResponse.__init__(content=", content_type=None, status=200, reason=None, charset=None)
JsonResponse object
JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
Example:
>>> from django.http import JsonResponse >>> response = JsonResponse({'foo': 'bar'}) >>> response.content b'{"foo": "bar"}' >>> response = JsonResponse([1, 2, 3], safe=False)
Load template
# django. template. The loader module provides two methods to load templates get_template(template_name, using=None) # Load the specified Template and return the Template object select_template(template_name_list, using=None)
It works with get_ Similar to template, it tries each name and returns the first existing template to load content from the file
from django.template import Context, loader def index(request): t = loader.get_template("test.html") context = {"name": "hello reboot !!!"} return HttpResponse(t.render(context, request))
Shortcut: render()
from django.shortcuts import render def index(request): context = {'name': "reboot"} return render(request, 'test.html', context)
GET and POST requests
- GET request and parameter transfer
- POST request and data submission
QueryDIct object
- In the HttpRequest object, the GET and POST attributes are Django http. Querydict is a custom dictionary like class used to handle the same key with multiple values. The requirement of this class comes from some HTML form elements to pass multiple values to the same key
- request.POST and request The QueryDict of get is immutable in a normal request / response cycle. To get a variable version, you need to use copy().
Materialized QueryDict
QueryDict.__init__(query_string=None, mutable=False, encoding=None)
Example
>>> QueryDict('a=1&a=2&c=3') <QueryDict: {'a': ['1', '2'], 'c': ['3']}>
Materialize querydict through fromkeys (added in 1.11)
classmethod QueryDict.fromkeys(iterable, value=", mutable=False, encoding=None)
Example
>>> QueryDict.fromkeys(['a', 'a', 'b'], value='val') <QueryDict: {'a': ['val', 'val'], 'b': ['val']}>
QueryDict method:
QueryDict.get(key, default=None) QueryDict.setdefault(key, default=None)[source] QueryDict.update(other_dict) QueryDict.items() QueryDict.values() QueryDict.copy() QueryDict.getlist(key, default=None) QueryDict.setlist(key, list_)[source] QueryDict.appendlist(key, item) QueryDict.setlistdefault(key, default_list=None) QueryDict.lists() QueryDict.pop(key) QueryDict.popitem() QueryDict.dict() QueryDict.urlencode(safe=None)
Actual user login
- 1. Configure django database
- 2. Synchronize data
- 3.Django API user creation
- 4. Execute user login
- 5. Deeply analyze the user login process
Configuration database
- opsweb/settings.py is an ordinary python module. Each configuration is a pair of key/value DATABASES. The configuration is stored in this module in the form of dict. The key name is DATABASES
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'PORT': 3306, } }
Synchronous data
- Use django's command-line tools to synchronize the database
python manage.py migrate
Create user
- Using django shell to create ordinary users: the most direct way to create users is to use create_user() helper function
>>> from django.contrib.auth.models import User >>> user = User.objects.create_user("rock", "rock@51reboot.com", "123456")
Create Manager
>>> python manage.py createsuperuser --username=reboot --email=reboot@51reboot.com
Change Password
- Django does not store the original (plaintext) password on the user model, but just a hash. For this reason, you do not have to try to manipulate the user's password attribute directly. This is also the auxiliary function to be used when creating a user for user.
>>> from django.contrib.auth.models import User >>> u = User.objects.get(username='rock') >>> u.set_password('654321') >>> u.save()
User login
- Follow up explanation of user login process
Django configuration
-
- Configure static files
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
- Configure time zone
TIME_ZONE = 'Asia/Shanghai'