Python之路,Day17 - 分分鍾做個BBS論壇


本節內容:

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

需求:

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

知識必備:

  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

 

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

CSRF 背景與介紹

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

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 則可以拿到錢后逍遙法外。

CSRF 攻擊的對象

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

 

防御策略:在請求地址中添加 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。

Django 中使用CSRF

How to use it

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

  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啦, 具體如何 寫,我們課上細講。   

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM