Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python BaseHTTPServer 介绍

$
0
0
python BaseHTTPServer 介绍

一点号数据玩家5小时前

限时干货下载:添加微信公众号“数据玩家「fbigdata」”

回复【7】免费获取【完整数据分析资料!(包括SPSS、SAS、SQL、EXCEL、Project)!】

本文针对 python 2.7 版本,介绍了 BaseHTTPServer 这个库的使用方法。

这个库是 python 自带的标准库的一部分,不需要额外安装,在 linux 系统下,位置在 /usr/lib/python2.7/BaseHTTPServer.py。

GET/HTTP/1.1

Host:cizixs.com

User-Agent:Mozilla/5.0(windowsNT6.1;WOW64;rv:42.0)Gecko/20100101Firefox/42.0

Accept:text/htmlapplication/xhtml+xmlapplication/xml;q=0.9*/*;q=0.8

Accept-Language:zh-CNzh;q=0.8en-US;q=0.5en;q=0.3

Accept-Encoding:gzipdeflate

Connection:keep-alive

If-Modified-Since:Thu25Feb201616:00:57GMT

Cache-Control:max-age=0

HTTP/1.1304NotModified

Server:GitHub.com

Date:Thu24Mar201606:21:25GMT

Last-Modified:Thu25Feb201616:00:57GMT

access-control-allow-origin: *

Expires:Thu24Mar201606:31:25GMT

Cache-Control:max-age=600

X-GitHub-Request-Id:3AF60A59:7CE3:1C889201:56F38765

data...

这个类可以帮助你快速编写一个 HTTP 服务端 server。别说了,先上代码:

fromBaseHTTPServerimportBaseHTTPRequestHandler

importcgi

importjson

classTodoHandler(BaseHTTPRequestHandler):

"""A simple TODO server

which can display and manage todos for you.

"""

# Global instance to store todos. You should use a database in reality.

TODOS=

defdo_GET(self):

# return all todos

ifself.path!='/':

self.send_error(404"File not found.")

return

# Just dump data to json, and return it

message=json.dumps(self.TODOS)

self.send_response(200)

self.send_header('Content-type''application/json')

self.end_headers

self.wfile.write(message)

defdo_POST(self):

"""Add a new todo

Only json data is supported, otherwise send a 415 response back.

Append new todo to class variable, and it will be displayed

in following get request

"""

ctypepdict=cgi.parse_header(self.headers['content-type'])

ifctype=='application/json':

length=int(self.headers['content-length'])

post_values=json.loads(self.rfile.read(length))

self.TODOS.append(post_values)

else:

self.send_error(415"Only json data is supported.")

self.wfile.write(post_values)

if__name__=='__main__':

# Start a simple server, and loop forever

fromBaseHTTPServerimportHTTPServer

server=HTTPServer(('localhost'8888),TodoHandler)

print("Starting server, use <Ctrl-C> to stop")

server.serve_forever

这段代码实现的功能很简单,就是一个简单的 Todo 管理:你可以添加 todo,也可以查询 todo。更新和删除 todo 可以根据上面的代码自行添加。

~--verbose://localhost:8888

GET/HTTP/1.1

Accept: */*

Host:localhost:8888

User-Agent:HTTPie/0.8.0

HTTP/1.0200OK

Content-type:application/json

Date:Fri25Mar201609:35:08GMT

Server:BaseHTTP/0.3Python/2.7.10

~--verbose POST://localhost:8888 content="buy a beer" finished:=false

POST/HTTP/1.1

Accept:application/json

Content-Length:44

Content-Type:application/json;

{

"content":"buy a beer"

"finished":false

}

HTTP/1.0200OK

Date:Fri25Mar201609:36:08GMT

{u'content':u'buy a beer'u'finished':False}

~--verbose POST://localhost:8888 content="learn HTTP" finished:=false

Content-Type:application/json;charset=utf-8

{

"content":

Viewing all articles
Browse latest Browse all 9596

Trending Articles