Python实现基于HTTP文件传输实例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现基于HTTP文件传输的方法。分享给大家供大家参考。具体实现方法如下:

一、问题:

因为需要最近看了一下通过POST请求传输文件的内容 并且自己写了Server和Client实现了一个简单的机遇HTTP的文件传输工具

二、实现代码:

Server端:

复制代码 代码如下:
#coding=utf-8
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
class   PostHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     }
        )
        self.send_response(200)
        self.end_headers()
        self.wfile.write('Client: %sn ' % str(self.client_address) )
        self.wfile.write('User-agent: %sn' % str(self.headers['user-agent']))
        self.wfile.write('Path: %sn'%self.path)
        self.wfile.write('Form data:n')
        for field in form.keys():
            field_item = form[field]
            filename = field_item.filename
            filevalue  = field_item.value
            filesize = len(filevalue)#文件大小(字节)
            print len(filevalue)
            with open(filename.decode('utf-8')+'a','wb') as f:
                f.write(filevalue)
        return
if __name__=='__main__':
    from BaseHTTPServer import HTTPServer
    sever = HTTPServer(('localhost',8080),PostHandler)
    print 'Starting server, use <Ctrl-C> to stop'
    sever.serve_forever()

Client端:
复制代码 代码如下:
#coding=utf-8
import requests
url = 'http://localhost:8080'
path = u'D:快盘阿狸头像.jpg'
print path
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print r.url,r.text

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python使用RNN实现文本分类

python使用RNN实现文本分类

本文实例为大家分享了使用RNN进行文本分类,python代码实现,供大家参考,具体内容如下 1、本博客项目由来是oxford 的nlp 深度学习课程第三周作业,作业要求使用LSTM进行...

python决策树之CART分类回归树详解

python决策树之CART分类回归树详解

决策树之CART(分类回归树)详解,具体内容如下 1、CART分类回归树简介   CART分类回归树是一种典型的二叉决策树,可以处理连续型变量和离散型变量。如...

Python中urllib2模块的8个使用细节分享

Python 标准库中有很多实用的工具类,但是在具体使用时,标准库文档上对使用细节描述的并不清楚,比如 urllib2 这个 HTTP 客户端库。这里总结了一些 urllib2 库的使用...

python实现图像识别功能

本文实例为大家分享了python实现图像识别的具体代码,供大家参考,具体内容如下 #! /usr/bin/env python from PIL import Image...

Python多进程multiprocessing.Pool类详解

Python多进程multiprocessing.Pool类详解

multiprocessing模块 multiprocessing包是Python中的多进程管理包。它与 threading.Thread类似,可以利用multiprocessing.P...