def route_login(request): headers = { 'Content-Type': 'text/html', # 'Set-Cookie': 'height=169; gua=1; pwd=2; Path=/', } # log('login, headers', request.headers) log('login, cookies', request.cookies) username = current_user(request) if request.method == 'POST': form = request.form() u = User.new(form) if u.validate_login(): # 设置一个随机字符串来当令牌使用 session_id = random_str() session[session_id] = u.username headers['Set-Cookie'] = 'user={}'.format(session_id) # 下面是把用户名存入 cookie 中 # headers['Set-Cookie'] = 'user={}'.format(u.username) result = '登录成功' else: result = '用户名或者密码错误' else: result = '' body = template('login.html') body = body.replace('{{result}}', result) body = body.replace('{{username}}', username) header = response_with_headers(headers) r = header + '\r\n' + body log('login 的响应', r) return r.encode(encoding='utf-8')
def response_for_path(path): path, query = parsed_path(path) request.path = path request.query = query log('path and query', path, query) r = {'/static': route_static} r.update(route_dict) r.update(todo_route) response = r.get(path, error) return response(request)
def add_cookies(self): """ height=169; user=gua :return: """ cookies = self.headers.get('Cookie', '') kvs = cookies.split('; ') log('cookie', kvs) for kv in kvs: if '=' in kv: k, v = kv.split('=') self.cookies[k] = v
def find_by(cls, **kwargs): """ 用法如下,kwargs 是只有一个元素的 dict u = User.find_by(username='******') """ log('kwargs, ', kwargs) k, v = '', '' for key, value in kwargs.items(): k, v = key, value all = cls.all() for m in all: # getattr(m, k) 等价于 m.__dict__[k] if v == m.__dict__[k]: return m return None
def run(host='', port=3000): log('start at: {}, {}'.format(host, port)) with socket.socket() as s: s.bind((host, port)) while True: s.listen(5) connection, address = s.accept() r = connection.recv(1024) r = r.decode('utf-8') log('ip and request: {}, {}'.format(address, r)) if len(r.split()) < 2: continue path = r.split()[1] request.method = r.split()[0] request.add_headers(r.split('\r\n\r\n', 1)[0].split('\r\n')[1:]) request.body = r.split('\r\n\r\n', 1)[1] response = response_for_path(path) log('debug **', 'sendall') connection.sendall(response) connection.close() log('debug **', 'closed') """
def save(self): """ 用 all 方法读取文件中的所有 model 并生成一个 list 把 self 添加进去并且保存进文件 """ log('debug save') models = self.all() log('models', models) first_index = 0 if self.__dict__.get('id') is None: # 加上 id if len(models) > 0: log('用 log 可以查看代码执行的走向') # 不是第一个数据 self.id = models[-1].id + 1 else: # 是第一个数据 log('first index', first_index) self.id = first_index models.append(self) else: # 有 id 说明已经是存在于数据文件中的数据 # 那么就找到这条数据并替换之 index = -1 for i, m in enumerate(models): if m.id == self.id: index = i break # 看看是否找到下标 # 如果找到,就替换掉这条数据 if index > -1: models[index] = self # 保存 l = [m.__dict__ for m in models] path = self.db_path() save(l, path)
def route_message(request): username = current_user(request) # 如果是未登录的用户, 重定向到 '/' if username == '【游客】': log("**debug, route msg 未登录") return redirect('/') log('本次请求的 method', request.method) if request.method == 'POST': form = request.form() msg = Message.new(form) log('post', form) message_list.append(msg) # 应该在这里保存 message_list header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n' # body = '<h1>消息版</h1>' body = template('html_basic.html') msgs = '<br>'.join([str(m) for m in message_list]) body = body.replace('{{messages}}', msgs) r = header + '\r\n' + body return r.encode(encoding='utf-8')