2017年1月5日 星期四

[Django]靜態文件設置

如果想要讓Django網站上的圖片顯示出來,最正規的方法
1.修改urls.py


from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$',homepage),
    url(r'^post/(\w+)$',showpost),
]+static(settings.STATIC_URL, document_root=settings.STATIC_URL)

#讓django可以偵測網址結尾為http://127.0.0.1/static/..........

2.修改settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static/images'),
]

STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

#STATIC_URL 讓 templates 裡的網址不會寫死
#STATICFILES_DIRS 執行collectstatic 時django會去這些資料夾收集檔案
#STATIC_ROOT 執行collectstatic django會把檔案集中到此目錄

3.模板渲染的修改
{% load staticfiles %}
<img src="{% static " swift.jpg="" />

4.執行python manage.py collectstatic

http://www.jianshu.com/p/a3fb31f49f2e
http://eric0806.blogspot.tw/2014/04/blogger-google-code-prettify.html
https://docs.djangoproject.com/en/1.10/howto/static-files/

2017年1月3日 星期二

[Python]1.9.3 綴星運算式 1.9.4 函數的有效範圍

若 lst = [1 , 2 , 3 , 4 ]
def add(a,b,c,d):
      return a+b+c+d
add(*lst) = add(lst[0],lst[1],lst[2],lst[3]) = add(1,2,3,4)=sum(lst)

Python 沒有多載(overload)

多載:允許相同名字的函數存在,只是他們的參數數量不同
比方說,我們今天要寫一個函式
在java 或是C++中,我們可以
def add(a,b):
    return a+b
def add(a,b,c):
    return a+b+c

add(1,2) >>>3
add(1,2,3) >>>6

透過add 參數的不同來分辨呼叫的函式

Python 裡面沒有這種方法,我們可以透過清單
def add(lst):
    return sum(lst)

還有另一種方法
def add(*tmp):
    return sum(tmp)

在這裡位於參數列的*tmp會將所有傳入的元素收集成元組

對於字典的呼叫我們可以使用**雙綴星號的方式
def power (base,exp):
    return base**exp

dic = {'base':2,'exp':3}
print power(**dic)

**dic 會將dic 拆解成 base = 2,exp = 3)

定義函式上也可以使用
def power(**dic):
    return dic['base'] ** dic['exp']

print power(base=2,exp=3)