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 add_cookies(self): 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 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(1000) r = r.decode('utf-8') log('原始请求', r) log('ip and request, {}\n{}'.format(address, request)) if len(r.split()) < 2: continue path = r.split()[1] log('path', path) # 设置 request 的 method request.method = r.split()[0] # 把 body 放入 request 中 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_for_path 函数来得到 path 对应的响应内容 response = response_for_path(path) connection.sendall(response) connection.close()
def response_for_path(path): # parsed_path 用于把 path 和 query 分离 path, query = parsed_path(path) request.path = path request.query = query log('path and query', path, query) r = { '/static': route_static, # '/': route_index, # '/login': route_login, # '/messages': route_message, } r.update(route_dict) response = r.get(path, error) return response(request) # why?
def route_message(request): """ 消息页面的路由函数 """ username = current_user(request) if username == '【游客】': log("**debug, route msg 未登录") pass 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')
def save(self): models = self.all() log('models', models) first_index = 0 if self.__dict__.get('id') is None: 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: 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 save(data, path): s = json.dumps(data, indent=2, ensure_ascii=False) with open(path, 'w+', encoding='utf-8') as f: log('save', path, s, data) f.write(s)
def load(path): with open(path, 'r', encoding='utf-8') as f: s = f.read() log('load', s) return json.loads(s)