- 在后台,Http服务器做的工作就是获取http请求,解析请求,用html文件作为body部分做http响应。wsgi的定义很简单,就是要求web应用开发者实现一个函数来响应Http请求。wsgi对于web应用开发者,屏蔽了http请求、解析,使其可专注于html文件的动态生成等业务逻辑。常用的静态服务器软件Apache、Nginx、Lighttpd等,python内置了一个wsg服务器,作为开发用。
def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '<h1>Hello, web!</h1>'
- web框架使开发者专注于处理各个的URL,写各个URL处理函数。python框架有flask、django、web.py、bottle、tornado等。其中tornado是facebook的开源异步web框架。
from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): return '<h1>Home</h1>' @app.route('/signin', methods=['GET']) def signin_form(): return '''<form action="/signin" method="post"> <p><input name="username"></p> <p><input name="password" type="password"></p> <p><button type="submit">Sign In</button></p> </form>''' @app.route('/signin', methods=['POST']) def signin(): # 需要从request对象读取表单内容: if request.form['username']=='admin' and request.form['password']=='password': return '<h3>Hello, admin!</h3>' return '<h3>Bad username or password.</h3>' if __name__ == '__main__': app.run()
- 模板。把python代码和html代码分开,其中html代码放到模板中,python代码专注于实现model(Http请求中涉及到要传递到模板中的数据)和controller(URL处理函数)。实例使用jinja2模板。
home.htmlfrom flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): return render_template('home.html') @app.route('/signin', methods=['GET']) def signin_form(): return render_template('form.html') @app.route('/signin', methods=['POST']) def signin(): username = request.form['username'] password = request.form['password'] if username=='admin' and password=='password': return render_template('signin-ok.html', username=username) return render_template('form.html', message='Bad username or password', username=username) if __name__ == '__main__': app.run()
form.html<html> <head> <title>Home</title> </head> <body> <h1 style="font-style:italic">Home</h1> </body> </html>
signin-ok.html<html> <head> <title>Please Sign In</title> </head> <body> {% if message %} <p style="color:red">{{ message }}</p> {% endif %} <form action="/signin" method="post"> <legend>Please sign in:</legend> <p><input name="username" placeholder="Username" value="{{ username }}"></p> <p><input name="password" placeholder="Password" type="password"></p> <p><button type="submit">Sign In</button></p> </form> </body> </html>
<html> <head> <title>Welcome, {{ username }}</title> </head> <body> <p>Welcome, {{ username }}!</p> </body> </html>
除了Jinja2,常见的模板还有:
读书笔记:关于wsgi、web框架和模板的总结(python)
最新推荐文章于 2025-06-12 10:20:02 发布