【python】web开发

No1:

hello.py

def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    return [b'<h1>Hello,web!<h1>']

server.py

from wsgiref.simple_server import make_server
from hello import application

httpd = make_server('',8000,application)
print('Serving HTTP on port 8000..')
httpd.serve_forever()

执行server.py后打开浏览器

无论多么复杂的Web应用程序,入口都是一个WSGI处理函数。HTTP请求的所有输入信息都可以通过environ获得,HTTP响应的输出都可以通过start_response()加上函数返回值作为Body。

No2:

【Flask】web框架

另外

  • Django:全能型Web框架;

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

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

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

注意:py文件命名的时候不要和框架重名

运行结果

No3:

【MVC】 

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 usesrname or password',username=username)
    
if __name__ == '__main__':
    app.run()
<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>
    </from>
</body>
</html>    
<html>
<head>
    <title>Welcome,{{username}}</title>
</head>
<body>
    <p>Welcome,{{username}}!</p>
</body>
</html>

运行结果

 有了MVC,我们就分离了Python代码和HTML代码

原文地址:https://www.cnblogs.com/anni-qianqian/p/9278198.html