python简易博客(四)–model+config

  • by

正文:

编写模板(就是sql脚本,其中没有技巧):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Models for user, blog, comment.
'''
__author__ = 'Michael Liao'
import time, uuid
from orm import Model, StringField, BooleanField, FloatField, TextField
def next_id():
    return '%015d%s000' % (int(time.time() * 1000), uuid.uuid4().hex)
class User(Model):
    __table__ = 'users'
    id = StringField(primary_key=True, default=next_id, ddl='varchar(50)')
    email = StringField(ddl='varchar(50)')
    passwd = StringField(ddl='varchar(50)')
    admin = BooleanField()
    name = StringField(ddl='varchar(50)')
    image = StringField(ddl='varchar(500)')
    created_at = FloatField(default=time.time)
class Blog(Model):
    __table__ = 'blogs'
    id = StringField(primary_key=True, default=next_id, ddl='varchar(50)')
    user_id = StringField(ddl='varchar(50)')
    user_name = StringField(ddl='varchar(50)')
    user_image = StringField(ddl='varchar(500)')
    name = StringField(ddl='varchar(50)')
    summary = StringField(ddl='varchar(200)')
    content = TextField()
    created_at = FloatField(default=time.time)
class Comment(Model):
    __table__ = 'comments'
    id = StringField(primary_key=True, default=next_id, ddl='varchar(50)')
    blog_id = StringField(ddl='varchar(50)')
    user_id = StringField(ddl='varchar(50)')
    user_name = StringField(ddl='varchar(50)')
    user_image = StringField(ddl='varchar(500)')
    content = TextField()
    created_at = FloatField(default=time.time)

配置文件:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Configuration
'''
__author__ = 'Michael Liao'
import config_default
class Dict(dict):
    '''
    Simple dict but support access as x.y style.
    '''
    def __init__(self, names=(), values=(), **kw):
        super(Dict, self).__init__(**kw)
        for k, v in zip(names, values):#zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
            self[k] = v
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
    def __setattr__(self, key, value):
        self[key] = value
def merge(defaults, override):
    r = {}
    for k, v in defaults.items():
        if k in override:
            if isinstance(v, dict):  如果config默认文件存在。
                r[k] = merge(v, override[k])   #字典里取字典
            else:
                r[k] = override[k]
        else:
            r[k] = v
    return r
def toDict(d):
    D = Dict()
    for k, v in d.items():
        D[k] = toDict(v) if isinstance(v, dict) else v  #small=x if x<y else y python 如果x<y 把x的值赋给small,否则把y赋给small
    return D
configs = config_default.configs
try:
    import config_override
    configs = merge(configs, config_override.configs)  #config_override.py 用来覆盖某些默认设置
except ImportError:
    pass
configs = toDict(configs)

 
2018.5.16
 

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注