一、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源码
- 连接结束

 

posted on 2018-06-11 18:11  海燕。  阅读(1106)  评论(0编辑  收藏  举报