国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

python3 簡(jiǎn)易 http server:實(shí)現(xiàn)本地與遠(yuǎn)程服務(wù)器傳大文件

這篇具有很好參考價(jià)值的文章主要介紹了python3 簡(jiǎn)易 http server:實(shí)現(xiàn)本地與遠(yuǎn)程服務(wù)器傳大文件。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

在個(gè)人目錄下創(chuàng)建新文件httpserver.py

vim httpserver.py

文件內(nèi)容為python3代碼:

# !/usr/bin/env python3
import datetime
import email
import html
import http.server
import io
import mimetypes
import os
import posixpath
import re
import shutil
import sys
import urllib.error
import urllib.parse
import urllib.request
from http import HTTPStatus

__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]


class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    server_version = "SimpleHTTP/" + __version__
    extensions_map = _encodings_map_default = {
        '.gz': 'application/gzip',
        '.Z': 'application/octet-stream',
        '.bz2': 'application/x-bzip2',
        '.xz': 'application/x-xz',
    }

    def __init__(self, *args, directory=None, **kwargs):
        if directory is None:
            directory = os.getcwd()
        self.directory = os.fspath(directory)
        super().__init__(*args, **kwargs)

    def do_GET(self):
        f = self.send_head()
        if f:
            try:
                self.copyfile(f, self.wfile)
            finally:
                f.close()

    def do_HEAD(self):
        f = self.send_head()
        if f:
            f.close()

    def send_head(self):
        path = self.translate_path(self.path)
        f = None
        if os.path.isdir(path):
            parts = urllib.parse.urlsplit(self.path)
            if not parts.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(HTTPStatus.MOVED_PERMANENTLY)
                new_parts = (parts[0], parts[1], parts[2] + '/',
                             parts[3], parts[4])
                new_url = urllib.parse.urlunsplit(new_parts)
                self.send_header("Location", new_url)
                self.end_headers()
                return None
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)

        ctype = self.guess_type(path)
        if path.endswith("/"):
            self.send_error(HTTPStatus.NOT_FOUND, "File not found")
            return None
        try:
            f = open(path, 'rb')
        except OSError:
            self.send_error(HTTPStatus.NOT_FOUND, "File not found")
            return None
        try:
            fs = os.fstat(f.fileno())
            # Use browser cache if possible
            if ("If-Modified-Since" in self.headers
                    and "If-None-Match" not in self.headers):
                # compare If-Modified-Since and time of last file modification
                try:
                    ims = email.utils.parsedate_to_datetime(self.headers["If-Modified-Since"])
                except (TypeError, IndexError, OverflowError, ValueError):
                    # ignore ill-formed values
                    pass
                else:
                    if ims.tzinfo is None:
                        # obsolete format with no timezone, cf.
                        # https://tools.ietf.org/html/rfc7231#section-7.1.1.1
                        ims = ims.replace(tzinfo=datetime.timezone.utc)
                    if ims.tzinfo is datetime.timezone.utc:
                        # compare to UTC datetime of last modification
                        last_modif = datetime.datetime.fromtimestamp(
                            fs.st_mtime, datetime.timezone.utc)
                        # remove microseconds, like in If-Modified-Since
                        last_modif = last_modif.replace(microsecond=0)

                        if last_modif <= ims:
                            self.send_response(HTTPStatus.NOT_MODIFIED)
                            self.end_headers()
                            f.close()
                            return None

            self.send_response(HTTPStatus.OK)
            self.send_header("Content-type", ctype)
            self.send_header("Content-Length", str(fs[6]))
            self.send_header("Last-Modified",
                             self.date_time_string(fs.st_mtime))
            self.end_headers()
            return f
        except:
            f.close()
            raise

    def list_directory(self, path):
        try:
            list_dir = os.listdir(path)
        except OSError:
            self.send_error(HTTPStatus.NOT_FOUND, "No permission to list_dir directory")
            return None
        list_dir.sort(key=lambda a: a.lower())
        r = []
        try:
            display_path = urllib.parse.unquote(self.path, errors='surrogatepass')
        except UnicodeDecodeError:
            display_path = urllib.parse.unquote(path)
        display_path = html.escape(display_path, quote=False)
        enc = sys.getfilesystemencoding()

        form = """
            <h1>文件上傳</h1>\n
            <form ENCTYPE="multipart/form-data" method="post">\n
                <input name="file" type="file"/>\n
                <input type="submit" value="upload"/>\n
            </form>\n"""
        title = 'Directory listing for %s' % display_path
        r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
                 '"http://www.w3.org/TR/html4/strict.dtd">')
        r.append('<html>\n<head>')
        r.append('<meta http-equiv="Content-Type" '
                 'content="text/html; charset=%s">' % enc)
        r.append('<title>%s</title>\n</head>' % title)
        r.append('<body>%s\n<h1>%s</h1>' % (form, title))
        r.append('<hr>\n<ul>')
        for name in list_dir:
            fullname = os.path.join(path, name)
            displayname = linkname = name
            # Append / for directories or @ for symbolic links
            if os.path.isdir(fullname):
                displayname = name + "/"
                linkname = name + "/"
            if os.path.islink(fullname):
                displayname = name + "@"
                # Note: a link to a directory displays with @ and links with /
            r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(linkname, errors='surrogatepass'),
                                                       html.escape(displayname, quote=False)))
        r.append('</ul>\n<hr>\n</body>\n</html>\n')
        encoded = '\n'.join(r).encode(enc, 'surrogate escape')
        f = io.BytesIO()
        f.write(encoded)
        f.seek(0)
        self.send_response(HTTPStatus.OK)
        self.send_header("Content-type", "text/html; charset=%s" % enc)
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        return f

    def translate_path(self, path):
        # abandon query parameters
        path = path.split('?', 1)[0]
        path = path.split('#', 1)[0]
        # Don't forget explicit trailing slash when normalizing. Issue17324
        trailing_slash = path.rstrip().endswith('/')
        try:
            path = urllib.parse.unquote(path, errors='surrogatepass')
        except UnicodeDecodeError:
            path = urllib.parse.unquote(path)
        path = posixpath.normpath(path)
        words = path.split('/')
        words = filter(None, words)
        path = self.directory
        for word in words:
            if os.path.dirname(word) or word in (os.curdir, os.pardir):
                # Ignore components that are not a simple file/directory name
                continue
            path = os.path.join(path, word)
        if trailing_slash:
            path += '/'
        return path

    def copyfile(self, source, outputfile):
        shutil.copyfileobj(source, outputfile)

    def guess_type(self, path):
        base, ext = posixpath.splitext(path)
        if ext in self.extensions_map:
            return self.extensions_map[ext]
        ext = ext.lower()
        if ext in self.extensions_map:
            return self.extensions_map[ext]
        guess, _ = mimetypes.guess_type(path)
        if guess:
            return guess
        return 'application/octet-stream'

    def do_POST(self):
        r, info = self.deal_post_data()
        self.log_message('%s, %s => %s' % (r, info, self.client_address))
        enc = sys.getfilesystemencoding()
        res = [
            '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
            '"http://www.w3.org/TR/html4/strict.dtd">',
            '<html>\n<head>',
            '<meta http-equiv="Content-Type" content="text/html; charset=%s">' % enc,
            '<title>%s</title>\n</head>' % "Upload Result Page",
            '<body><h1>%s</h1>\n' % "Upload Result"
        ]
        if r:
            res.append('<p>SUCCESS: %s</p>\n' % info)
        else:
            res.append('<p>FAILURE: %s</p>' % info)
        res.append('<a href=\"%s\">back</a>' % self.headers['referer'])
        res.append('</body></html>')
        encoded = '\n'.join(res).encode(enc, 'surrogate escape')
        f = io.BytesIO()
        f.write(encoded)
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(length))
        self.end_headers()
        if f:
            self.copyfile(f, self.wfile)
            f.close()

    def deal_post_data(self):
        content_type = self.headers['content-type']
        if not content_type:
            return False, "Content-Type header doesn't contain boundary"
        boundary = content_type.split("=")[1].encode()
        remain_bytes = int(self.headers['content-length'])
        line = self.rfile.readline()
        remain_bytes -= len(line)
        if boundary not in line:
            return False, "Content NOT begin with boundary"
        line = self.rfile.readline()
        remain_bytes -= len(line)
        fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line.decode())
        if not fn:
            return False, "Can't find out file name..."
        path = self.translate_path(self.path)
        fn = os.path.join(path, fn[0])
        line = self.rfile.readline()
        remain_bytes -= len(line)
        line = self.rfile.readline()
        remain_bytes -= len(line)
        try:
            out = open(fn, 'wb')
        except IOError:
            return False, "Can't create file to write, do you have permission to write?"

        preline = self.rfile.readline()
        remain_bytes -= len(preline)
        while remain_bytes > 0:
            line = self.rfile.readline()
            remain_bytes -= len(line)
            if boundary in line:
                preline = preline[0:-1]
                if preline.endswith(b'\r'):
                    preline = preline[0:-1]
                out.write(preline)
                out.close()
                return True, "File '%s' upload success!" % fn
            else:
                out.write(preline)
                preline = line
        return False, "Unexpect Ends of data."


if __name__ == '__main__':
    try:
        port = int(sys.argv[1])
    except Exception:
        port = 8000
        print('-------->> Warning: Port is not given, will use deafult port: 8000 ')
        print('-------->> if you want to use other port, please execute: ')
        print('-------->> python SimpleHTTPServerWithUpload.py port ')
        print("-------->> port is a integer and it's range: 1024 < port < 65535 ")

    http.server.test(
        HandlerClass=SimpleHTTPRequestHandler,
        ServerClass=http.server.HTTPServer,
        port=port
    )

在需要暴露的目錄下啟動(dòng)http服務(wù),如/data/codes/

cd /data/codes/
python3 httpserver.py 8888

隨后在個(gè)人電腦訪問http://ip:8888即可瀏覽文件、上傳文件:
python3 簡(jiǎn)易 http server:實(shí)現(xiàn)本地與遠(yuǎn)程服務(wù)器傳大文件,運(yùn)維:Liunx系統(tǒng)&amp;環(huán)境搭建&amp;Web開發(fā),http,服務(wù)器,網(wǎng)絡(luò)協(xié)議文章來源地址http://www.zghlxwxcb.cn/news/detail-716340.html

到了這里,關(guān)于python3 簡(jiǎn)易 http server:實(shí)現(xiàn)本地與遠(yuǎn)程服務(wù)器傳大文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • http-server使用,啟動(dòng)本地服務(wù)器 & 使用serve包本地啟動(dòng)

    http-server使用,啟動(dòng)本地服務(wù)器 & 使用serve包本地啟動(dòng)

    http-server使用,啟動(dòng)本地服務(wù)器 使用serve包本地啟動(dòng) 直接打開html文件,跨域不渲染圖片 1、簡(jiǎn)介 官網(wǎng):https://github.com/http-party/http-server http-server是一個(gè)簡(jiǎn)單的零配置命令行 http服務(wù)器 。 它足夠強(qiáng)大,足以用于生產(chǎn)用途,但它既簡(jiǎn)單又易于破解,可用于測(cè)試,本地開發(fā)和學(xué)習(xí)。

    2024年02月02日
    瀏覽(30)
  • 本地開發(fā) npm 好用的http server、好用的web server、靜態(tài)服務(wù)器

    本地開發(fā) npm 好用的http server、好用的web server、靜態(tài)服務(wù)器

    有時(shí)需要快速啟動(dòng)一個(gè)web 服務(wù)器(http服務(wù)器)來伺服靜態(tài)網(wǎng)頁,安裝nginx又太繁瑣,那么可以考慮使用npm serve、http-server、webpack-dev-server。 npm 的serve可以提供給http server功能, 如果你想提供 靜態(tài)站點(diǎn) 、 單頁面應(yīng)用 或者 靜態(tài)文件 甚至羅列文件夾的內(nèi)容服務(wù),那么npm serve 是

    2024年02月14日
    瀏覽(27)
  • 如何用python搭建簡(jiǎn)易的http/https服務(wù)器

    如何用python搭建簡(jiǎn)易的http/https服務(wù)器

    如何用python搭建簡(jiǎn)易的http/https服務(wù)器? 首先安裝個(gè)ubuntu 22.04.3, 這個(gè)時(shí)候就已經(jīng)能用python起http服務(wù)器了, sudo python3 -m http.server, 發(fā)現(xiàn)默認(rèn)起的http服務(wù)器的端口是8000, 瀏覽器訪問確認(rèn), 想用標(biāo)準(zhǔn)的80端口需要加參數(shù),sudo python3 -m http.server 80, 瀏覽器訪問確認(rèn), 起https服務(wù)

    2024年04月12日
    瀏覽(21)
  • [Python3]爬蟲HTTP Error 500錯(cuò)誤,報(bào)錯(cuò)信息:urllib.error.HTTPError: HTTP Error 500: INTERNAL SERVER ERROR

    [Python3]爬蟲HTTP Error 500錯(cuò)誤,報(bào)錯(cuò)信息:urllib.error.HTTPError: HTTP Error 500: INTERNAL SERVER ERROR

    之后報(bào)下面的錯(cuò)誤: 發(fā)現(xiàn)報(bào)錯(cuò)代碼: 修改代碼: 運(yùn)行成功: 爬到的數(shù)據(jù):

    2024年02月16日
    瀏覽(27)
  • python:http.server --- HTTP 服務(wù)器

    HTTPServer 是 socketserver.TCPServer 的一個(gè)子類。它會(huì)創(chuàng)建和偵聽 HTTP 套接字,并將請(qǐng)求分發(fā)給處理程序。創(chuàng)建和運(yùn)行 HTTP 服務(wù)器的代碼類似如下所示: 該類基于 TCPServer 類,并在實(shí)例變量 server_name 和 server_port 中保存 HTTP 服務(wù)器地址。處理程序可通過實(shí)例變量 server 訪問 HTTP 服務(wù)器

    2024年02月08日
    瀏覽(26)
  • python3:四種常見方式從遠(yuǎn)程服務(wù)器下載文件(paramiko、requests、wget、urllib2)

    下載一個(gè)文件夾時(shí),便可以使用這個(gè)方法, paramiko模塊提供了ssh及sftp進(jìn)行遠(yuǎn)程登錄服務(wù)器執(zhí)行命令和上傳下載文件的功能。這是一個(gè)第三方的軟件包,使用之前需要先進(jìn)行安裝 默認(rèn)會(huì)立即下載文件內(nèi)容并保存到內(nèi)存中,如果文件很大,會(huì)給內(nèi)存造成壓力 如果文件很大,會(huì)給

    2024年02月16日
    瀏覽(27)
  • Python中啟動(dòng)HTTP服務(wù)器的命令python -m http.server

    python -m http.server ? 是一個(gè)在Python中啟動(dòng) HTTP服務(wù)器 的命令, 它允許你在本地計(jì)算機(jī)上快速搭建一個(gè)簡(jiǎn)單的HTTP服務(wù)器。 1. 打開終端或命令提示符窗口。 2. 導(dǎo)航到你要在服務(wù)器上共享的目錄。例如,如果你想共享名為\\\"my_folder\\\"的目錄,可以使用? cd ?命令(在Windows上)或? cd

    2024年02月06日
    瀏覽(32)
  • [Python http.server] 搭建http服務(wù)器用于下載/上傳文件

    [Python http.server] 搭建http服務(wù)器用于下載/上傳文件

    動(dòng)機(jī): 筆者需測(cè)試bs架構(gòu)下的文件上傳與下載性能,故想通過Python搭建http服務(wù)器并實(shí)現(xiàn)客戶端與服務(wù)器之間的文件上傳和下載需求 難點(diǎn): 這應(yīng)該是很基礎(chǔ)的東西,不過筆者之前未接觸過http編程,謹(jǐn)在此記錄下學(xué)習(xí)的過程,可能不是最優(yōu)解 方法: 在服務(wù)器端部署html頁面,并

    2024年02月11日
    瀏覽(18)
  • FastDFS+Nginx搭建本地服務(wù)器并實(shí)現(xiàn)遠(yuǎn)程訪問

    FastDFS+Nginx搭建本地服務(wù)器并實(shí)現(xiàn)遠(yuǎn)程訪問

    FastDFS是一個(gè)開源的輕量級(jí)分布式文件系統(tǒng),它對(duì)文件進(jìn)行管理,功能包括:文件存儲(chǔ)、文件同步、文件訪問(文件上傳、文件下載)等,解決了大容量存儲(chǔ)和負(fù)載均衡的問題。特別適合以文件為載體的在線服務(wù),如相冊(cè)網(wǎng)站、視頻網(wǎng)站等等。 FastDFS為互聯(lián)網(wǎng)量身定制,充分考

    2024年02月06日
    瀏覽(28)
  • IDEA實(shí)現(xiàn)ssh遠(yuǎn)程連接本地Linux服務(wù)器

    IDEA實(shí)現(xiàn)ssh遠(yuǎn)程連接本地Linux服務(wù)器

    本文主要介紹如何在IDEA中設(shè)置遠(yuǎn)程連接服務(wù)器開發(fā)環(huán)境,并結(jié)合Cpolar內(nèi)網(wǎng)穿透工具實(shí)現(xiàn)無公網(wǎng)遠(yuǎn)程連接,然后實(shí)現(xiàn)遠(yuǎn)程Linux環(huán)境進(jìn)行開發(fā)。 IDEA的遠(yuǎn)程開發(fā)功能,可以將本地的編譯、構(gòu)建、調(diào)試、運(yùn)行等工作都放在遠(yuǎn)程服務(wù)器上執(zhí)行,而本地僅運(yùn)行客戶端軟件進(jìn)行常規(guī)的開發(fā)

    2024年02月22日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包