回覆列表
  • 1 # MrWang6686

    直接上程式碼

    1、伺服器介面

    import flask, os,sys,time

    from flask import request, send_from_directory

    interface_path = os.path.dirname(__file__)

    sys.path.insert(0, interface_path) #將當前檔案的父目錄加入臨時系統變數

    server = flask.Flask(__name__)

    #get方法:指定目錄下載檔案

    @server.route("/download", methods=["get"])

    def download():

    fpath = request.values.get("path", "") #獲取檔案路徑

    fname = request.values.get("filename", "") #獲取檔名

    if fname.strip() and fpath.strip():

    print(fname, fpath)

    if os.path.isfile(os.path.join(fpath,fname)) and os.path.isdir(fpath):

    return send_from_directory(fpath, fname, as_attachment=True) #返回要下載的檔案內容給客戶端

    else:

    return "{"msg":"引數不正確"}"

    else:

    return "{"msg":"請輸入引數"}"

    # get方法:查詢當前路徑下的所有檔案

    @server.route("/getfiles", methods=["get"])

    def getfiles():

    fpath = request.values.get("fpath", "") #獲取使用者輸入的目錄

    print(fpath)

    if os.path.isdir(fpath):

    filelist = os.listdir(fpath)

    files = [file for file in filelist if os.path.isfile(os.path.join(fpath, file))]

    return "{"files":"%s"}" % files

    # post方法:上傳檔案的

    @server.route("/upload", methods=["post"])

    def upload():

    fname = request.files.get("file") #獲取上傳的檔案

    if fname:

    t = time.strftime("%Y%m%d%H%M%S")

    new_fname = r"upload/" + t + fname.filename

    fname.save(new_fname) #儲存檔案到指定路徑

    return "{"code": "ok"}"

    else:

    return "{"msg": "請上傳檔案!"}"

    server.run(port=8000, debug=True)

    2、客戶端請求

    import requests

    import os

    #上傳檔案到伺服器

    file = {"file": open("hello.txt","rb")}

    r = requests.post("http://127.0.0.1:8000/upload", files=file)

    print(r.text)

    #查詢fpath下的所有檔案

    r1 = requests.get("http://127.0.0.1:8000/getfiles",data={"fpath": r"download/"})

    print(r1.text)

    #下載伺服器download目錄下的指定檔案

    r2 = requests.get("http://127.0.0.1:8000/download",data={"filename":"hello_upload.txt", "path": r"upload/"})

    file = r2.text #獲取檔案內容

    basepath = os.path.join(os.path.dirname(__file__), r"download/")

    with open(os.path.join(basepath, "hello_download.txt"),"w",encoding="utf-8") as f: #儲存檔案

    f.write(file)

  • 中秋節和大豐收的關聯?
  • 一首英文歌,歌詞中大概有see you want(what would all)喔哦喔哦喔,歌曲結尾?