urllib2

还有一个更好的库requests http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
requests http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

文件上传,有专门的库。也可以自己实现。

https://blog.csdn.net/xiaojianpitt/article/details/6856536

http://www.cnblogs.com/chy710/p/3791317.html

还有一种简单的方法,就是body中只放二进制数据,文件名放在url或url的参数中。Content-Type:application/octet-stream

 

Request总共三个参数,除了必须要有url参数,还有下面两个:

  1. data(默认空):是伴随 url 提交的数据(比如要post的数据),同时 HTTP 请求将从 "GET"方式 改为 "POST"方式。

  2. headers(默认空):是一个字典,包含了需要发送的HTTP报头的键值对。

#! python
#coding=utf8
import urllib2
import urllib
import time,os
def test1():
    response = urllib2.urlopen('http://127.0.0.1:5000/app/?user=111')
    html = response.read()
    print html


    req = urllib2.Request('http://127.0.0.1:5000/app/?user=222')
    req.add_header('gg', 'fff') #可以调用这个函数加header,也可以在request构造函数中加header
    response = urllib2.urlopen(req)
    html = response.read()
    print html


    req = urllib2.Request('http://127.0.0.1:5000/app/?' + urllib.urlencode({"user":"333"}))
    response = urllib2.urlopen(req)
    html = response.read()
    print html

    req = urllib2.Request('http://127.0.0.1:5000/app/?user=444',headers={'ZCODE':'555'})
    response = urllib2.urlopen(req)
    html = response.read()
    print html

    req = urllib2.Request('http://127.0.0.1:5000/app2/',data='user=555')
    req.get_method = lambda: 'PUT' # or 'DELETE'
    response = urllib2.urlopen(req)
    html = response.read()
    print html

    req = urllib2.Request('http://127.0.0.1:5000/json/',data='{"a":1,"data":"hello"}')
    response = urllib2.urlopen(req)
    html = response.read()
    print html


    ticks = time.time()
    try:
        response = urllib2.urlopen('http://127.0.0.1:5000/timeout/',timeout=5)
        html = response.read()
        print html
    except:
        print 'timeout', time.time()-ticks

用于测试的flask

 

# coding=utf8
from flask import Flask,url_for,render_template,redirect,request,send_from_directory
import werkzeug
import os,time,json

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app=Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'G:\\tudou'

# curl 127.0.0.1:5000/app/?user=888 -s
# curl 127.0.0.1:5000/app/?user=888 -H'zcode:555'
@app.route('/app/')
def hello1():
  print 'request.headers',request.headers
  print 'Host' , request.headers['Host']
  # print 'Zcode' , request.headers['Zcode']
  return 'hello world '+request.args.get('user')

# curl 127.0.0.1:5000/app2/ -d'user=888'
# curl 127.0.0.1:5000/app2/ -X PUT -d'user=888'
@app.route('/app2/',methods=['POST','PUT'])
def hello2():
  print request.method
  return 'hello world '+request.form['user']

# curl 127.0.0.1:5000/commit/gaofeng
@app.route('/commit/<name>')
def commit(name):
  print 'func hello1 is route:', url_for('hello1')
  return "%s" % name


@app.route('/timeout/')
def timeout():
    time.sleep(10)
    return "i sleep 10"


#curl http://127.0.0.1:5000/json/ -d'{"a":1,"data":"hello"}'
@app.route('/json/' , methods=['POST'])
def index():
    if request.method == 'POST':
        a = request.get_data()
        dict1 = json.loads(a)
        return json.dumps(dict1["data"])


@app.route('/up/', methods=['GET', "POST"])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = werkzeug.secure_filename(file.filename)
            print "filename",filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="/up/" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    print filename
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#print werkzeug.secure_filename('../../../../home/username/.hashrc')
if __name__=='__main__':
  app.run()

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值