6.11大雜燴。。


一、get_or_create 

get_or_create : 如果查詢到就返回,如果沒有查詢到就向數據庫加入新的對象。返回的是一個元祖。

二、python如何判斷web訪問來源是PC端還是手機端

def judge_pc_or_mobile(ua):
        """
        判斷訪問來源是pc端還是手機端
        :param ua: 訪問來源頭信息中的User-Agent字段內容
        :return:
        """
        factor = ua
        is_mobile = False
        _long_matches = r'googlebot-mobile|android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp' \
                        r'|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)' \
                        r'|vodafone|wap|windows ce; (iemobile|ppc)|xiino|maemo|fennec'
        _long_matches = re.compile(_long_matches, re.IGNORECASE)
        _short_matches = r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)' \
                         r'|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)' \
                         r'|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw' \
                         r'|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8' \
                         r'|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit' \
                         r'|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)' \
                         r'|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji' \
                         r'|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx' \
                         r'|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi' \
                         r'|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)' \
                         r'|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg' \
                         r'|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21' \
                         r'|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-' \
                         r'|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it' \
                         r'|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)' \
                         r'|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)' \
                         r'|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit' \
                         r'|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-'

        _short_matches = re.compile(_short_matches, re.IGNORECASE)

        if _long_matches.search(factor) != None:
            is_mobile = True
        user_agent = factor[0:4]
        if _short_matches.search(user_agent) != None:
            is_mobile = True

        return is_mobile

    #調用
    template_name = 'frontend_desktop/index.html'
    if judge_pc_or_mobile(request.META['HTTP_USER_AGENT']):
        template_name = 'frontend_mobile/index.html'

三、小細節

1、 一般render返回頁面的時候盡量返回對象,然后用對象去點。如果想要獲取的數據沒有,可以循環當前那個對象,
給這個對象設置一個屬性。比如:

# 最熱游戲
hot_games = Game.objects.all().order_by('-pv')[:4]
for i in hot_games:
  score = GameLog.objects.filter(game__name=i.name).aggregate(score=Max('score'))
  if score['score'] == None:
  score['score'] = 0

  i.__setattr__('maxscore', score['score'])
return render(request, template_name, context={'hot_games': hot_games})

2、一般要篩選數據結果的時候,比如要最新的前幾條數據,可以先查后篩,然后返回前端,不要吧結果都返回了在前端篩。比如:

course_obj2 = Category.objects.filter(type='course', is_show_banner=True).order_by("-create_time")
course_banner_list = []
for i in course_obj2:
  if i.parent and i.children.all(): # 如果有父親說明是課程或者節
    course_banner_list.append(i)
  if len(course_banner_list) == 6:
    break

 3、注意在render頁面的時候如果要求是登陸用戶看,加上@login_required(login_url='/d_login_page/')裝飾器。導入:from django.contrib.auth.decorators import login_required

如果是借口注意加上@csrf_exempt裝飾器,導入:from django.views.decorators.csrf import csrf_exempt

四、model操作

#方式一 :在模型類上添加一個classmethod:
    class Book(models.Model):
        title = models.CharField(max_length=20)

        @classmethod
        def create(cls, title):
            book = cls(title=title)
            return book

    book = Book.create('追風箏的人')

    # 方式二:在自定義管理器中添/一個方法(通常是首選):
    class BookManager(models.Manager):
        def create_book(self, title):
            book = self.create(title=title)
            return book

    class Book(models.Model):
        title = models.CharField(max_length=20)
        objects = BookManager()
        
    book = Book.objects.create_book('追風箏的人')

 

五、驗證對象

驗證模型涉及三大步驟:
1、驗證模型字段:Model.clean_fields()
2、驗證整個模型:Model.clead()
3、驗證字段唯一性:Model.validate_unique()
當您調用模型的full_clean()方法時,所有三個步驟都會執行 。
Model.full_clean(exclude = None,validate_unique = True)[source] 
此方法按此順序調用Model.clean_fields(),Model.clean()(和 Model.validate_unique()如果validate_unique是True),並引發一個包含來自所有三個階段的錯誤ValidationError的 message_dict屬性。

六、保存對象save()方法

要將對象保存到數據庫,請調用save()
如果你想要自定義保存行為,則可以重寫save()方法。覆蓋內置方法的經典用例是,如果你希望在保存對象時發生某些事情,例如:
from django.db import models
class Blog(models.Model):
    name = models.CharField(max_length100)
    tagline = models.TextField()

    def save(self,*args,**kwargs):
        do_something()
        super().save(*args ,**kwargs)
        do_something_else()


也可以防止保存:
from django.db import models
class Blog(models.Model):
    name = models.CharField(max_length100)
    tagline = models.TextField()

    def save(self,*args,**kwargs):
        if self.name == 'haiyan':
            return
        else:
            super().save(*args,**kwargs)
記住調用基類方法,這就是該業務-以確保該對象仍然保存到數據庫中非常重要。如果你忘記調用該父類方法,則默認行為
將不會發生,並且數據庫不會被觸及.super.save(*args,**kwargs)

七、model其他模型實例方法

1、__str__(self)
   __str__(self)每次調用str()對象都會調用該方法,吧對象轉換成字符串顯示,e.g:
           from django.db import models
           class Person(models.Model):
               first_name = models.CharField(max_length=50)
            last_name = models.CharField(max_length=50)

            def __str__(self):
                return '%s %s' % (self.first_name, self.last_name)    
2、__eq__(self)
  等式方法被定義為使用具有相同主鍵值和相同具體類的實例被認為是相同的,除了具有主鍵值的實例None不等於除自身以外的任何實例
  。對於代理模型,具體類被定義為模型的第一個非代理父代;對於所有其他模型,他只是模型的類。
3、get_absolute_url()
    - 定義一個get_absolute_url()方法來告訴Django如何計算一個對象的規范url。對於調用者來說,這個方法似乎應該返回一個
        可以用來通過http引用對象的字符串。比如:
        def get_absolute_url(self):
            return reverse('frontend:courseware_details', args=[self.id])
        Django使用一個地方get_absolute_url()是在管理應用程序中。如果一個對象定義了這個方法,那么對象編輯頁面將會有一個
        ‘View on site’鏈接,它將直接跳轉到對象的公共視圖
    - get_absolute_url()在模版中使用也是一種很好的做法,而不是對對象的url進行硬編碼。例如,
        old_url :<a href="/people/{{ object.id }}/">{{ object.name }}</a>
        new_url :<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

3、get_field_display() :對於已choice設置的每個字段,對象都有一個get_field_display()方法,其中field是該字段的
  名稱。該方法返回該字段choice 指定對應的值。e.g:
      from django.db import models
      class Person(models.Model):
          SHIRT_SIZES = (
              ('S','Small'),
              ('M','Medium'),
              ('S','Large'),
          )
          name = models.CharField(max_length=20)
          shirt_sizes = models.CharField(max_length30)

    >>> p = Person(name="Fred Flintstone", shirt_size="L")
    >>> p.save()
    >>> p.shirt_size
    'L'
    >>> p.get_shirt_size_display()
    'Large'

 八、點擊發送郵件按鈕讓按鈕上的文字不換行

class 的兩個屬性:
      nowrap :規定制定的內容不換行
          e.g1: <td align="center" nowrap="nowrap">的整體意思是:定義表格的一行,對齊方式為居中,nowrap 屬性規定表格單元格中的內容不換行 。
          e.g2:  return format_html('<a href="%s" title="發送" class="nowrap confirm">發送</a>' % group_send)
      confirm :效果上相當於alert 

 

九、去掉ckeditor默認的<html><head></head><body></body></html>標簽,但是title標簽沒有去掉

'fullPage': False,#是否使用完整的html編輯模式 如使用,其源碼將包含:<html><head></head><body></body></html>等標簽

 

  1 CKEDITOR_CONFIGS = {
  2     'default': {
  3         'fullPage': False,#是否使用完整的html編輯模式 如使用,其源碼將包含:<html><head></head><body></body></html>等標簽
  4         'allowedContent': True, #關閉標簽過濾
  5         'language':'zh-cn',
  6         'skin': 'moono-lisa',
  7         'toolbar_Basic': [
  8             ['Source', '-', 'Bold', 'Italic']
  9         ]
 10     },
 11     'pagetemplate': {
 12         'fullPage': True,
 13         'allowedContent': True,
 14         'language': 'zh-cn',
 15         'skin': 'moono-lisa',
 16         'toolbar_Basic': [
 17             ['Source', '-', 'Bold', 'Italic']
 18         ],
 19         'toolbar_YourCustomToolbarConfig': [
 20             {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
 21             {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
 22             {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
 23             {'name': 'forms',
 24              'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 25                        'HiddenField']},
 26             '/',
 27             {'name': 'basicstyles',
 28              'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
 29             {'name': 'paragraph',
 30              'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
 31                        'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']},
 32             {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
 33             {'name': 'insert',
 34              'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
 35             {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
 36             {'name': 'colors', 'items': ['TextColor', 'BGColor']},
 37             {'name': 'tools', 'items': ['ShowBlocks']},
 38             '/',
 39             {'name': 'custom_staff_firstname', 'items': ['custom_staff_name', 'custom_staff_firstname', 'custom_staff_lastname', 'custom_staff_mobile', 'custom_staff_email', 'custom_staff_department', 'custom_staff_officialtitle']},
 40             {'name': 'custom_filetemplate_url_link', 'items': ['custom_filetemplate_url_link', 'custom_filetemplate_url']},
 41             {'name': 'custom_import', 'items': ['custom_import']},
 42             {'name': 'custom_indicator', 'items': ['custom_indicator']},
 43             {'name': 'custom_staticize', 'items': ['custom_staticize']},
 44             {'name': 'tools', 'items': ['Maximize']},
 45             {'name': 'custom_page_js_inject', 'items': ['custom_page_js_inject']},
 46         ],
 47         'toolbar': 'YourCustomToolbarConfig',
 48         'tabSpaces': 4,
 49         'extraPlugins': ','.join(
 50             [
 51                 'div',
 52                 'autolink',
 53                 'autoembed',
 54                 'embedsemantic',
 55                 'widget',
 56                 'lineutils',
 57                 'clipboard',
 58                 'dialog',
 59                 'dialogui',
 60                 'elementspath',
 61                 'custom_staff_firstname',
 62                 'custom_staff_lastname',
 63                 'custom_staff_name',
 64                 'custom_staff_mobile',
 65                 'custom_staff_email',
 66                 'custom_staff_department',
 67                 'custom_staff_officialtitle',
 68                 'custom_filetemplate_url_link',
 69                 'custom_filetemplate_url',
 70                 'custom_import',
 71                 'custom_indicator',
 72                 'custom_staticize',
 73                 'custom_page_js_inject',
 74             ]),
 75     },
 76     'mailtemplate': {
 77         'fullPage': True,
 78         'allowedContent': True,
 79         'language': 'zh-cn',
 80         'skin': 'moono-lisa',
 81         'toolbar_Basic': [
 82             ['Source', '-', 'Bold', 'Italic']
 83         ],
 84         'toolbar_YourCustomToolbarConfig': [
 85             {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
 86             {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
 87             {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
 88             {'name': 'forms',
 89              'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 90                        'HiddenField']},
 91             '/',
 92             {'name': 'basicstyles',
 93              'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
 94             {'name': 'paragraph',
 95              'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
 96                        'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']},
 97             {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
 98             {'name': 'insert',
 99              'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
100             {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
101             {'name': 'colors', 'items': ['TextColor', 'BGColor']},
102             {'name': 'tools', 'items': ['ShowBlocks']},
103             '/',
104             {'name': 'custom_staff_firstname', 'items': ['custom_staff_name', 'custom_staff_firstname', 'custom_staff_lastname', 'custom_staff_mobile', 'custom_staff_email', 'custom_staff_department', 'custom_staff_officialtitle']},
105             {'name': 'custom_pagetemplate_url_link', 'items': ['custom_pagetemplate_url_link', 'custom_pagetemplate_url']},
106             {'name': 'custom_filetemplate_url_link', 'items': ['custom_filetemplate_url_link', 'custom_filetemplate_url']},
107             {'name': 'custom_staticize', 'items': ['custom_staticize']},
108             {'name': 'tools', 'items': ['Maximize']},
109         ],
110         'toolbar': 'YourCustomToolbarConfig',
111         'tabSpaces': 4,
112         'extraPlugins': ','.join(
113             [
114                 'div',
115                 'autolink',
116                 'autoembed',
117                 'embedsemantic',
118                 'widget',
119                 'lineutils',
120                 'clipboard',
121                 'dialog',
122                 'dialogui',
123                 'elementspath',
124                 'custom_staff_firstname',
125                 'custom_staff_lastname',
126                 'custom_staff_name',
127                 'custom_staff_mobile',
128                 'custom_staff_email',
129                 'custom_staff_department',
130                 'custom_staff_officialtitle',
131                 'custom_pagetemplate_url_link',
132                 'custom_pagetemplate_url',
133                 'custom_filetemplate_url_link',
134                 'custom_filetemplate_url',
135                 'custom_staticize'
136             ]),
137     },
138     'smstemplate': {
139         'fullPage': False,
140         'allowedContent': True,
141         'forceEnterMode': True,
142         'enterMode': 2,
143         'language': 'zh-cn',
144         'skin': 'moono-lisa',
145         'toolbar_YourCustomToolbarConfig': [
146             {'name': 'document', 'items': ['Source', '-']},
147             {'name': 'custom_staff_firstname', 'items': ['custom_staff_name', 'custom_staff_firstname', 'custom_staff_lastname', 'custom_staff_mobile', 'custom_staff_email', 'custom_staff_department', 'custom_staff_officialtitle']},
148             {'name': 'custom_pagetemplate_url_link', 'items': ['custom_pagetemplate_url']},
149             {'name': 'custom_filetemplate_url_link', 'items': ['custom_filetemplate_url']},
150             {'name': 'tools', 'items': ['Maximize']},
151         ],
152         'toolbar': 'YourCustomToolbarConfig',
153         'tabSpaces': 4,
154         'extraPlugins': ','.join(
155             [
156                 'div',
157                 'autolink',
158                 'autoembed',
159                 'embedsemantic',
160                 'widget',
161                 'lineutils',
162                 'clipboard',
163                 'dialog',
164                 'dialogui',
165                 'elementspath',
166                 'custom_staff_firstname',
167                 'custom_staff_lastname',
168                 'custom_staff_name',
169                 'custom_staff_mobile',
170                 'custom_staff_email',
171                 'custom_staff_department',
172                 'custom_staff_officialtitle',
173                 'custom_pagetemplate_url',
174                 'custom_filetemplate_url',
175             ]),
176     },
177     'introduction': {
178         'fullPage': False,
179         'allowedContent': True,
180         'image_previewText': '',
181         'language': 'zh-cn',
182         'skin': 'moono-lisa',
183         'toolbar_Basic': [
184             ['Source', '-', 'Bold', 'Italic']
185         ],
186         'toolbar_YourCustomToolbarConfig': [
187             {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
188             {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
189             {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
190             {'name': 'forms',
191              'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
192                        'HiddenField']},
193             '/',
194             {'name': 'basicstyles',
195              'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
196             {'name': 'paragraph',
197              'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
198                        'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']},
199             {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
200             {'name': 'insert',
201              'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
202             {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
203             {'name': 'colors', 'items': ['TextColor', 'BGColor']},
204             {'name': 'tools', 'items': ['ShowBlocks']},
205             {'name': 'tools', 'items': ['Maximize']},
206         ],
207         'toolbar': 'YourCustomToolbarConfig',
208         'tabSpaces': 4,
209         'extraPlugins': ','.join(
210             [
211                 'div',
212                 'autolink',
213                 'autoembed',
214                 'embedsemantic',
215                 'widget',
216                 'lineutils',
217                 'clipboard',
218                 'dialog',
219                 'dialogui',
220                 'elementspath',
221             ]),
222     },
223 }
CKEDITOR_CONFIGS

 

十、計算視頻文件的大小

if obj.video:
    video_size = FileCheck(urllib.unquote(obj.video.path))
    video_size = '(視頻大小:'+video_size.get_filesize()+''
    return format_html('<a href="%s" target=_blank>打開</a><span>%s</span>'%(obj.video.url,video_size))

 

 1 # coding: utf-8
 2 from moviepy.editor import VideoFileClip
 3 import datetime,os
 4 
 5 
 6 class FileCheck():
 7     def __init__(self, filename):
 8         self.filename = filename
 9 
10     def time_convert(self, size):  # 單位換算
11         m, h = 60, 60 ** 2
12         if size < m:
13             return datetime.timedelta(hours=00, minutes=00, seconds=int(size))
14         if size < h:
15             return datetime.timedelta(hours=00, minutes=int(size / m), seconds=int(size % m))
16         else:
17             return datetime.timedelta(hours=int(size / h), minutes=int(size % h / m), seconds=int(size % h % m))
18 
19     def get_file_times(self):
20         u"""
21         獲取視頻時長(s:秒)
22         """
23         clip = VideoFileClip(self.filename)
24         file_time = self.time_convert(clip.duration)
25         return file_time
26 
27     def get_filesize(self):
28         u"""
29         獲取文件大小(M: 兆)
30         """
31         file_byte = os.path.getsize(self.filename)
32         return self.size_convert(file_byte)
33 
34     def size_convert(self, size):  # 單位換算
35         K, M, G = 1024, 1024 ** 2, 1024 ** 3
36         if size >= G:
37             return str(size / G) + 'GB'
38         elif size >= M:
39             return str(size / M) + 'MB'
40         elif size >= K:
41             return str(size / K) + 'KB'
42         else:
43             return str(size) + 'B'
計算視頻時長,視頻大小等

 

十一、shutil模塊函數copyfile和copy

  • shutil.copyfile( src, dst) 從源src復制到dst中去。當然前提是目標地址是具備可寫權限。拋出的異常信息為IOException. 如果當前的dst已存在的話就會被覆蓋掉
  • shutil.move(src, dst) 移動文件或重命名
  • shutil.copymode( src, dst) 只是會復制其權限其他的東西是不會被復制的
  • shutil.copystat( src, dst) 復制權限、最后訪問時間、最后修改時間
  • shutil.copy( src, dst) 復制一個文件到一個文件或一個目錄
  • shutil.copy2( src, dst) 在copy上的基礎上再復制文件最后訪問時間與修改時間也復制過來了,類似於cp –p的東西
  • shutil.copy2( src, dst) 如果兩個位置的文件系統是一樣的話相當於是rename操作,只是改名;如果是不在相同的文件系統的話就是做move操作
  • shutil.copytree( olddir, newdir, True/Flase)
  • 把olddir拷貝一份newdir,如果第3個參數是True,則復制目錄時將保持文件夾下的符號連接,如果第3個參數是False,則將在復制的目錄下生成物理副本來替代符號連接
  • shutil.rmtree( src ) 遞歸刪除一個目錄以及目錄內的所有內容

python 日期和時間
python 提供了一個time和calendar模塊可以用於格式化日期和時間
一:time模塊
python 中時間日期格式化符號:

%y 兩位數的年份表示(00-99%Y 四位數的年份表示(000-9999%m 月份(01-12%d 月內中的一天(0-31%H 24小時制小時數(0-23%I 12小時制小時數(01-12%M 分鍾數(00=59%S 秒(00-59%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天為星期的開始
%w 星期(0-6),星期天為星期的開始
%W 一年中的星期數(00-53)星期一為星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身

 


二:calendar模塊
calendar模塊有很廣泛的方法用來處理年歷和月歷,例如打印某月的月歷

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import calendar

cal = calendar.month(2016, 1)
print "以下輸出2016年1月份的日歷:"
print cal
#########輸出#######
以下輸出2016年1月份的日歷:
January 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

 


三、正則表達式

>>>import re
>>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小寫
>>> m = pattern.match('Hello World Wide Web')
>>> print m # 匹配成功,返回一個 Match 對象
<_sre.SRE_Match object at 0x10bea83e8>
>>> m.group(0) # 返回匹配成功的整個子串
'Hello World'
>>> m.span(0) # 返回匹配成功的整個子串的索引
(0, 11)
>>> m.group(1) # 返回第一個分組匹配成功的子串
'Hello'
>>> m.span(1) # 返回第一個分組匹配成功的子串的索引
(0, 5)
>>> m.group(2) # 返回第二個分組匹配成功的子串
'World'
>>> m.span(2) # 返回第二個分組匹配成功的子串
(6, 11)
>>> m.groups() # 等價於 (m.group(1), m.group(2), ...)

四、python CGI 編程
1、什么是CGI?

CGI目前由NCSA維護,NCSA定義如下:
CGI(Common Gateway Interface)是通用網關接口,它是一段程序,運行在服務器上,如:HTTP服務器,提供同客戶端HTML頁面的接口。

 

2、網頁瀏覽

從網頁上點擊一個鏈接或者URL的流程:
- 在發送http請求前,需要域名解析(DNS解析):先從本地的host里面,看有沒有域名對應的IP地址,如果自己沒有去上一級找
- 瀏覽器向服務器發送TCP連接,與瀏覽器建立tcp三次握手
- 握手成功后,瀏覽器向服務器發送HTTP請求,請求數據包。
- 服務器處理收到的請求,將數據返回到瀏覽器,
- 瀏覽器收到http響應,讀取頁面內容,瀏覽器渲染,解析html源碼
- 連接結束

 


免責聲明!

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



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