Python學習路程day20

  

本節內容:javascript

項目:開發一個簡單的BBS論壇html

需求:前端

  1. 總體參考「抽屜新熱榜」 + 「虎嗅網」
  2. 實現不一樣論壇版塊
  3. 帖子列表展現
  4. 帖子評論數、點贊數展現
  5. 在線用戶展現
  6. 容許登陸用戶發貼、評論、點贊
  7. 容許上傳文件
  8. 帖子可被置頂
  9. 可進行多級評論
  10. 就先這些吧。。。

知識必備:java

  1. Django
  2. HTML\CSS\JS
  3. BootStrap
  4. Jquery

 

設計表結構  

from django.db import models
 
# Create your models here.
from django.db import models
 
from django.contrib.auth.models import User
# Create your models here.
 
 
 
class Article(models.Model):
    title = models.CharField(max_length=255,unique=True)
    category = models.ForeignKey('Category')
    priority = models.IntegerField(default=1000)
    author = models.ForeignKey("UserProfile")
    content = models.TextField(max_length=100000)
    breif = models.TextField(max_length=512,default='none.....')
    head_img = models.ImageField(upload_to="upload/bbs_summary/")
    publish_date = models.DateTimeField(auto_now_add=True)
 
    def __unicode__(self):
        return self.title
 
class Comment(models.Model):
    bbs = models.ForeignKey('Article')
    parent_comment = models.ForeignKey('Comment',blank=True,null=True,related_name='p_comment')
    user = models.ForeignKey('UserProfile')
    comment = models.TextField(max_length=1024)
    date = models.DateTimeField(auto_now_add=True)
 
    def __unicode__(self):
        return self.comment
 
class Thumb(models.Model):
    bbs = models.ForeignKey('Article')
    action_choices = (('thumb_up','Thumb Up'), ('view_count',"View Count"))
    action = models.CharField(choices=action_choices,max_length=32)
    user = models.ForeignKey('UserProfile')
 
    def __unicode__(self):
        return "%s : %s" %(self.bbs.title,self.action)
 
 
class Category(models.Model):
    name = models.CharField(max_length=32,unique=True)
    enabled = models.BooleanField(default=True)
    def __unicode__(self):
        return self.name
 
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=64)
    user_groups = models.ManyToManyField('UserGroup')
 
    friends = models.ManyToManyField("self",blank=True)
    online = models.BooleanField(default=False)
 
    def __unicode__(self):
        return self.name
 
class UserGroup(models.Model):
    name = models.CharField(max_length=32,unique=True)
 
    def __unicode__(self):
        return self.name
View Code

CSRF(Cross Site Request Forgery, 跨站域請求僞造)

CSRF 背景與介紹

CSRF(Cross Site Request Forgery, 跨站域請求僞造)是一種網絡的攻擊方式,它在 2007 年曾被列爲互聯網 20 大安全隱患之一。其餘安全隱患,好比 SQL 腳本注入,跨站域腳本攻擊等在近年來已經逐漸爲衆人熟知,不少網站也都針對他們進行了防護。然而,對於大多數人來講,CSRF 卻依然是一個陌生的概念。即使是大名鼎鼎的 Gmail, 在 2007 年末也存在着 CSRF 漏洞,從而被黑客攻擊而使 Gmail 的用戶形成巨大的損失。python

CSRF 攻擊實例

CSRF 攻擊能夠在受害者絕不知情的狀況下以受害者名義僞造請求發送給受攻擊站點,從而在並未受權的狀況下執行在權限保護之下的操做。好比說,受害者 Bob 在銀行有一筆存款,經過對銀行的網站發送請求 http://bank.example/withdraw?account=bob&amount=1000000&for=bob2 可使 Bob 把 1000000 的存款轉到 bob2 的帳號下。一般狀況下,該請求發送到網站後,服務器會先驗證該請求是否來自一個合法的 session,而且該 session 的用戶 Bob 已經成功登錄。黑客 Mallory 本身在該銀行也有帳戶,他知道上文中的 URL 能夠把錢進行轉賬操做。Mallory 能夠本身發送一個請求給銀行:http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory。可是這個請求來自 Mallory 而非 Bob,他不能經過安全認證,所以該請求不會起做用。這時,Mallory 想到使用 CSRF 的攻擊方式,他先本身作一個網站,在網站中放入以下代碼: src=」http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory 」,而且經過廣告等誘使 Bob 來訪問他的網站。當 Bob 訪問該網站時,上述 url 就會從 Bob 的瀏覽器發向銀行,而這個請求會附帶 Bob 瀏覽器中的 cookie 一塊兒發向銀行服務器。大多數狀況下,該請求會失敗,由於他要求 Bob 的認證信息。可是,若是 Bob 當時恰巧剛訪問他的銀行後不久,他的瀏覽器與銀行網站之間的 session 還沒有過時,瀏覽器的 cookie 之中含有 Bob 的認證信息。這時,悲劇發生了,這個 url 請求就會獲得響應,錢將從 Bob 的帳號轉移到 Mallory 的帳號,而 Bob 當時絕不知情。等之後 Bob 發現帳戶錢少了,即便他去銀行查詢日誌,他也只能發現確實有一個來自於他本人的合法請求轉移了資金,沒有任何被攻擊的痕跡。而 Mallory 則能夠拿到錢後逍遙法外。jquery

CSRF 攻擊的對象

在討論如何抵禦 CSRF 以前,先要明確 CSRF 攻擊的對象,也就是要保護的對象。從以上的例子可知,CSRF 攻擊是黑客藉助受害者的 cookie 騙取服務器的信任,可是黑客並不能拿到 cookie,也看不到 cookie 的內容。另外,對於服務器返回的結果,因爲瀏覽器同源策略的限制,黑客也沒法進行解析。所以,黑客沒法從返回的結果中獲得任何東西,他所能作的就是給服務器發送請求,以執行請求中所描述的命令,在服務器端直接改變數據的值,而非竊取服務器中的數據。因此,咱們要保護的對象是那些能夠直接產生數據改變的服務,而對於讀取數據的服務,則不須要進行 CSRF 的保護。好比銀行系統中轉帳的請求會直接改變帳戶的金額,會遭到 CSRF 攻擊,須要保護。而查詢餘額是對金額的讀取操做,不會改變數據,CSRF 攻擊沒法解析服務器返回的結果,無需保護。git

 

防護策略:在請求地址中添加 token 並驗證

CSRF 攻擊之因此可以成功,是由於黑客能夠徹底僞造用戶的請求,該請求中全部的用戶驗證信息都是存在於 cookie 中,所以黑客能夠在不知道這些驗證信息的狀況下直接利用用戶本身的 cookie 來經過安全驗證。要抵禦 CSRF,關鍵在於在請求中放入黑客所不能僞造的信息,而且該信息不存在於 cookie 之中。能夠在 HTTP 請求中以參數的形式加入一個隨機產生的 token,並在服務器端創建一個攔截器來驗證這個 token,若是請求中沒有 token 或者 token 內容不正確,則認爲多是 CSRF 攻擊而拒絕該請求。程序員

token 能夠在用戶登錄後產生並放於 session 之中,而後在每次請求時把 token 從 session 中拿出,與請求中的 token 進行比對,但這種方法的難點在於如何把 token 以參數的形式加入請求。對於 GET 請求,token 將附在請求地址以後,這樣 URL 就變成 http://url?csrftoken=tokenvalue。 而對於 POST 請求來講,要在 form 的最後加上 <input type=」hidden」 name=」csrftoken」 value=」tokenvalue」/>,這樣就把 token 以參數的形式加入請求了。可是,在一個網站中,能夠接受請求的地方很是多,要對於每個請求都加上 token 是很麻煩的,而且很容易漏掉,一般使用的方法就是在每次頁面加載時,使用 javascript 遍歷整個 dom 樹,對於 dom 中全部的 a 和 form 標籤後加入 token。這樣能夠解決大部分的請求,可是對於在頁面加載以後動態生成的 html 代碼,這種方法就沒有做用,還須要程序員在編碼時手動添加 token。github

Django 中使用CSRF

How to use it

To take advantage of CSRF protection in your views, follow these steps:ajax

  1. The CSRF middleware is activated by default in the MIDDLEWARE_CLASSES setting. If you override that setting, remember that 'django.middleware.csrf.CsrfViewMiddleware' should come before any view middleware that assume that CSRF attacks have been dealt with.

    If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).

  2. In any template that uses a POST form, use the csrf_token tag inside the <form> element if the form is for an internal URL, e.g.:

    <form action="" method="post">{% csrf_token %}
    

    This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.

  3. In the corresponding view functions, ensure that RequestContext is used to render the response so that {%csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.

CSRF with AJAX

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that allow headers to be set on every request.

As a first step, you must get the CSRF token itself. The recommended source for the token is the csrftokencookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.

 

Acquiring the token is straightforward:

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

The above code could be simplified by using the JavaScript Cookie library to replace getCookie:

var csrftoken = Cookies.get('csrftoken');

Finally, you’ll have to actually set the header on your AJAX request, while protecting the CSRF token from being sent to other domains using settings.crossDomain in jQuery 1.5.1 and newer:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

上傳文件

template form表單 

<form enctype="multipart/form-data"  action="{% url 'new_article' %}" method="post">{% csrf_token %}
 
            上傳標題圖片:<input  type="file" name="head_img" >
      
            <button type="submit" class="btn btn-success pull-right">提交</button>
 
</form>

Consider a simple form containing a FileField:

# In forms.py...
from django import forms
 
class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

A view handling this form will receive the file data in request.FILES, which is a dictionary containing a key for each FileField (or ImageField, or other FileField subclass) in the form. So the data from the above form would be accessible as request.FILES['file'].

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

Most of the time, you’ll simply pass the file data from request into the form as described in Binding uploaded files to a form. This would look something like:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
 
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
 
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

Notice that we have to pass request.FILES into the form’s constructor; this is how file data gets bound into a form.

Here’s a common way you might handle an uploaded file:

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

Looping over UploadedFile.chunks() instead of using read() ensures that large files don’t overwhelm your system’s memory.

There are a few other methods and attributes available on UploadedFile objects; see UploadedFile for a complete reference.

Where uploaded data is stored

Before you save uploaded files, the data needs to be stored somewhere.

By default, if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. This means that saving the file involves only a read from memory and a write to disk and thus is very fast.

However, if an uploaded file is too large, Django will write the uploaded file to a temporary file stored in your system’s temporary directory. On a Unix-like platform this means you can expect Django to generate a file called something like /tmp/tmpzfp6I6.upload. If an upload is large enough, you can watch this file grow in size as Django streams the data onto disk.

These specifics – 2.5 megabytes; /tmp; etc. – are simply 「reasonable defaults」 which can be customized as described in the next section.

多級評論  

用戶能夠直接對貼子進行評論,其它用戶也能夠對別的用戶的評論再進行評論,也就是所謂的壘樓,以下圖:

 

全部的評論都存在一張表中, 評論與評論以前又有從屬關係,如何在前端 頁面上把這種層級關係體現出來?

先把評論簡化成一個這樣的模型:

數據庫裏評論以前的關係大概以下
data = [
    ('a',None),
    ('b', 'a'),
    ('c', None),
    ('d', 'a'),
    ('e', 'a'),
    ('g', 'b'),
    ('h', 'g'),
    ('j', None),
    ('f', 'j'),
]
 
 
'''
完整的層級關係以下:
a -> b -> g ->h
a -> d
a -> e
 
'''
 
#轉成字典後的關係以下
{
    'a':{
        'b':{
            'g':{
                'h':{}
            }
        },
        'd':{},
        'e':{}
    },
    'j':{
        'f':{}
    }
 }

接下來其實直接用遞歸的方法去迭代一遍字典就行啦。  

注意, 你不能直接把字典格式返回給前端的template, 前端的template在對這個字典進行的遍歷的時候必須採用遞歸的方法,可是template裏沒有遞歸的語法支持, 因此怎麼辦呢? 只能用自定義template tag啦, 具體如何 寫,咱們課上細講。

function  csrfSafeMethod(method) {
     // these HTTP methods do not require CSRF protection
     return  (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
     beforeSend:  function (xhr, settings) {
         if  (!csrfSafeMethod(settings.type) && ! this .crossDomain) {
             xhr.setRequestHeader( "X-CSRFToken" , csrftoken);
         }
     }
});
相關文章
相關標籤/搜索