python-基础-web开发方式

web开发

Web应用BS架构
Web开发的阶段:

  • 静态Web页面:文本编辑器编辑HTML页面
  • CGI:Common Gateway Interface处理动态数据
  • ASP/JSP/PHP:脚本语言开发
  • MVC:Model-View-Controller不嵌入脚本

新的MVVM前段技术

WSGI

Web应用的本质

  • 浏览器发送一个HTTP请求;
  • 服务器收到请求,生成一个HTML文档;
  • 服务器把HTML文档作为HTTP响应的Body发送给浏览器;
  • 浏览器收到HTTP响应,从HTTP Body取出HTML文档并显示。

WSGI实际是一个网关,网关的作用就是在协议之间进行转换,是服务器和APP之间的低级别接口;
Flask,webpy,Django、CherryPy都内置了自己的WSGI,但是性能都不好;
WSGI中间件同时实现API的两方,可以执行一下功能:

  • 重写环境变量后,根据目标URL,将请求消息路由到不同的应用对象。
  • 允许在一个进程中同时运行多个应用程序或应用框架。
  • 负载均衡和远程处理,通过在网络上转发请求和响应消息。
  • 进行内容后处理,例如应用XSLT样式表。

使用例子:

from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain')]

    start_response(status, headers)

    ret = ["%s: %s\n" % (key, value)
           for key, value in environ.iteritems()]
    return ret

httpd = make_server('', 8000, simple_app)
print "Serving on port 8000..."
httpd.serve_forever()

simple_app()函数就是WSGI标准的HTTP处理函数
接收参数

  • environ包含所有请求的dict对象
  • start_response发送HTTP响应的函数

start_response接收来个参数,第一个是响应码,第二个是HTTP Header,调用的函数由WSGI服务器提供;
simple_app函数只能由服务器调用

web框架

WSGI就是针对每个HTTP请求都编写一个响应,如何处理多个url呢;
可以从environ中提取HTTP信息

def application(environ, start_response):
    method = environ['REQUEST_METHOD']
    path = environ['PATH_INFO']
    if method=='GET' and path=='/':
        return handle_home(environ, start_response)
    if method=='POST' and path='/signin':
        return handle_signin(environ, start_response)
    ...

Web进一步抽象,在WSGI之上加入了一个函数处理一个RUL的逻辑,这个映射关系交给web框架
除了flask其他的框架还有

  • Django:全能型Web框架;
  • web.py:一个小巧的Web框架;
  • Bottle:和Flask类似的Web框架;
  • Tornado:Facebook的开源异步Web框架

获取HTTP数据具有自己的方法,比如flask通过request.form['name']获取表单数据

使用模板

预先准备一个HTML文档,嵌入一些变量和指令
Flask通过render_template()渲染模板,默认使用jinja2模板

from 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()

home.html

<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1 style="font-style:italic">Home</h1>
</body>
</html>

form.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>

signin-ok.html

<html>
<head>
  <title>Welcome, {{ username }}</title>
</head>
<body>
  <p>Welcome, {{ username }}!</p>
</body>
</html>

其他的常用模板

  • Mako:用<% ... %>和${xxx}的一个模板;
  • Cheetah:也是用<% ... %>和${xxx}的一个模板;
  • Django:Django是一站式框架,内置一个用{% ... %}和{{ xxx }}的模板
posted @ 2016-11-25 20:08  zhangshihai1232  阅读(122)  评论(0)    收藏  举报