2017年11月22日 星期三

Django - 當Django的DEBUG設為False,無法讀取staticfiles的問題

當Django的settings.py中DEBUG由True改為False,為開發環境轉換為生產環境必改的設定。
DEBUG改為False後,讀取靜態檔案發生錯誤,原來DEBUG設置DEBUG為False時,’django.contrib.staticfiles’會關閉,即Django不會自動搜尋靜態檔案。
靜態文件不能讀取導致2個問題:
  1. CSS、JS檔案無法讀取
  2. 通過url不能訪問靜態文件,如圖片、檔案
網路搜尋的處理方式眾多,但隨著Django版本不同,過去的紀錄已不適用。
以下為Django1.11版本參考網路上的紀錄修改後的版本

版本:

System version : Windows 10,Ubuntu16.04   
Python version : Python 3.6.0 :: Anaconda 4.3.1 (64-bit)  
Django version : 1.11.2

檔案結構:

◢ project_name
    ◢ app_name
        ◢ templates
            ◢ app_name
                page1.html
                404.html
        urls.py
        views.py
    ◢ project_name
        settings.py
        urls.py
        views.py
    ◢ static
        ◢ css 
        ◢ js 
        ◢ image 
            favicon.png
    manage.py
project_name/project_name/settings.py
# DEBUG = True
DEBUG = False
STATIC_URL = '/static/'

if DEBUG is False: 
    STATIC_ROOT = (
        os.path.join(BASE_DIR, 'static')
    )

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
project_name/project_name/urls.py
加入以下程式碼
from django.views.static import serve
from . import settings
if settings.DEBUG is False:
    urlpatterns.append(url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}))
​

Django - 自定義404或500的網頁 - custom 404/500 error page setting

版本:

System version : Windows 10,Ubuntu16.04   
Python version : Python 3.6.0 :: Anaconda 4.3.1 (64-bit)  
Django version : 1.11.2

檔案結構:

◢ project_name
    ◢ app_name
        ◢ templates
            ◢ app_name
                page1.html
                404.html
        urls.py
        views.py
    ◢ project_name
        settings.py
        urls.py
        views.py
    ◢ static
        ◢ css 
        ◢ js 
        ◢ image 
            favicon.png
    manage.py
project_name/project_name/urls.py
加入以下程式碼
handler404 = views.error_404
handler500 = views.error_404
project_name/project_name/views.py
加入以下程式碼
from django.shortcuts import render
def error_404(request):
    return render(request, 'app_name/404.html')
project_name/project_name/settings.py
將DEBUG的值改為False
# DEBUG = True
DEBUG = False
​

Django - Django網站圖示的變更(favicon.ico,shortcut icon)

版本:

System version : Windows 10,Ubuntu16.04   
Python version : Python 3.6.0 :: Anaconda 4.3.1 (64-bit)  
Django version : 1.11.2

檔案結構:

◢ project_name
    ◢ app_name
        ◢ templates
            ◢ app_name
                page1.html
                404.html
        urls.py
        views.py
    ◢ project_name
        settings.py
        urls.py
        views.py
    ◢ static
        ◢ css 
        ◢ js 
        ◢ image 
            favicon.png
    manage.py
project_name/app_name/templates/app_name/page1.html
在html檔的第一行加上
{% load staticfiles %}
在head標籤內加入
<head>
    <title>...</title>
    <link href="{% static 'image/favicon.png' %}" rel="shortcut icon"></link>    
</head>
如果有做繼承關係的網頁,建議將以上程式碼放到父頁面
​

2017年11月20日 星期一

Python - Convert xml data to dict to in python - 將xml格式轉換為字典

版本

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Codes:

import xmltodict, json
xml_str = '<root><rule>a</rule><right>1</right></root>'
order_dict_tmp = xmltodict.parse(xml_str)
dict_temp = json.loads(json.dumps(order_dict_tmp))
print( xml_str )
print('-'*35)
print( order_dict_tmp )
print( type(order_dict_tmp) )
print('-'*35)
print( dict_temp )
print( type(dict_temp) )

執行結果:

​

2017年11月8日 星期三

Python - Convert a dict to XML in python - 將字典轉換為XML的格式

版本

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Codes:

# dict to xml
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import tostring
def dict_to_xml(tag, d):
    ele = Element(tag)
    for key, val in d.items():
        child = Element('key',{'name':key})
        child.text = str(val)
        ele.append(child)
    return ele

dic1 = {'a':5,'123b':22,'c':'str1'}
print(dic1)
print('-'*85)
xml_str = tostring(dict_to_xml('score', dic1)  )
xml_str2 = xml_str.decode()
print(xml_str2)
print('='*85)
xml_str = tostring(dict_to_xml('score', dic1), encoding='utf8', method='xml')
xml_str2 = xml_str.decode()
print(xml_str2)

執行結果:

​

2017年9月7日 星期四

Python - Building a list using for loop and other work about list - list用迴圈產生、list串接(相加)、使用迴圈切割list

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)

System version :Windows 10
list1 = ['a'+str(x) for x in range(7)]
print(list1)
print('='*40)

list2=[]
for a in range(2):
    list2=list2+list1
print(list2)
print('='*40)

num = 3
for a in range(0,len(list2),num):
    print(list2[a:a+num])
執行結果:
['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6']
========================================
['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6']
========================================
['a0', 'a1', 'a2']
['a3', 'a4', 'a5']
['a6', 'a0', 'a1']
['a2', 'a3', 'a4']
['a5', 'a6']
​

2017年9月5日 星期二

Python - Convert String to list and Convert list to dictionary in Python - 字串藉由指定符號轉為list與list轉為字典

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
str1 = '背景,0,特性,1,元件,3'
list1 = str1.split(",")
dic1 = {list1[i]: list1[i+1] for i in range(0, len(list1), 2)}
print(list1)
print(dic1)
執行結果:
['背景', '0', '特性', '1', '元件', '3']
{'背景': '0', '特性': '1', '元件': '3'}
​

2017年8月30日 星期三

Python - Pretty printing nested dictionaries - 印出巢狀結構的字典

Version:

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Code:

from pprint 
import pprint 
dic1 ={'name':'Dondonaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'number':9527,'item':['a','b','a','b','a','b','a','b','a','b','a','b','a','b','a','b']} 
print(dic1) 
print('='*30) 
pprint(dic1)

Result:


​

2017年8月2日 星期三

Python - how to widen output display to see more columns and rows in pandas dataframe? - 更改pandas dataframe顯示的行數列數

Version

Python Version:Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System Version:Windows 10

Code:

import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
​

2017年7月27日 星期四

Python - Convert String to datetime object and Convert datetime to String and timedalta - 字串轉日期、日期轉字串、日的加減

Version

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Code:

from datetime import datetime,timedelta
string_date = '20170727'
# Convert String to datetime object - 字串轉日期
datetime_date = datetime.strptime(string_date, "%Y%m%d").date()

# 日期的加減法
date_sub_1 = datetime_date - timedelta(1)

# Convert datetime to String - 日期轉字串 
date_sub_1_string = date_sub_1.strftime("%Y-%m-%d")

print('datetime_date :',datetime_date,'\t,type :',type(datetime_date))
print('date_sub_1 :',date_sub_1,'\t,type :',type(date_sub_1))
print('date_sub_1_string :',date_sub_1_string,'\t,type :',type(date_sub_1_string))

Result:

datetime_date : 2017-07-27     ,type : <class 'datetime.date'>
date_sub_1 : 2017-07-26     ,type : <class 'datetime.date'>
date_sub_1_string : 2017-07-26     ,type : <class 'str'>
​

Python - Convert list to dictionary with indexes - 將list轉為字典且將index設為字典的key

Version

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10

Code:

list1 = ['A','B','C']
dic1 = {k:v for k,v in enumerate(list1)}
dic1

Result:

{0: 'A', 1: 'B', 2: 'C'}
​

Python Regular Expression example - re.search & re.match - Python正規表示式使用

版本:

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
Pandas version :0.19.2
System version :Windows 10

Codes:

import re
s1 = 'abc123def'
print(re.search('abc',s1))
print(re.match('abc',s1))
print(re.search('123',s1))
print(re.match('123',s1))
print(re.search('abc',s1).group())
print(re.match('abc',s1).group())

執行結果:

<_sre.SRE_Match object; span=(0, 3), match='abc'>    
<_sre.SRE_Match object; span=(0, 3), match='abc'>    
<_sre.SRE_Match object; span=(3, 6), match='123'>    
None    
abc     
abc
​

2017年7月26日 星期三

Python - Looking up the list of sheets in an excel file - 找出指定excel檔的sheet name

Version

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
Pandas version :0.19.2
System version :Windows 10

Codes

import pandas as pd
file_path=r'E:\download\tmp\test.xlsx'
sheet_name_list = pd.ExcelFile(file_path).sheet_names
sheet_name_list

執行結果:

['sheet1', 'sheet2', 'sheet3']
​