Django跨域、cookie、session
阿新 • • 發佈:2019-03-12
跨域訪問 cached alt false dir rtc 都是 個人 ror
前後臺分離開發
1.前臺頁面運行在前臺服務器上,負責頁面的渲染(靜態文件的加載)與跳轉
2.後臺代碼運行在後臺服務器上,負責數據的處理(提供數據請求的接口)
跨域
什麽是跨域?
通常情況下,A網頁訪問B服務器時,不滿足以下三個條件中,其中之一就是跨域訪問:
1.協議不同;
2.端口不同;
3.主機不同
如何解決?
#安裝django-cors-headers模塊 #在settings.py中配置 #註冊app INSTALLED_APPS = [ ‘corsheaders‘ ] #添加中間件 MIDDLEWARE = [ ‘corsheaders.middleware.CorsMiddleware‘ ] #允許跨域源 CORS_ORIGIN_ALLOW_ALL = True
‘‘‘ 前臺代碼 $.ajax({ url: ‘http://127.0.0.1:8731/login/‘, type: ‘post‘, data: { usr: ‘abc‘, pwd: ‘123‘ }, success: function (data) { console.log(data); // 可以完成頁面的局部刷新 } }) 後臺代碼 def login(request): # 假設數據庫存放的用戶信息為 abc:123 if request.method == ‘POST‘: usr = request.POST.get(‘usr‘, None) pwd = request.POST.get(‘pwd‘, None) if usr == ‘abc‘ and pwd == ‘123‘: return JsonResponse({‘status‘: ‘OK‘, ‘usr‘: usr}) return JsonResponse({‘status‘: ‘error‘, ‘usr‘: None})代碼‘‘‘
文件上傳
瀏覽器:
<form> <input class="file" type="file"> <button type="button" class="upload">上傳</button> </form> <script> $(‘.upload‘).click(function () { var form_data = new FormData(); var file = $(‘.file‘)[0].files[0]; form_data.append(‘file‘, file); $.ajax({ url: ‘跨域上傳地址‘, type: ‘post‘, data: form_data, contentType: false, // 不設置內容類型 processData: false, // 不預處理數據 success: function (data) { console.log(data) } }) }) </script>
後臺:
def upload(request): file = request.FILES.get(‘file‘, None) if file: with open(file.name, ‘wb‘) as f: for line in file: f.write(line) return JsonResponse({ ‘status‘: ‘OK‘, ‘msg‘: ‘upload success‘ })
文件下載
瀏覽器:
<a href="http://127.0.0.1:8121/download/">下載</a> <button type="button" class="download">下載</button> <script> $(‘.download‘).click(function () { location.href = ‘http://127.0.0.1:8121/download/‘ }) </script>
後臺:
def download(request): file = open(‘123.zip‘, ‘rb‘) response = FileResponse(file) response[‘Content-Type‘] = ‘application/octet-stream‘ response[‘Content-Disposition‘] = ‘attachment;filename="%s"‘ % file.name return response
Cookie
1.什麽是cookie?
cookie指的是前端瀏覽器以明文的形式存放具有key、value信息特征的字符串。
2.cookie的作用
在前後臺均可以訪問並設置cookie,從而解決http協議的無狀態特點所導致的前後兩次請求無邏輯可循的問題(例如:不同用戶登錄後,再進入個人主頁,明顯是有信息區別的)
3.cookie簡介
隨著瀏覽器的發展,很多瀏覽器不再對cookie的個數加以限制,但是仍存在大小的限制,一般為4k;但是為了達到傳輸的高效,服務器的解析速度,還是建議開發者嚴格控制cookie的個數。
cookie初始:為頁面文檔document的一個字符串屬性:document.cookie = ‘key=value;‘
Cookie的使用及其參數:
#Django用HttpResponse對象操作Cookie response = HttpResponse(‘所有的響應都是HttpResponse對象‘) #設置cookie:key,value與過期時間(max_age) response.set_cookie(key,value,max_age) #刪除cookie:key response.delete_cookie(key) #設置加鹽cookie:key,value與鹽字符串(就是簡易的加密) response.set_signed_cookie(key,value,salt) #通過request對象獲取cookie # 獲取key對應的value request.COOKIES.get(key, None) # 獲取加鹽後的key對應的value request.get_signed_cookie(key, salt) #set_cookie方法的其他參數 1. expires:過期時間,格式為字符串類型的時間 2. path:作用路徑,/代表所有路徑下均起作用 3. domain:作用域名 4. secure:布爾類型,瀏覽器是否通過HTTPS方式回傳cookie 5. httponly:布爾類型,JS能否直接訪問該條cookie
# views.py from django.shortcuts import render, redirect, HttpResponse # 確認登錄裝飾器 def login_check(func): def inner(request, *args, **kwargs): is_login = request.COOKIES.get(‘is_login‘, False) # 確定當前被裝飾的請求,登錄完畢可以跳轉回去 url = request.get_full_path() if is_login: return func(request, *args, **kwargs) else: # 將回跳的路徑作為參數(登錄的表單action需要空著不寫) return redirect(‘/login/?back_url=%s‘ % url) return inner # 主頁 def index(request): return render(request, ‘index.html‘) # 登錄頁面 def login(request): if request.method == "GET": return render(request, ‘login.html‘) if request.method == "POST": # 獲取回跳的地址 back_url = request.GET.get(‘back_url‘, ‘/index/‘) usr = request.POST.get(‘usr‘, None) pwd = request.POST.get(‘pwd‘, None) if usr == ‘abc‘ and pwd == ‘123‘: # 確定回跳 response = redirect(back_url) # 登錄成功獲取cookie for i in range(500): response.set_cookie(‘usr%i‘ % i, usr) response.set_cookie(‘is_login‘, True) return response @login_check def order(request): print(request.COOKIES) usr = request.COOKIES.get(‘usr‘, None) return render(request, ‘order.html‘, locals()) @login_check def user(request): usr = request.COOKIES.get(‘usr‘, None) return render(request, ‘user.html‘, locals()) def logout(request): response = HttpResponse(‘註銷成功‘) response.delete_cookie(‘is_login‘) response.delete_cookie(‘usr‘) return responsecookie實例
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主頁</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> </head> <body> <div class="container"> <div class="row"> <h1 class="page-header text-info text-center">主頁</h1> </div> <div class="row"> <a href="/login/" class="btn text-danger"><h3>登錄</h3></a> <a href="/user/" class="btn text-info"><h3>個人主頁</h3></a> <a href="/order/" class="btn text-info"><h3>訂單詳情</h3></a> <a href="/login_out/" class="btn text-info"><h3>註銷</h3></a> </div> </div> </body> </html> login.html <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄界面</title> <link rel="stylesheet" href="/static/login.css"> </head> <body> <div class="box"> <h2>歡迎登錄</h2> <form action="" method="post"> <div class="usr"> 用 戶:<input type="text" name="usr" placeholder="請輸入用戶名"> </div> <div class="usr"> 密 碼:<input type="password" name="pwd" placeholder="請輸入密碼"> </div> <div class="login"> <input type="submit" value="登錄"> </div> </form> </div> </body> </html> </body> </html> user.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>個人主頁</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> </head> <body> <h1 class="text-primary col-md-6 page-header text-center">{{ usr }}的個人主頁</h1> </body> </html> order.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>訂單詳情</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> </head> <body> <h1 class="page-header text-center text-primary col-md-6">{{ usr }}的訂單詳情</h1> </body> </html>模板層
Session
1.什麽是session?
session指的是在後臺通常以密文的形式存放key,value形式的數據,一個會話存放為數據庫的一條字段。
2.session的作用
必須結合cookie使用,解決了cookie的不安全性。
3.session簡介:session時存放在服務器端的key-value形式的狀態數據。
session使用及其參數:
#常用操作: #設置 request.session[‘key1‘] = ‘value1‘ request.session[‘key2‘] = ‘value2‘ #過程: #1.生成一個隨機字符串,作為主鍵; #2.在django_session表中插入有三個字段的一條數據(一條數據對應一個瀏覽器會話) --session_key:主鍵-隨機字符串 --session_data:該會話擁有的所有key-value形成的大字典的加密字符串 --expire_date:過期時間,默認14天 #3.往瀏覽器中寫入一條cookie,sessionid=主鍵的隨機字符串 #獲取 request.session.get(‘key‘,None) #刪除 request.session.delete() #只刪除當前會話對應的一條記錄 request.session.flush() #除了刪除當前會話對應的一條記錄外,還刪除對應瀏覽器中的cookie #其他 request.session.session_key # 獲取當前會話對應的session_key request.session.exists(‘session_key‘) # 判斷某session_key是否存在 request.session.clear_expired() # 清空所有過期的Session
settings.py中的配置:
1. 數據庫Session SESSION_ENGINE = ‘django.contrib.sessions.backends.db‘ # 引擎(默認) 2. 緩存Session SESSION_ENGINE = ‘django.contrib.sessions.backends.cache‘ # 引擎 SESSION_CACHE_ALIAS = ‘default‘ # 使用的緩存別名(默認內存緩存,也可以是memcache),此處別名依賴緩存的設置 3. 文件Session SESSION_ENGINE = ‘django.contrib.sessions.backends.file‘ # 引擎 SESSION_FILE_PATH = None # 緩存文件路徑,如果為None,則使用tempfile模塊獲取一個臨時地址tempfile.gettempdir() 4. 緩存+數據庫 SESSION_ENGINE = ‘django.contrib.sessions.backends.cached_db‘ # 引擎 5. 加密Cookie Session SESSION_ENGINE = ‘django.contrib.sessions.backends.signed_cookies‘ # 引擎 其他公用設置項: SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在瀏覽器上時的key,即:sessionid=隨機字符串(默認) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路徑(默認) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默認) SESSION_COOKIE_SECURE = False # 是否Https傳輸cookie(默認) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http傳輸(默認) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默認) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否關閉瀏覽器使得Session過期(默認) SESSION_SAVE_EVERY_REQUEST = False # 是否每次請求都保存Session,默認修改之後才保存(默認)
Django跨域、cookie、session