代码改变世界

哗啦啦Python之路 - Day 5 - 双重装饰器,字符串格式化的两种方式,迭代,模块,序列化相关,时间戳,logging

2016-06-08 16:43  人畜无害哗啦啦  阅读(240)  评论(0编辑  收藏  举报

1. 双重装饰器

 小例子,双重装饰器来分别判断登录和管理员

##自己设的一些值
user_info = {}
user_info['is_login'] = True
user_info['user_type'] = 2

def check_login(func): #用来判断有没有login
    def inner():
        if user_info.get('is_login',None): # 注意这个用法,字典.get是用来取值
            ret = func()
            return ret
        else:
            print('请登录')
    return inner

def check_admin(func): #用来判断是不是管理员
    def inner():
        if user_info.get('user_type',None) == 2:
            ret = func()
            return ret
        else:
            print('无权查看')
    return inner

@check_login
@check_admin
def index()
    print("随便什么")

index()

#output是随便什么

 

2. 字符串格式化的两种方式

 # http://www.cnblogs.com/wupeiqi/articles/5484747.html  这个博客值得一看

1) 百分号方式


形式是%[(name)][flags][width].[precision]typecode
非常有意思的左对齐右对齐和索引
s = "%(name)+10s and %(age)-10d %(p).2f"%{'name' : 'alex', 'age' : 123,"p":1.22222} #括号取名字
print(s)

#output:       alex and 123        1.22

 

  百分号的插入方式

s = "%%, %s"%"alex"
print(s)

#output: %, alex

 

2) format方式

 索引

s1 = "a {0}{0}{1}b".format(123,333) # 索引
print(s1)

#output
# a 123123333b

 

 索引2

s2 = "{name:s}{age:d}".format(name="alex",age = 111)
print(s2)

#output: alex111

 

   填充,居中

s3 = "{:a^20}".format("alex")
print(s3)

#output: aaaaaaaaalexaaaaaaaa

 

 数字加上加减号

s4 = "{:+d}".format(5)
print(s4)

#output: +5

  

  按序取数

s5 = "{: 20}{}{}".format(*[1,2,3])
print(s5)

#output:

#                   123

 

字典取值

s6 = "{name:*>20} {age}{aaa}".format(**{"name":"alex","age":123,"aaa":"none"})
print(s6)

#output:
#****************alex 123none

 

列表取值

s7 = "{0[1]}".format([1,2,3])
print(s7)

#output:
#2

 

 

3. 迭代

 

- 小知识点,怎么筛选数据

li = [11,22,33,44]
ret = filter(lambda x:x>22,li)
print(list(ret))

#output:
#[33, 44]

 

- 生成器,迭代


def func(): #生成器
    yield 1
    yield 2
    yield 3
ret = func()
# for i in ret:
#     print(i)
r1 = ret.__next__()
print(r1)

 

- 取值迭代

def myrange(argv):
    start = 0
    while True:
        if start >argv:
            return
        yield start
        start += 1

ret = myrange(1)
# print(list(ret))
m = ret.__next__()
print(m)
n = ret.__next__()
print(n)

#output: 
#0 
#1

 

- 自循环

#一个自循环
def func(n):
    if n > 4:

        return "end"
    print(n)
    n+= 1
    return func(n)

r = func(1)
print(r)

#output:
1
2
3
4
end

 

 

 4. 模块

 

模块分三种: 内置模块,自定义模块,第三方模块

模块存放在sys.path.

模块是为了将代码归类

导入某个目录下的模块

 

 

import sys
sys.path.append('E:\\')

 

 

一定不要重名

 

from sys import * # 把这个模块里所有的东西都导进来,但是不建议
单模块:
    import
嵌套在文件夹下:
    from *** import ****
    from *** import **** as *

 

python3装requests这个模块

import sys
import os
import random

# requests
# pip3 pip3 install requests
# 源码安装 cd 目录 # python3 setup.py install


 

5. 序列化相关

import json
import pickle

 

- json

import json
dic = '{"k1":"v1"}'
m = json.loads(dic)
print(m)

#转换成字典格式

 

- 从别处查询天气

import requests
import json
response = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')
response.encoding = 'utf-8'

dic = json.loads(response.text)
print(type(dic))

#output:
#class 'dict'

print(dic)

#output:
#{'status': 1000, 'desc': 'OK', 'data': {'yesterday': {'fl': '3-4级', 'date': '9日星期四', 'type': '阴', 'fx': '南风', 'low': '低温 22℃', 'high': '高温 32℃'}, 'ganmao': '各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。'

 

json的缺点是只能处理基本的数据类型,它适合跨语言,字符串

 

- 读,写

import json #json缺点是只能处理基本的数据类型,适合跨语言,字符串

li = '["alex","eric"]'

json.dump(li,open('db','w')) #写文件
li = json.load(open('db','r'))
print(type(li),li)


#output: <class 'str'> ["alex","eric"]

 

 

- pickle

 

import pickle #只能python用,对复杂类型进行操作
li = [11,22,33]
r = pickle.dumps(li)
r2 = pickle.loads(r)
print(r2,type(r2))
pickle.dump(li,open('db','wb'))


#output: [11, 22, 33] <class 'list'>

 

 

6. 时间戳

 

- time用法

import time #一般用来取时间戳
print(time.time()) # 从1970年1月1日开始到现在的秒数,时间戳
print(time.ctime()) #显示当前时间字符串形式,精确到秒
print(time.ctime(time.time()-86400))
time_obj = time.gmtime() #出来的时间是UTC时间
print("{year} - {month}".format(year = time_obj.tm_year, month = time_obj.tm_mon))
print(time.localtime()) #本地时间,也是分structure的
print(time.mktime(time.localtime()))#将时间转换成时间戳
time.sleep(4)#延时
print("-----")
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
tm = time.strptime('2016-05-06',"%Y-%m-%d")
print(tm)

 

 - datetime用法

import datetime #好处是直接时间格式
print(datetime.date.today())#输出当前日期
print(datetime.date.fromtimestamp(time.time())) #将时间戳转换成日期
current_time = datetime.datetime.now()
print(current_time)
new_date = datetime.datetime.now() + datetime.timedelta(days = 10) #hours seconds minutes
print(new_date)
m = current_time.replace(2014,9,12)
print(m)

 

7. logging函数使用方法

 

logging有五层

debug
info
warning
error
critical


import logging
logging.warning("user[alex]attempted wrong pwd more than 3 times")
logging.critical("server is down")

logging.basicConfig(filename ="alex.log",level = logging.INFO,
                    format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug("debug")
logging.warning("user[alex]attempted wrong pwd more than 3 times")
logging.critical("server is down")


#output:
#06/05/2016 07:00:11 PM user[alex]attempted wrong pwd more than 3 times
#06/05/2016 07:00:11 PM server is down


 

 

python使用datetime模块timedelta实现日期时间相加:

python计算明天的日期:

from datetime import datetime
from datetime import timedelta

now = datetime.now()
aDay = timedelta(days=1)
now = now + aDay
print now.strftime('%Y-%m-%d')

python计算昨天时间:

from datetime import datetime
from datetime import timedelta

now = datetime.now()
aDay = timedelta(days=-1)
now = now + aDay
print now.strftime('%Y-%m-%d')

使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法

计算上个月的月份

import time
last_month = time.localtime()[1]-1 or 12
print last_month

timedelta实现日期相减

from datetime import timedelta
from datetime import datetime
import time

d1 = datetime.now()
time.sleep(10)
eclipseTimes = datetime.now() - d1
print eclipseTimes.total_seconds()