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

时间:2018-10-04 22:18:39

标签: python python-3.x bottle

我正在尝试创建一个允许用户将文件保存到服务器的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)

respons / 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>

1 个答案:

答案 0 :(得分:1)

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