werkzurg
先看看werkzurg
的两个简单示例#示例一:还需要对请求,响应作处理
from werkzeug.serving import run_simple
def run(environ,start_response):
return [b"asdfasdf"]
if __name__ == '__main__':
run_simple('localhost', 4000, run) #第三个参数除了填函数名外,还可以填类的对象名,若为对象名,在执行时会执行,对象(),此时会调用类对象中的__call__方法
#示例一:已经对请求做了处理
from werkzeug.wrappers import Response
from werkzeug.serving import run_simple
def run_server(environ, start_response):
response = Response('hello')
return response(environ, start_response)
if __name__ == '__main__':
run_simple('127.0.0.1', 8000, run_server)
#示例二:
from werkzeug.wrappers import Request, Response
@Request.application
def hello(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, hello)
补充:在对象后加括号会执行什么
class Foo(object):
def __init__(self):
print('sdfsdf')
def __call__(self, *args, **kwargs):
print('call')
obj = Foo()
obj()
#执行结果
sdfsdf
call
结果说明了对象名()
会执行类中__call__
方法
下面是wsgiref模块示例,为django框架依赖
wsgiref示例:
from wsgiref.simple_server import make_server
def run_server(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]
if __name__ == '__main__':
httpd = make_server('127.0.0.1', 8000, run_server)
httpd.serve_forever()
pip3 install flask
from flask import Flask #导入flask
app = Flask(__name__) #创建app对象
@app.route('/index')
def index():
return "Hello World"
if __name__ == '__main__':
app.run() #如果启动为主函数,开启flask
#执行结果
"D:\Python 3.7.1\python.exe" "D:/BaiduYunDownload/python 学习/flask/day114课上所有/s9day114/s4.py"
* Serving Flask app "s4" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
程序已经启动,访问本地网址http://127.0.0.1:5000/index
试试,发现已经可以显示出helloworld