发布时间:2019-08-24 09:21:16编辑:auto阅读(1267)
安装
Last login: Sat Aug 19 20:33:28 on ttys001
yangzhehaodeMacBook:~ yangzhehao$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
浏览器访问
Last login: Sat Aug 19 19:56:28 on ttys000
yangzhehaodeMacBook:~ yangzhehao$ cd Python/
yangzhehaodeMacBook:Python yangzhehao$ python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8080 ...
127.0.0.1 - - [19/Aug/2017 20:10:25] "GET / HTTP/1.1" 200 -
一个最简单的web服务器
python给我们提供了一个接口:WSGI:Web Server Gateway Interface 它只要求Web开发者实现一个函数,就可以响应HTTP请求。而不用触到TCP连接、HTTP原始请求和响应格式。
下面实例一个最简单的web应用 - 两个文件
# hello.py
#environ:一个包含所有HTTP请求信息的dict对象;
#start_response:一个发送HTTP响应的函数。
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'<h1>Hello, web!</h1>']
# server.py
# 从wsgiref模块导入:
from wsgiref.simple_server import make_server
# 导入我们自己编写的application函数:
from hello import application
# 创建一个服务器,IP地址为空,端口是8080,处理函数是application:
httpd = make_server('', 8080, application)
print('Serving HTTP on port 8080...')
# 开始监听HTTP请求:
httpd.serve_forever()
将这两个文件放在同一个文件夹中,运行server.py , 然后浏览器访问http://localhost:8080
yangzhehaodeMacBook:Python yangzhehao$ python server.py
Serving HTTP on port 8080...
127.0.0.1 - - [19/Aug/2017 22:26:57] "GET / HTTP/1.1" 200 20
就能在浏览器看到 Hello, web!
无法运行错误处理
#coding:utf-8
上一篇: Python处理带timezone的da
下一篇: python 调用接口造数据
46403
44289
35742
33296
28000
24567
23495
18711
17952
16642
4471°
5035°
4562°
4707°
5370°
4328°
4383°
4933°
4826°
6066°