~ Day52 Django early glimpse Login registration system

Recap
1. homochiral line and a simplified version of a web frame
1. The manual processing request socket
2. Manual processing http data, acquired user access url
3. Depending on the response to the user access to different outcomes of url
2.wsgiref module (web services end gateway interface)
encapsulates socket codes
when unsealing the http request of the data format into a large dictionary
in response to take the time to package the data to conform to the requirements of the data format of the http protocol
start
server = make_server ( '127.0.0.1', 8080, run)
# real-time monitoring 127.0.0.1:8080 address once a client to connect automatically parentheses calls the run method
server.serve_forever () # start the server
3. how to transfer data to html page
1. how will the current date to render html r page reading mode >>> html file using the replacement string to string
2. how to render a dictionary and the html page values also simple and fast operation of
rendering template
jinja2 module
rendering template 1 (mass data)
2. template grammar (syntax very close to the python)

from Import template Jinja2
the incoming data in text format html template
the render ()

template syntax
{{data}}
User in user_list% for {%}
{%}% endfor

templates are only two syntax
{} {}: related variables
{%%}: logically related

4. unsealing different functions into different file
templates folder (specifically put the html file)
urls.py
views.py

for this we recommend version of the web framework if you want to add a feature only in
each write a bit of code to the above two documents

HTTP protocol
1. The characteristics of the four
1-based TCP / IP protocol over the role of the application layer
2. Based on the request response
3. stateless
Cookie
the session
token
4. connectionless
Keep-Alive

WebSocket (mainly used in a chat room related functions)

2. request response data format
request the first line (request mode protocol version)
request header (a bunch k: v key-value pairs) carrying the information is similar to pioneer some of the server can know ahead of time of

the request body (post to send the request to carry data will be placed in the body of the request)



the response data format supra
3. the response status codes
1XX
2XX: 200 is
3XX: 301/302
4XX: 404/403
5XX: 500


Python three main frame web
Django
Flask
Tornado


django
order to allow django project normally bubbles on your machine
1. The name of the computer can not have Chinese
2. Project also try not to play a Chinese name
3. a pycharm window allows only one project


django version of the problem
django1.X
django2.X

django download
PIP3 install django == 1.11.11

Python interpreter not to use the latest 3.7, recommended for 3.6 / 3.5 / 3.4


how to determine the successful download
django-admin

create a project django
django-admin startproject project name
with the same name as the project folder
__init__ .py
settings.py exposed to the user-configurable profiles
urls.py
wsgi.py
manage.py
create App
Django-ADMIN startapp App name (students habitual old boy from ... app01)
python3 manage.py startapp App name
the file name of the app folder
migrations folder database operations recorded
__init__.py
apps.py registered app related files
admin.py django backend management-related
models.py orm model class associated
views.py view function (function / class)
tests.py test-related

start django project
python3 manage.py runserver django default port is 8000. The project is started

Note: the command line create a project does not automatically create templates folder
which means you need to manually create and needs in the configuration file on the path to add

app also need to create settings file registered

app concept
django project is similar to a university, app University College which is different
for each college has its own independent function


django white will be three tricks
HttpResponse returns the string

render returns html page

redirect redirect

You first go again with the overall process django
login function, for example
a static configuration file
form the back end how to get the form to submit data
request method
pycharm database connection mysql database using django
django orm Profile
additions and deletions to change search table field
additions and deletions to change search table data


newly created app settings.py register must first go to
the INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
' django.contrib.sessions',
'django.contrib.messages ',
' django.contrib.staticfiles',
# 'app01' # shorthand
'app01.apps.App01Config' # full name
]


HTML files are all placed in the default templates folder
for the preceding document has been written to use so we just take over these files can be called called "static files"
Static files can be
bootstrap preceding frame has been written for a class of
images
CSS
JS
Static files all on static default folder under
static default folder by default subfolders created folder
css folder of the current site all the style file
js file js file of the current site all
img files in the current site all the picture files
to other (front-end framework code third-party plug-in code ...)


start ddjango project when we must make sure that a port number is only a django project in occupied
otherwise would be likely to cause the bug


in the url resources users can access
related resources offer you only the url to access to (******)

back-end resources generally need to manually specify whether the user needs to be exposed to

a static configuration file
STATICFILES_DIRS = [
os.path.join (base_dir, 'static')
]
as long as you enter the static folder path can access specific files to



STATIC_URL = '/ static /' # the name of the folder is not a static but rather an interface prefix
"" "If you want to access a resource file path to a static file must start with a static" ""
# manually static folder, all resources exposed to the user
STATICFILES_DIRS = [
os.path.join (base_dir, 'static'), the real # Folder path
os.path.join (BASE_DIR, 'static1') ,
os.path.join (BASE_DIR, 'static2') , # the real folder path
os.path.join (BASE_DIR, 'static3') # real folder path
]


Django supports automatic restart by default so you only need the code refresh the page several times more than you can
, but sometimes it's restart mechanism is relatively slow
mechanism: real-time monitoring file changes as long as the code changes will automatically restart
possible that your code has not yet finished this time will automatically be given


a static file interface prefix "dynamic analytical "
{%} static Load%

<Link the rel = "this stylesheet" the href = "{% static 'on Bootstrap-3.3.7-dist / CSS / bootstrap.min.css'}%">
<Script the src = "{% static' on Bootstrap-3.3.7-dist /js/bootstrap.min.js'%} "> </ script>
using parser dynamically obtaining interface prefix



form is the default form get request
carrying data mode is followed by the data url regards
http://127.0.0.1:8000/login /? username = zekai & password = 123

by method post request to
change the settings after post requests need to file a comment out intermediate
mIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware .SessionMiddleware ',
' django.middleware.common.CommonMiddleware ',
#' django.middleware.csrf.CsrfViewMiddleware ',
' django.contrib.auth.middleware.AuthenticationMiddleware ',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

form form submission action by the destination data
in the case 1. The default is not written to the current address filed
2 can also be written suffix / index / (used this project)
3. Also you can write the whole path to

view the main function will first deal with the general get request
DEF the Login (request):
# view function for different request should have different ways of processing logic
# IF request.method == 'GET':
# Print ( 'received ')
# Print (request.method) # manner and capable of acquiring distal request string is all uppercase
# Print (type (request.method))
# return the render (request,' the login.html ')
# = elif request.method = 'the POST':
# # get user input logic is determined accordingly
# return HttpResponse ( "get brother")
IF request.method == 'the POST':
return the HttpResponse ( 'coming baby')
return the render (Request, ' login.html ')


Acquires front-end data
request.method acquisition request method

Processing of the data is not just only wsgiref django backend module also done a lot of data processing
GET
request.GET data acquisition front-end get submitted (it is like a big dictionary)
values
request.GET.get ( 'username') # Although the default value is a list, but just take a list of the last element
# strongly recommended that you use the form values in brackets

# if you want directly to list all out (******)
request.GET.getlist ( 'Hobby' )
POST
request.POST data acquisition front-end post submission (it is like a big dictionary)
values
request.POST.get ( 'username') # Although the default value is a list, but just take a list of the last element
# strongly recommend that you use the form values in brackets

# if you want directly to list all out (******)
request.POST.getlist ( 'Hobby')


Django defaults are built-in sqlite database
if you want it to another database settings need to be configured in the configuration file
1.settings configuration file
dATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Day5l '
'The HOST': '127.0.0.1',
'PORT': 3306,
'the USER': 'the root',
'PASSWORD': '123',
'the CHARSET': 'UTF8'
}
}
2. also in the name of the project init file or an application file name init told not to use the default django mysqldb mysql connection
but rather pymysql
Import pymysql
pymysql.install_as_MySQLdb ()






django ORM
the ORM object relational mapping
table class
a record target
object's property value corresponding to the field


first need to write a model class in models.py under application
class User (models.Model):
# id field to the User table primary key fields in django orm you can not write to the master key django dictionary will default to your table to create a the primary key field named id
# id = models.AutoField (primary_key = True ) # Once you specify the primary key field that will not be django will help you automatically create a
username = models.CharField (max_length = 32) # username varchar ( 32) CharField must specify the parameters max_length
= models.IntegerField password () # password int
************************* need to perform database migration (synchronous) command ******* ***********************
python3 manage.py makemigrations # just does not operate directly (migrations folder) to modify the database records of data on a small notebook
python3 manage.py migrate # modify the database record actually synchronized to the database
Note: just move the models in the code associated with the database must be re-implementation of the above two commands are indispensable (******)



by table fields deletion check
increased
when the table has been created out of a subsequent want to add fields, there are two ways
1. the new field to set a default value
addr = models.CharField (max_length = 32, default = 'China') # default this field defaults

2. Give the new field to be empty
age = models.IntegerField (null = True) # This field allows null


deletion (caution)
and re-execute two command to delete the comment field in the field directly models.py you can
Note: to delete all the data in the table fields corresponding to all after the execution
and under normal circumstances is basically will not be used to delete the true sense




orm operation requires the use of models in the name of the class of

data check
from app01 import Models

models.User.objects.all () # direct holding all the data

models.User.objects.get (username = username)

RES = models.User.objects.filter (username = username)
res.query

USER_OBJ = res.first ()

data by
1.
models.User.objects.create (username = username, password = password)
2.
USER_OBJ = models.User (username = username, password = password)
user_obj.save ()

delete
models.User.objects .filter (condition) .delete ()

Change
models.User.objects.filter (Condition) .Update ()







user CRUD
1. orm to display all of the front end of
all ()
template syntax for loop
2. Add New button (the user's new operation)
A href tag directly triggers the backend logic
Create ()
3. Add edit delete button
edit
delete
using the get request carrying an id value of the characteristic parameter corresponding to the data to keep the back of the url
request.GET.get ()

if it is edited
to re-render a page edited object is passed to the front

if it is deleted
directly filter (...). delete ()



operation
user CRUD page of the form write to me
















Guess you like

Origin www.cnblogs.com/Ryan-Yuan/p/11528327.html