重修課程day57(Django的開始)
阿新 • • 發佈:2017-11-26
tex contex ado rec spl pan type socket 參數
一 瀏覽器相關知識
http:只有依賴一回,屬於短鏈接,不會報錯客戶端的信息。
瀏覽器相當於一個客戶端,客戶端的鏈接
服務端:socket服務端,起服務監聽客戶端的請求。
import socket sk=socket.socket() sk.bind((‘192.168.11.38‘,8888)) sk.listen(5) def index(): with open(‘輪播網頁.html‘,encoding=‘utf-8‘)as f: ret=f.read() return ret def login(): with open(‘login.html‘,encoding=‘utf-8‘)as f: ret=f.read() import pymysql conn=pymysql.connect( host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘0410‘, db=‘day46‘ ) cursor=conn.cursor() cursor.execute(‘select * from user‘) user_list=cursor.fetchall() cursor.close() conn.close() res=‘‘ for i in user_list: res += ‘‘‘View Code<tr> <td>{}</td> <td>{}</td> <td>{}</td> </tr> ‘‘‘.format(i[0], i[1], i[2]) tables= ret.replace(‘@@xx@@‘,res) return tables def info(): return "這是個人信息" info_index=[ (‘/login/‘,login), (‘/index/‘,index), (‘/info/‘,info) ] while True: conn,addr=sk.accept() print(addr) data=conn.recv(8096) data3=str(data,encoding=‘utf-8‘) data1=data3.split(‘\r\n\r\n‘)[0] print(‘*‘*50) print(data1) data2=data1.split(‘\r\n‘)[0].split(‘ ‘)[1] print(data2) ingo_name=None for i in info_index: if data2==i[0]: ingo_name=i[1] break if ingo_name: response=ingo_name() else: response=‘404‘ conn.send(b‘HTTP/1.1 200 0k\r\nContent-Type:text/html;charset=utf-8\r\n\r\n‘) conn.send(response.encode(‘utf-8‘)) conn.close()
二 框架的介紹
tornado:模版都是人家寫好的,我們只管拿來使用。
Django:服務端可以自己寫,其他的模版都是別人寫好的。
flask:服務端和模版渲染都是自己寫的,函數的功能都是別人寫好了的。
所有的web框架叫做web應用服務器。
三 django的安裝和使用
安裝:pip install django。
創建項目:django-admin startproject 項目名
手動創建:
查看參數:django-admin。
開啟項目:python manage.py runserver
響應格式:
{
"接收到的想要":回復
。。。。。
}
四 使用
request:代表所有請求的內容
request.method
request.POST.get(‘***‘)
新手三件套:
導入:from django.import import
HttpResponse:http的響應
render:渲染
render(request, ‘html文件‘)
render(request,"html文件",{"替換的內容":值})
redirect:跳轉頁面
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import render,redirect
def mysql():
import pymysql
user_dic = {}
conn=pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="0410", db="day43", charset="utf8")
cursor=conn.cursor()
cursor.execute(‘select name,password from user‘)
user_list = cursor.fetchall()
cursor.close()
conn.close()
for user in user_list:
user_dic[user[0]]=user[1]
return user_dic
def login(request):
if request.method==‘GET‘:
return render(request,‘登陸界面.html‘)
else:
user_dic=mysql()
for user in user_dic:
if request.POST.get(‘user‘)==user and request.POST.get(‘passwd‘)==user_dic[user] and request.POST.get(‘pwd‘)==user_dic[user]:
return redirect(‘http://www.xiaohuar.com/hua/‘)
elif request.POST.get(‘user‘)==user and request.POST.get(‘passwd‘)==user_dic[user] and request.POST.get(‘pwd‘)!=user_dic[user]:
return render(request, ‘登陸界面.html‘, {‘error_msg‘: ‘密碼輸入不一致‘})
else:
return render(request,‘登陸界面.html‘,{‘error_msg‘:‘用戶名和密碼錯誤‘})
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/‘,login)
]
View Code
模版語言:
格式1:
{% for i in **%}
{{x}}
{% endfor %}
格式2:
{{ 變量名 }}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .c1 { width: 100%; height: 50px; background-color:#DDDDDD; opacity: 0.3; } .c4{ width:80%; height:50px; background-color:#DDDDDD; margin-left: 10%; } .c7{ width: 100px; height: 50px; float:left; } .c8{ width: 80px; height: 50px; float:right; } .c9{ width: 120px; height: 50px; float:right; } .c10{ width: 80px; height: 50px; float:right; } .c11{ width: 80px; height: 50px; float:right; } .c12{ width: 50px; height: 50px; float:right; } .s1{ line-height:50px; text-align: center; color:#1F1E1E; } .c2{ width:100%; height: 60px; background-color: #ffffff; margin-top: 20px; } .c5{ width: 80%; height: 60px; background-color: #FFFFFF; margin-left: 10%; } .c3{ width:100%; height:auto; } .c6{ width: 80%; height: auto; margin-left: 10%; } .d1{ width: 500px; height: 400px; float: left; margin-top: 50px; } .d3{ width: 500px; height: 50px; margin-top:60px; } .s2{ font-weight:600; font-size:30px; color: #2e2e2e; line-height:50px; margin-left: 70px; } .p1{ margin-left: 120px; } .p2{ margin-left: 104px; } .i2{ margin-left: 15px; } .s3{ color:red; } .p4{ margin-left: 150px; } .s4{ color:#0000CC; } .i3{ font-size: 14px; } .p5{ margin-left: 200px; } .i5{ font-size: 10px; background-color:red; } .d2{ width: 314px; height:400px; float: right; margin-top: 50px; } .p6{ margin-left:30px; } .p7{ margin-top: 50px; } </style> </head> <body> <div class="c1"> <div class="c4"> <div class="c7"><span class="s1">*收藏網址</span></div> <div class="c8"><span class="s1">客戶服務</span></div> <div class="c9"><span class="s1">VIP會員俱樂部</span></div> <div class="c10"><span class="s1">我的訂單</span></div> <div class="c11"><span class="s1">免費註冊</span></div> <div class="c12"><span class="s1">登陸</span></div> </div> </div> <div class="c2"> <div class="c5"><img src="111.png" alt="悟空"></div> </div> <div class="c3"> <div class="c6"> <div class="d1"> <div class="d3"><span class="s2">註冊新用戶</span></div> <form action="/login/" method="post"> <p class="p1"><span class="s3">*</span>用戶名:<input type="text" name="user" class="i2"></p> <p class="p1"><span class="s3">*</span>手機號:<input type="text" name="phone" class="i2"></p> <p class="p2"><span class="s3">*</span>登陸密碼:<input type="password" name="passwd" class="i2"></p> <p class="p2"><span class="s3">*</span>確認密碼:<input type="password" name="pwd" class="i2"></p> <p class="p4"><input type="checkbox" name="ppp"><span class="i3">我已閱讀並同意</span><span class="s4 i3">《用戶註冊協議》</span> </p> <p class="p5"><input type="submit" value="開始登錄" class="i5"></p> {{ error_msg }} </form> </div> <div class="d2"> <p class="p6 p7"><img src="222.png" alt="悟天" width=‘250px‘ height="200px"></p> </div> </div> </div> </body> </html>View Code
setting文件的配置:
添加路徑:
TEMPLATES = [ { ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [], # 在這裏進行設置 ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘, ‘django.contrib.messages.context_processors.messages‘, ], }, }, ]
註釋內容:
2. 中間件需要註釋一個 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‘, ]
靜態文件設置:
STATIC_URL = ‘/static/‘ STATICFILES_DIRS = ( os.path.join(BASE_DIR, "ss"), # 靜態文件存放位置 )
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘#vofy$6d=w^aoa0kk#8jhtc3mno9o)eil^8-a^u=)cana=9zq^‘
# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
]
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‘,
]
ROOT_URLCONF = ‘bigJob.urls‘
TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)]
,
‘APP_DIRS‘: True,
‘OPTIONS‘: {
‘context_processors‘: [
‘django.template.context_processors.debug‘,
‘django.template.context_processors.request‘,
‘django.contrib.auth.context_processors.auth‘,
‘django.contrib.messages.context_processors.messages‘,
],
},
},
]
WSGI_APPLICATION = ‘bigJob.wsgi.application‘
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.sqlite3‘,
‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
‘NAME‘: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator‘,
},
{
‘NAME‘: ‘django.contrib.auth.password_validation.MinimumLengthValidator‘,
},
{
‘NAME‘: ‘django.contrib.auth.password_validation.CommonPasswordValidator‘,
},
{
‘NAME‘: ‘django.contrib.auth.password_validation.NumericPasswordValidator‘,
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = ‘en-us‘
TIME_ZONE = ‘UTC‘
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = ‘/static/‘
STATICFILES_DIRS=(os.path.join(BASE_DIR,‘css‘),)
IEMPLATE_DIRS=(os.path.join(BASE_DIR,‘templates‘),)
View Code
重修課程day57(Django的開始)