吹静静

欢迎QQ交流:592590682

随机验证码

import random       # 随机函数,没有参数

li = []
for i in range(6):
    r = random.randrange(0, 5)
    if r == 2 or r == 4:
        num = random.randrange(0, 10)
        li.append(str(num))                # 因为jion 只能添加字符串,所以要str()
    else:
        temp = random.randrange(65, 91)    # 随机产生一个65-90的数字
        c = chr(temp)                      # 数字转化成字母
        li.append(c)

result = ''.join(li)        # 使产生的随机数连起来,中间没有间隔
print(result)               # jion() 只能添加字符串

注意:

  1、随机函数 random 后面不跟参数;

  2、join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串;

json

1、json.dumps:将 Python 对象编码成 JSON 字符串

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = json.dumps(data)
print json

输出结果:[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}

2、json.loads :用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

s = "[11, 22, 33, 44]"   # 类似列表的字符串
print(type(s), s)


import json
n = json.loads(s)        # loads 将一个字符串,转化成python的基本数据类型:列表、字典可以,元组不行
print(type(n), n)        # 输出:<class 'list'> [11, 22, 33, 44]


s1 = '{"k1":"v1"}'       # 要把字符串转化成字典,字典里面必须是双引号
n1 = json.loads(s1)
print(type(n1), n1)      # 输出:<class 'dict'> {'k1': 'v1'}

 

# Auther Cjj

# {"backend": "test.oldboy.org", "record": {"server": "100.1.7.9", "weight": 20, "maxconn": 30}}
import json
r = input("input:")
dic = json.loads(r)
bk = dic['backend']
rd = "server %s %s weight %d maxconn %d" %(dic['record']['server'],
                                           dic['record']['server'],
                                           dic['record']['weight'],
                                           dic['record']['maxconn'])

print(rd)

'''
import json

jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
text = json.loads(jsonData)
print(text)
'''
练习

 

 

1、loads 将一个字符串,转化成python的基本数据类型:列表、字典可以,元组不行;

2、要把字符串转化成字典,字典里面必须是双引号。

查看 fetch & 添加 add

# Auther Cjj

# line.strip()    移除字符串首尾指定字符,默认为空格


def fetch(backend):      # 用来获取的
    # backend = "www.oldboy.org"
    result = []
    with open('ha.conf', 'r', encoding='utf-8') as f:
        flag = False
        for line in f:
            if line.strip().startswith("backend ") and line.strip() == "backend " + backend:    # 判断,遇到backend 并且后面跟的是 www.oldboy.org 开始执行读取操作
                flag = True
                continue
            if flag and line.strip().startswith("backend "):  # 判断,flag = True并且遇到backend,返回flag = False 结束读取
                flag = False
                break
            if flag and line.strip():  # 如果 flag = True,开始读
                result.append(line.strip())
    return result


ret = fetch("www.oldboy.org")
print(ret)


def add(backend, record):        # 用来添加的
    # 先检查记录存不存在
    record_list = fetch(backend)
    if not record_list:
        # backend 不存在
        with open('ha.conf', 'r') as old, open("new_conf", 'w') as new:
            for line in old:
                new.write(line)
            new.write("\nbackend" + backend + "\n")
            new.write(" " * 8 + record + "\n")

    else:
        # backend 存在
        if record in record_list:
            # record 已经存在
            # import shutil
            # shutil.copy("ha.conf", 'new.conf')
            pass
        else:
            # backend存在,record不存在
            record_list.append(record)
            with open('ha.conf', 'r') as old, open('new.conf', 'w') as new:
                for line in old:
                    if line.strip().startswith("backend ") and line.strip() == "backend " + backend:
                        flag = True
                        new.write(line)
                        for new_line in record_list:
                            new.write(" " * 8 + new_line + "\n")
                    if  flag and line.strip().startswith("backend"):
                        flag = False
                        new.write(line)
                        continue
                    if line.strip() and not flag:
                        new.write(line)

bk = "test.oldboy.org"
rd = "server 100.1.7.29 100.1.7.49 weight 20 maxconn 30"
add(bk, rd)

配置文件:

 1 global
 2         log 127.0.0.1 local2
 3         daemon
 4         maxconn 256
 5         log 127.0.0.1 local2 info
 6 defaults
 7         log global
 8         mode http
 9         timeout connect 5000ms
10         timeout client 50000ms
11         timeout server 50000ms
12         option  dontlognull
13 
14 listen stats :8888
15         stats enable
16         stats uri       /admin
17         stats auth      admin:1234
18 
19 frontend oldboy.org
20         bind 0.0.0.0:80
21         option httplog
22         option httpclose
23         option  forwardfor
24         log global
25         acl www hdr_reg(host) -i www.oldboy.org
26         use_backend www.oldboy.org if www
27 
28 backend www.oldboy.org
29         server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
30         server 100.1.7.19 100.1.7.19 weight 20 maxconn 3000
31 
32 backend buy.oldboy.org
33         server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
配置文件

装饰器

由函数 b1 调用函数 s2 实现功能

def outer(func):     # func 带纸的老的f1函数
    def inner(*args, **kwargs):
        print('before')
        r = func(*args, **kwargs)  # 执行老的f1
        print('after')
        return r
    return inner

# 功能:
#    1、自动执行outer函数并且将其下面的函数名f1当作参数传递给outer
#    2、将outer函数的返回值,重复赋值给 f1
@outer              # 装饰器
def f1(arg):        # inner 函数大代替了原来的f1函数
    print(arg)
    return "静静"


@outer
def f2(arg1, arg2):   # 如果这里有两个或者两个以上参数,inner需要加一个万能参数
    print(arg1, arg2)
s2.py

 

# Auther Cjj

import s2


ret = s2.f1('fafafa')


print("返回值", ret)


s2.f2(11, 22)
b1.py

装饰器例子:

# Auther Cjj


LOGIN_USER = {"is_login": False}


def outer(func):
    def inner(*args, **kwargs):
        if LOGIN_USER['is_login']:
            r = func()
            return r
        else:
            print('请登录')
    return inner

@outer
def manager():
    print("欢迎%s登陆" % LOGIN_USER['current_user'])


def login(username, password):
    if username == 'cjj' and password == 123:
        LOGIN_USER['is_login'] = True
        LOGIN_USER['current_user'] = username
        manager()

def main():
    while True:
        int = input('1,后台管理;2,登陆')
        if int == '1':
            manager()
        elif int == '2':
            username = input('请输入用户名:')
            password = input('请输入密码:')
            login(username, password)
main()

 

 

 

        

posted on 2017-12-20 20:09  吹静静  阅读(183)  评论(0编辑  收藏  举报