HTTP简单示例

HTTP服务端简单示例

1、flask示例代码

示例代码如下(httpServer_flask_test1.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'POST':
        print "post :",request.form
    else :
        print "get :",request.args
    return 'test data!'

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8080)

需要安装flask : pip install flask

程序启动后监听8080端口,可以通过浏览器访问: http://127.0.0.1:8080

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/httpRelate/httpServer/httpServer_flask_test1.py

HTTP客户端简单示例

1、urllib get示例代码

示例代码如下(urllib_get.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import urllib

f=urllib.urlopen("http://127.0.0.1:8080")
s=f.read()
print s

params = urllib.urlencode({'id': 1, 'name': 'mike'})
f = urllib.urlopen("http://127.0.0.1:8080?%s" % params)
print f.read()

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/httpRelate/httpClient/urllib_get.py

2、urllib post示例代码

示例代码如下(urllib_post.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import urllib

params = urllib.urlencode({'id': 1, 'name': 'mike'})
f = urllib.urlopen("http://127.0.0.1:8080",params)
print f.read()

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/httpRelate/httpClient/urllib_post.py