在Python的web框架中编写创建日志的程序的教程 在Web开发中,后端代码写起来其实是相当容易的。 例如,我们编写一个REST API,用于创建一个Blog: @api @post('/api/blogs') def api_create_blog(): i = ctx.request.input(name='', summary='', content='') name = i.name.strip() summary = i.summary.strip() content = i.content.strip() if not name: raise APIValueError('name', 'name cannot be empty.') if not summary: raise APIValueError('summary', 'summary cannot be empty.') if not content: raise APIValueError('content', 'content cannot be empty.') user = ctx.request.user blog = Blog(user_id=user.id, user_name=user.name, name=name, summary=summary, content=content) blog.insert() return blog 编写后端Python代码不但很简单,而且非常容易测试,上面的API:api_create_blog()本身只是一个普通函数。 Web开发真正困难的地方在于编写前端页面。前端页面需要混合HTML、CSS和JavaScript,如果对这三者没有深入地掌握,编写的前端页面将很快难以维护。 更大的问题在于,前端页面通常是动态页面,也就是说,前端页面往往是由后端代码生成的。 生成前端页面最早的方式是拼接字符串: s = '' + title + '' + body + '' 显然这种方式完全不具备可维护性。所以有第二种模板方式: