Errno 2 没有这样的文件或目录:'/storage/test.txt'

Errno 2 No such file or directory: '/storage/test.txt'

我正在尝试创建一个允许用户将文件保存到服务器的 Bottle 服务器(我知道这有一个很大的安全漏洞,稍后添加一个身份验证系统)。当我尝试使用网页保存文件时,出现此错误。 [Errno 2] No such file or directory: '/storage/test.txt'

main.py

from bottle import *

class File():
  def __init__(self, Path):
    self.Path = Path
  def read(self):
    self.File = open(self.Path, 'r')
    return [self.File.read(), self.File.close()][0]

@route('/')
def Request():
  return File('responses/index.html').read()

@route('/actions/save')
def Request():
  return File('responses/actions/save/index.html').read()

@route('/actions/save', method='POST')
def Request():
  Source =  request.forms.get('source')
  Path =    request.forms.get('path')
  try:
    FileObj =  open('/storage/{}'.format(Path), 'w')
    FileObj.write(Source)
    FileObj.close()
    return File('responses/actions/save/ok.html').read()
  except Exception as Message:
    return File('responses/actions/save/error.html').read().format(Message=Message)

if __name__ == '__main__':
  run(host='0.0.0.0', port=8000)

responses/actions/save/index.html

  <html>
    <head>
      <link rel="stylesheet" href="/style/index.css">
      <title>Save File</title>
    </head>
    <body>
      <h1>Save File</h1>
      <form action="/actions/save" method="post">
        <textarea name="source" cols="40" rows="10"></textarea><br>
        Path: <input type="text" name="path" value="/public"><br>
        <input type="submit" value="Submit">
      </form>
    </body>
  </html>

index.html

<html>
    <head>
      <link rel="stylesheet" href="/style/index.css">
      <title>POSTRun</title>
    </head>
    <body>
      <h1>PostRun</h1>
      <a href='/actions/save'>Save File</a>
    </body>
  </html>

Bottle 正在处理相对于服务器根目录的路径,例如@route('/actions/save')。但是 open 是一个 python 运算符,并且在您的系统上指定了一个路径。将 open('/storage/{}'.format(Path), 'w') 更改为相对于您的 python 解释器的存储文件路径(例如 storage/{}