import os
import datetime
import peewee as pw
from werkzeug.security import generate_password_hash, check_password_hash
database = pw.SqliteDatabase('db.sqlite')
class Model(pw.Model):
class Meta:
database = database
class User(Model):
username = pw.CharField()
password_hash = pw.CharField()
@property
def password(self):
raise AttributeError('password is not readable')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __str__(self):
return '<User %r>' %self.username
class Category(Model):
tag = pw.CharField()
count = pw.IntegerField(default=0)
def __str__(self):
return '<Category %r>' %self.tag
class Post(Model):
title = pw.CharField()
body = pw.TextField()
summary = pw.CharField()
category = pw.ForeignKeyField(Category, backref='posts')
timestamp = pw.DateTimeField(default=datetime.datetime.now)
def __str__(self):
return '<Post %r>' %self.title
if __name__ == "__main__":
if not os.path.exists('db.sqlite'):
User.create_table()
Post.create_table()
Category.create_table()
categoryC = Category.create(tag='C')
categoryPy = Category.create(tag='Py')
Post.create(category=categoryC, title='learn c', body='learn c hardly', summary='').save()
Post.create(category=categoryPy, title='learn py', body='learn py hardly', summary='').save()
Post.create(category=categoryPy, title='learn flask', body='learn flask hardly', summary='').save()
for category in Category.select():
print(category)
for post in category.posts:
print(' ', post)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.