Python之学习笔记(web服务)

WSGI

# -*- coding: utf-8 -*-

'''
web开发简介:
    静态Web页面:由文本编辑器直接编辑并生成静态的HTML页面,如果要修改Web页面的内容,就需要再次编辑HTML源文件,早期的互联网Web页面就是静态的;
    CGI:由于静态Web页面无法与用户交互,比如用户填写了一个注册表单,静态Web页面就无法处理。要处理用户发送的动态数据,出现了Common Gateway Interface,简称CGI,用C/C++编写。
    ASP/JSP/PHP:由于Web应用特点是修改频繁,用C/C++这样的低级语言非常不适合Web开发,而脚本语言由于开发效率高,与HTML结合紧密,因此,迅速取代了CGI模式。ASP是微软推出的用VBScript脚本编程的Web开发技术,而JSP用Java来编写脚本,PHP本身则是开源的脚本语言。
    MVC:为了解决直接用脚本语言嵌入HTML导致的可维护性差的问题,Web应用也引入了Model-View-Controller的模式,来简化Web开发。ASP发展为ASP.Net,JSP和PHP也有一大堆MVC框架。
    现在都是BS架构,之前是CS架构
    使用WSGI:WSGI:Web Server Gateway Interface
    需要一个函数来响应HTTP请求
'''
# environ:包含了所有HTTP请求消息的dict对象
# start_response:发送HTTP响应的函数
# 注意Header只能发送一次,也就是只能调用一次start_response()函数。
# start_response()函数接收两个参数,一个是HTTP响应码,一个是一组list表示的HTTP Header,
# 每个Header用一个包含两个str的tuple表示
def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    # return '<h1>Hello,web!</h1>'
    return '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
'''
如何从environ这个dict对象拿到HTTP请求信息,
然后构造HTML,通过start_response()发送Header,
最后返回Body。
'''
# WSGI服务器有很多,选择一个简单进行实现
# 无论多么复杂的Web应用程序,入口都是一个WSGI处理函数。
# HTTP请求的所有输入信息都可以通过environ获得,
# HTTP响应的输出都可以通过start_response()加上函数返回值作为Body
# -*- coding: utf-8 -*-

# server.py
# 从wsgiref模块导入:
from wsgiref.simple_server import make_server
# 导入我们自己编写的application函数:
from web_app import application

# 创建一个服务器,IP地址为空,端口是8000,处理函数是application:
httpd = make_server('', 8090, application)
print "Serving HTTP on port 8000..."
# 开始监听HTTP请求:
httpd.serve_forever()

# 打开http://localhost:8090看效果
# 如遇到10013错误那么就是端口被占用,可以修改成别的

web框架

# -*- coding: utf-8 -*-

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']=='cy' and request.form['password']=='12345':
        return '<h3>Hello, admin!</h3>'
    return '<h3>Bad username or password.</h3>'

if __name__ == '__main__':
    app.run()


# web开发的框架

# Flask,常见的Python Web框架还有:

# Django:全能型Web框架;

# web.py:一个小巧的Web框架;

# Bottle:和Flask类似的Web框架;

# Tornado:Facebook的开源异步Web框架。

模板

# -*- coding: utf-8 -*-

from flask import Flask,request,render_template 

# MVC:Model-View-Controller,中文名“模型-视图-控制器”
'''
处理URL的函数就是C:Controller,Controller负责业务逻辑,比如检查用户名是否存在,取出用户信息等等;

包含变量{{ name }}的模板就是V:View,View负责显示逻辑,通过简单地替换一些变量,View最终输出的就是用户看到的HTML。

Model是用来传给View的,这样View在替换变量的时候,就可以从Model中取出相应的数据。

有时候Model就是一个dict
'''

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

# 使用的模板
# Jinja2:用{% ... %}
# Mako:用<% ... %>和${xxx}的一个模板
# Cheetah:也是用<% ... %>和${xxx}的一个模板 
# Django:Django是一站式框架,内置一个用{% ... %}和{{ xxx }}的模板
<html>
<head>
  <title>Home</title>
</head>
<body>
  <h1 style="font-style:italic">Home</h1>
</body>
</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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值