mac python学习开发简单入门

安装

  • Mac自带python 在/usr/bin/python
  • 进入终端直接键入python即可进入交互模式
  • 或是python xxx.py 运行 写好的python程序
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.
>>> 

浏览器访问

  • 在任意地方新建文件夹
  • 切换到该文件夹中新建一个简单的html文件
  • 然后执行python -m SimpleHTTPServer 8080
  • 8080端口号 默认8000
  • 然后浏览器访问http://localhost:8080/test.html
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
  • 检查端口是否冲突
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值